gemi 0.187.0 → 0.189.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +23 -23
- package/dist/ai/index.js.map +5 -5
- package/dist/ai/providers/call.d.ts +9 -0
- package/dist/ai/providers/call.d.ts.map +1 -1
- package/dist/ai/providers/endpoints.d.ts +32 -2
- package/dist/ai/providers/endpoints.d.ts.map +1 -1
- package/dist/ai/providers/errors.d.ts +9 -0
- package/dist/ai/providers/errors.d.ts.map +1 -1
- package/dist/ai/providers/http.d.ts +18 -1
- package/dist/ai/providers/http.d.ts.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-3cmm9atm.js → chunk-1f9143dv.js} +2 -2
- package/dist/{chunk-3cmm9atm.js.map → chunk-1f9143dv.js.map} +1 -1
- package/dist/{chunk-b3e27j6t.js → chunk-1q0bqfas.js} +2 -2
- package/dist/{chunk-b3e27j6t.js.map → chunk-1q0bqfas.js.map} +1 -1
- package/dist/{chunk-jx8n3w5j.js → chunk-1tryvab1.js} +3 -3
- package/dist/{chunk-jx8n3w5j.js.map → chunk-1tryvab1.js.map} +1 -1
- package/dist/{chunk-bf88yh7q.js → chunk-1v70g3kn.js} +2 -2
- package/dist/{chunk-bf88yh7q.js.map → chunk-1v70g3kn.js.map} +1 -1
- package/dist/{chunk-3t37a4e5.js → chunk-2ba0v2ar.js} +2 -2
- package/dist/{chunk-3t37a4e5.js.map → chunk-2ba0v2ar.js.map} +1 -1
- package/dist/{chunk-c3rn99hm.js → chunk-2hd38awk.js} +1 -1
- package/dist/{chunk-6m5rt6xg.js → chunk-2s5pm9d9.js} +2 -2
- package/dist/{chunk-6m5rt6xg.js.map → chunk-2s5pm9d9.js.map} +1 -1
- package/dist/{chunk-d19x7t1z.js → chunk-34mk80mk.js} +2 -2
- package/dist/{chunk-d19x7t1z.js.map → chunk-34mk80mk.js.map} +1 -1
- package/dist/{chunk-bw2ptzxr.js → chunk-3p724p6c.js} +2 -2
- package/dist/{chunk-bw2ptzxr.js.map → chunk-3p724p6c.js.map} +1 -1
- package/dist/chunk-3ygtp1xe.js +5 -0
- package/dist/{chunk-ghf4kgs6.js.map → chunk-3ygtp1xe.js.map} +1 -1
- package/dist/{chunk-y4yv9e31.js → chunk-44hk3x6q.js} +1 -1
- package/dist/{chunk-6cq83t7e.js → chunk-45fbwj3s.js} +2 -2
- package/dist/{chunk-6cq83t7e.js.map → chunk-45fbwj3s.js.map} +1 -1
- package/dist/{chunk-5q2v29ma.js → chunk-4dg5kn53.js} +1 -1
- package/dist/{chunk-n2vx8eqm.js → chunk-4j7zwk5c.js} +2 -2
- package/dist/{chunk-n2vx8eqm.js.map → chunk-4j7zwk5c.js.map} +1 -1
- package/dist/{chunk-nd2vajx0.js → chunk-4x63knz8.js} +2 -2
- package/dist/{chunk-nd2vajx0.js.map → chunk-4x63knz8.js.map} +1 -1
- package/dist/{chunk-xf515fp7.js → chunk-4y8tc3zn.js} +2 -2
- package/dist/{chunk-xf515fp7.js.map → chunk-4y8tc3zn.js.map} +1 -1
- package/dist/{chunk-tnqvxzbw.js → chunk-4ze3f6vh.js} +2 -2
- package/dist/{chunk-tnqvxzbw.js.map → chunk-4ze3f6vh.js.map} +1 -1
- package/dist/{chunk-aezj1erg.js → chunk-5byng5rw.js} +3 -3
- package/dist/{chunk-aezj1erg.js.map → chunk-5byng5rw.js.map} +1 -1
- package/dist/{chunk-gpsqtjx5.js → chunk-5dwbhjk7.js} +1 -1
- package/dist/{chunk-nwafkabk.js → chunk-5sexb7ct.js} +2 -2
- package/dist/{chunk-nwafkabk.js.map → chunk-5sexb7ct.js.map} +1 -1
- package/dist/{chunk-10sbvn36.js → chunk-5wgnn0hf.js} +2 -2
- package/dist/{chunk-10sbvn36.js.map → chunk-5wgnn0hf.js.map} +1 -1
- package/dist/{chunk-s5p7pd7v.js → chunk-61ctwj1z.js} +2 -2
- package/dist/{chunk-s5p7pd7v.js.map → chunk-61ctwj1z.js.map} +1 -1
- package/dist/{chunk-n7nx6hby.js → chunk-6mzw2g0n.js} +4 -4
- package/dist/{chunk-n7nx6hby.js.map → chunk-6mzw2g0n.js.map} +1 -1
- package/dist/{chunk-2757n2e2.js → chunk-7tjxr4yz.js} +20 -20
- package/dist/{chunk-2757n2e2.js.map → chunk-7tjxr4yz.js.map} +3 -3
- package/dist/{chunk-q7nz3b4q.js → chunk-7wkwm0tn.js} +2 -2
- package/dist/{chunk-q7nz3b4q.js.map → chunk-7wkwm0tn.js.map} +1 -1
- package/dist/{chunk-4e99zzkt.js → chunk-97hpxdgf.js} +2 -2
- package/dist/{chunk-4e99zzkt.js.map → chunk-97hpxdgf.js.map} +1 -1
- package/dist/{chunk-kj6wqkjc.js → chunk-9b5c87xp.js} +4 -4
- package/dist/{chunk-kj6wqkjc.js.map → chunk-9b5c87xp.js.map} +1 -1
- package/dist/{chunk-3yzmzcxn.js → chunk-9fpecjxg.js} +2 -2
- package/dist/{chunk-3yzmzcxn.js.map → chunk-9fpecjxg.js.map} +1 -1
- package/dist/{chunk-twn4yxsd.js → chunk-9tce2xpm.js} +2 -2
- package/dist/{chunk-twn4yxsd.js.map → chunk-9tce2xpm.js.map} +1 -1
- package/dist/{chunk-8nxrgzxp.js → chunk-9x00fgse.js} +3 -3
- package/dist/{chunk-8nxrgzxp.js.map → chunk-9x00fgse.js.map} +1 -1
- package/dist/{chunk-sg8fcsvn.js → chunk-a1fb8zz6.js} +2 -2
- package/dist/{chunk-sg8fcsvn.js.map → chunk-a1fb8zz6.js.map} +1 -1
- package/dist/{chunk-wd3eyjbj.js → chunk-a2cswj4a.js} +3 -3
- package/dist/{chunk-wd3eyjbj.js.map → chunk-a2cswj4a.js.map} +1 -1
- package/dist/chunk-aefze46n.js +15 -0
- package/dist/{chunk-9caq1znh.js.map → chunk-aefze46n.js.map} +7 -6
- package/dist/{chunk-kgsmh0v0.js → chunk-ashn5jqy.js} +2 -2
- package/dist/{chunk-kgsmh0v0.js.map → chunk-ashn5jqy.js.map} +1 -1
- package/dist/{chunk-pcc8v9jc.js → chunk-b8qryxkd.js} +2 -2
- package/dist/{chunk-pcc8v9jc.js.map → chunk-b8qryxkd.js.map} +1 -1
- package/dist/{chunk-zdwgcyjh.js → chunk-bc8npwd8.js} +2 -2
- package/dist/{chunk-zdwgcyjh.js.map → chunk-bc8npwd8.js.map} +1 -1
- package/dist/{chunk-ttcmvam5.js → chunk-ccxn7kw0.js} +2 -2
- package/dist/{chunk-ttcmvam5.js.map → chunk-ccxn7kw0.js.map} +1 -1
- package/dist/{chunk-2ys56r3z.js → chunk-cmgrjsa2.js} +2 -2
- package/dist/{chunk-2ys56r3z.js.map → chunk-cmgrjsa2.js.map} +1 -1
- package/dist/{chunk-ascbx2kb.js → chunk-dg73a6xb.js} +1 -1
- package/dist/{chunk-tns989kw.js → chunk-ergrkg2f.js} +2 -2
- package/dist/{chunk-tns989kw.js.map → chunk-ergrkg2f.js.map} +1 -1
- package/dist/{chunk-2pj5e233.js → chunk-esgq4rbk.js} +3 -3
- package/dist/{chunk-2pj5e233.js.map → chunk-esgq4rbk.js.map} +1 -1
- package/dist/{chunk-epmtvd6j.js → chunk-ex6hbxw4.js} +2 -2
- package/dist/{chunk-epmtvd6j.js.map → chunk-ex6hbxw4.js.map} +1 -1
- package/dist/{chunk-znnt70rn.js → chunk-fr6e5g2z.js} +3 -3
- package/dist/{chunk-znnt70rn.js.map → chunk-fr6e5g2z.js.map} +1 -1
- package/dist/{chunk-1x1je71f.js → chunk-fycnw782.js} +2 -2
- package/dist/{chunk-1x1je71f.js.map → chunk-fycnw782.js.map} +1 -1
- package/dist/{chunk-rztf3yam.js → chunk-g5yrwqhv.js} +2 -2
- package/dist/{chunk-rztf3yam.js.map → chunk-g5yrwqhv.js.map} +1 -1
- package/dist/{chunk-v7e5gv6w.js → chunk-h16bfh2v.js} +2 -2
- package/dist/{chunk-v7e5gv6w.js.map → chunk-h16bfh2v.js.map} +1 -1
- package/dist/{chunk-28xqs354.js → chunk-h5q6w17p.js} +2 -2
- package/dist/{chunk-28xqs354.js.map → chunk-h5q6w17p.js.map} +1 -1
- package/dist/{chunk-cgxk8pn8.js → chunk-j5txga06.js} +3 -3
- package/dist/{chunk-cgxk8pn8.js.map → chunk-j5txga06.js.map} +1 -1
- package/dist/{chunk-2a4q9t8c.js → chunk-m252bwtf.js} +2 -2
- package/dist/{chunk-2a4q9t8c.js.map → chunk-m252bwtf.js.map} +1 -1
- package/dist/{chunk-bm3pyh9m.js → chunk-mndcq5z1.js} +2 -2
- package/dist/{chunk-bm3pyh9m.js.map → chunk-mndcq5z1.js.map} +1 -1
- package/dist/{chunk-0bzcxgks.js → chunk-nfrgz3gw.js} +3 -3
- package/dist/{chunk-0bzcxgks.js.map → chunk-nfrgz3gw.js.map} +1 -1
- package/dist/{chunk-kqwenh9b.js → chunk-p23sctqt.js} +2 -2
- package/dist/{chunk-kqwenh9b.js.map → chunk-p23sctqt.js.map} +1 -1
- package/dist/{chunk-m62jshaz.js → chunk-pebp4an8.js} +3 -3
- package/dist/{chunk-m62jshaz.js.map → chunk-pebp4an8.js.map} +1 -1
- package/dist/{chunk-5yj3k754.js → chunk-pme2yb8p.js} +3 -3
- package/dist/{chunk-5yj3k754.js.map → chunk-pme2yb8p.js.map} +1 -1
- package/dist/{chunk-x0983cez.js → chunk-qhz22t3a.js} +2 -2
- package/dist/{chunk-x0983cez.js.map → chunk-qhz22t3a.js.map} +1 -1
- package/dist/{chunk-x0vrrfp7.js → chunk-qwkgnt4q.js} +3 -3
- package/dist/{chunk-x0vrrfp7.js.map → chunk-qwkgnt4q.js.map} +1 -1
- package/dist/{chunk-eeqfp05r.js → chunk-r887spwe.js} +2 -2
- package/dist/{chunk-eeqfp05r.js.map → chunk-r887spwe.js.map} +1 -1
- package/dist/{chunk-dwt3p2aw.js → chunk-rjvpy87k.js} +2 -2
- package/dist/{chunk-dwt3p2aw.js.map → chunk-rjvpy87k.js.map} +1 -1
- package/dist/{chunk-gap8ta5q.js → chunk-t1abd8jv.js} +3 -3
- package/dist/{chunk-gap8ta5q.js.map → chunk-t1abd8jv.js.map} +1 -1
- package/dist/{chunk-xa2k8dm0.js → chunk-v176r68j.js} +2 -2
- package/dist/{chunk-xa2k8dm0.js.map → chunk-v176r68j.js.map} +1 -1
- package/dist/{chunk-q19cs1qf.js → chunk-vqq0z746.js} +2 -2
- package/dist/{chunk-q19cs1qf.js.map → chunk-vqq0z746.js.map} +1 -1
- package/dist/{chunk-gw9sy16b.js → chunk-vy1334k3.js} +2 -2
- package/dist/{chunk-gw9sy16b.js.map → chunk-vy1334k3.js.map} +1 -1
- package/dist/{chunk-s52ecbdd.js → chunk-wbrxv9ab.js} +2 -2
- package/dist/{chunk-s52ecbdd.js.map → chunk-wbrxv9ab.js.map} +1 -1
- package/dist/{chunk-rsnm21vr.js → chunk-wytpqkss.js} +3 -3
- package/dist/{chunk-rsnm21vr.js.map → chunk-wytpqkss.js.map} +1 -1
- package/dist/{chunk-qj138p8j.js → chunk-wz63qyvt.js} +3 -3
- package/dist/{chunk-qj138p8j.js.map → chunk-wz63qyvt.js.map} +1 -1
- package/dist/{chunk-jqdqpdss.js → chunk-x1s1r6ch.js} +2 -2
- package/dist/{chunk-jqdqpdss.js.map → chunk-x1s1r6ch.js.map} +1 -1
- package/dist/{chunk-9by5yphc.js → chunk-x2zqx53x.js} +1 -1
- package/dist/{chunk-y8c704wp.js → chunk-x3qtvs3n.js} +2 -2
- package/dist/{chunk-y8c704wp.js.map → chunk-x3qtvs3n.js.map} +1 -1
- package/dist/{chunk-9sv8skzh.js → chunk-x7pv1jjf.js} +2 -2
- package/dist/{chunk-9sv8skzh.js.map → chunk-x7pv1jjf.js.map} +1 -1
- package/dist/{chunk-5sc7j1g0.js → chunk-x7yrxhk9.js} +2 -2
- package/dist/{chunk-5sc7j1g0.js.map → chunk-x7yrxhk9.js.map} +1 -1
- package/dist/{chunk-0jbwxas3.js → chunk-xk32g0n4.js} +2 -2
- package/dist/{chunk-0jbwxas3.js.map → chunk-xk32g0n4.js.map} +1 -1
- package/dist/{chunk-nchyjgpr.js → chunk-y6q1gv83.js} +2 -2
- package/dist/{chunk-nchyjgpr.js.map → chunk-y6q1gv83.js.map} +1 -1
- package/dist/{chunk-1ecvjvbg.js → chunk-yp99x86s.js} +2 -2
- package/dist/{chunk-1ecvjvbg.js.map → chunk-yp99x86s.js.map} +1 -1
- package/dist/{chunk-yn2v5axb.js → chunk-zd2670hx.js} +2 -2
- package/dist/{chunk-yn2v5axb.js.map → chunk-zd2670hx.js.map} +1 -1
- package/dist/{chunk-7pes8axs.js → chunk-ze3562xh.js} +2 -2
- package/dist/{chunk-7pes8axs.js.map → chunk-ze3562xh.js.map} +1 -1
- package/dist/{chunk-jg1n0b5e.js → chunk-znyte3fp.js} +2 -2
- package/dist/{chunk-jg1n0b5e.js.map → chunk-znyte3fp.js.map} +1 -1
- package/dist/{chunk-hc58rnwq.js → chunk-zr1h51pw.js} +2 -2
- package/dist/{chunk-hc58rnwq.js.map → chunk-zr1h51pw.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/Storage.d.ts +6 -0
- package/dist/facades/Storage.d.ts.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/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/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/file-storage/FilesystemManager.d.ts +4 -0
- package/dist/services/file-storage/FilesystemManager.d.ts.map +1 -1
- package/dist/services/file-storage/config.d.ts +16 -0
- package/dist/services/file-storage/config.d.ts.map +1 -1
- package/dist/services/file-storage/fetchTimeouts.d.ts +41 -0
- package/dist/services/file-storage/fetchTimeouts.d.ts.map +1 -0
- package/dist/services/index.d.ts +1 -0
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +3 -3
- package/dist/services/index.js.map +2 -2
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.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-9caq1znh.js +0 -15
- package/dist/chunk-ghf4kgs6.js +0 -5
- /package/dist/{chunk-c3rn99hm.js.map → chunk-2hd38awk.js.map} +0 -0
- /package/dist/{chunk-y4yv9e31.js.map → chunk-44hk3x6q.js.map} +0 -0
- /package/dist/{chunk-5q2v29ma.js.map → chunk-4dg5kn53.js.map} +0 -0
- /package/dist/{chunk-gpsqtjx5.js.map → chunk-5dwbhjk7.js.map} +0 -0
- /package/dist/{chunk-ascbx2kb.js.map → chunk-dg73a6xb.js.map} +0 -0
- /package/dist/{chunk-9by5yphc.js.map → chunk-x2zqx53x.js.map} +0 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$b as Z8,$c as
|
|
3
|
-
`)}function ZJ($){return new Date($).toISOString().replace(/\.\d{3}Z$/,"Z")}function P8($,J){return $.length<=J?$:`${$.slice(0,J-1)}\u2026`}class KJ{table;sql;dialect;connection;constructor($,J={}){let Q=J.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=$.sql,this.dialect=$.dialect,this.connection=$.name}async createTable(){for(let $ of
|
|
2
|
+
import{$b as Z8,$c as Z6,Ac as JQ,Bc as QQ,Cc as M8,Ec as S8,Fc as k8,Gc as E8,Hc as T8,Ic as j8,Jc as x8,Kc as q8,Lc as I8,Mc as w8,Nc as b8,Oc as f8,Pc as v8,Rc as w,Sc as Z9,Tc as O9,Uc as a,Vc as j,Wc as K8,Xc as e0,Yb as Q8,Yc as $6,Zb as OQ,Zc as J6,_b as _Q,_c as Q6,ad as W6,bd as K6,cc as I$,cd as X6,dc as R,dd as Y6,ec as E,ed as G6,fd as V6,gc as e8,gd as F$,hc as n8,hd as H6,ic as X$,id as jQ,jc as r0,jd as z6,kc as u,kd as kQ,lc as W8,ld as D6,mc as MQ,md as F6,nc as SQ,nd as B6,oc as AQ,od as j$,pc as p,pd as PJ,qc as RQ,qd as P6,rc as a$,rd as N6,sc as EQ,sd as xQ,tc as TQ,td as U6,uc as t$,ud as L6,vc as C8,vd as C6,wc as O8,wd as O6,xd as FJ,yc as _8,zc as y}from"../chunk-7tjxr4yz.js";import{Pd as B8}from"../chunk-mndcq5z1.js";import"../chunk-t1abd8jv.js";import{Mh as PQ,Ph as UQ,Qi as LQ,Ti as dJ,Xi as CQ,di as R9,ei as s0,fi as a0,gi as t0,hi as q}from"../chunk-aefze46n.js";import{$i as s$,Yi as NQ,_i as o$}from"../chunk-yp99x86s.js";import{ij as g}from"../chunk-4x63knz8.js";import"../chunk-xk32g0n4.js";import"../chunk-h16bfh2v.js";import"../chunk-x1s1r6ch.js";import{Ak as R$,lk as o,mk as s}from"../chunk-pme2yb8p.js";import"../chunk-9fpecjxg.js";import"../chunk-ccxn7kw0.js";import{nl as d9}from"../chunk-fr6e5g2z.js";import"../chunk-qhz22t3a.js";import"../chunk-rjvpy87k.js";import{Gl as JJ}from"../chunk-ergrkg2f.js";import"../chunk-7wkwm0tn.js";import{existsSync as yQ,readdirSync as M6,readFileSync as z8}from"fs";import{isAbsolute as hQ,join as C$,relative as gQ,sep as uQ}from"path";var D8="prompts.json",cQ=/\{\{>\s*([\w./-]+)\s*\}\}/g,G8=/\{\{(\w+)\}\}/g,mQ=/^[\w-]+(\/[\w-]+)*$/,V8={dir:"app/agents",shared:"prompts"},_$={},e$=new Map,O$;function pQ(){if(O$===void 0){let $=C$(JJ(),"dist","server",D8);O$=yQ($)?JSON.parse(z8($,"utf8")):null}return O$??null}function lQ($){return $.replace(/\r?\n$/,"")}function H8(){return _$.cache??Bun.env.NODE_ENV==="production"}function dQ($){if(!mQ.test($))throw Error(`"${$}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let J=_$.dir??V8.dir,Q=hQ(J)?J:C$(process.cwd(),J),Z=$.includes("/")?`${$}.md`:C$(_$.shared??V8.shared,`${$}.md`);return C$(Q,Z)}function iQ($){let J=dQ($),Q=H8()?e$.get(J):void 0;if(Q!==void 0)return Q;let Z=Bun.env.NODE_ENV==="production";if(Z){let K=pQ()?.[gQ(JJ(),J).split(uQ).join("/")];if(K!==void 0)return K}let W;try{W=lQ(z8(J,"utf8"))}catch(K){if(K.code==="ENOENT"){let X=Z?` or in dist/server/${D8}`:"";throw Error(`The prompt "${$}" does not exist (looked for ${J}${X}).`)}throw K}if(H8())e$.set(J,W);return W}function $J($,J){if(J.includes($))throw Error(`The prompt "${$}" includes itself: ${[...J,$].join(" > ")}.`);return iQ($).replace(cQ,(Q,Z)=>$J(Z,[...J,$]))}class F8{static configure($){_$={...$},e$.clear(),O$=void 0}static render($,J={}){return $J($,[]).replace(G8,(Q,Z)=>{if(!Object.hasOwn(J,Z))throw Error(`The prompt "${$}" has no value for {{${Z}}}.`);return String(J[Z])})}static placeholders($){let J=[...$J($,[]).matchAll(G8)].map((Q)=>Q[1]);return[...new Set(J)]}}class QJ extends B8{name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await y.sweep({limit:100})===100);}}var M$=20;function N8($,J){if(J<=0||$.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.",...[...$.filter((K)=>K.state==="running").sort(Q),...$.filter((K)=>K.state!=="running").sort(Q)].slice(0,J).map((K)=>{let X=[`- ${K.id} (${K.toolName})`];if(K.state==="running")X.push(`running since ${ZJ(K.createdAt)}`);else if(K.state==="ok")X.push(`finished at ${ZJ(K.settledAt??K.updatedAt)}`);else{let G=K.error?`${K.error.code}: ${P8(K.error.message,200)}`:"failed";X.push(`failed at ${ZJ(K.settledAt??K.updatedAt)} (${G})`)}if(K.summary!==void 0)X.push(`summary: ${P8(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 ZJ($){return new Date($).toISOString().replace(/\.\d{3}Z$/,"Z")}function P8($,J){return $.length<=J?$:`${$.slice(0,J-1)}\u2026`}class KJ{table;sql;dialect;connection;constructor($,J={}){let Q=J.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=$.sql,this.dialect=$.dialect,this.connection=$.name}async createTable(){for(let $ of nQ(this.dialect,this.table))await this.sql.unsafe($)}async transaction($){if(this.connection===void 0||this.joinable())return $();return R$(this.sql,()=>$(),{connection:this.connection})}async create($){let J=this.q(),Q=this.clock(J);await J`
|
|
4
4
|
INSERT INTO ${this.name(J)}
|
|
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)
|
|
@@ -28,7 +28,7 @@ import{$b as Z8,$c as Q6,Ac as e9,Bc as $Q,Cc as M8,Ec as S8,Fc as k8,Gc as E8,H
|
|
|
28
28
|
`).map(WJ)}async now(){let $=this.q(),[J]=await $`SELECT ${this.clock($)} AS now`;return Number(J.now)}async prune($){let J=this.q(),Q=await J`
|
|
29
29
|
DELETE FROM ${this.name(J)}
|
|
30
30
|
WHERE state <> 'running' AND settled_at <= ${this.clock(J)} - ${this.ms(J,$)}
|
|
31
|
-
`;return L8(Q)}joinable(){if(this.connection===void 0)return;let $=o();if($===void 0||s()!==this.connection)return;return $}q(){return this.joinable()??this.sql}column($,J){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return $.unsafe(Q?`\`${J}\``:`"${J}"`)}name($){let J=this.dialect==="mysql"||this.dialect==="mariadb";return $.unsafe(J?`\`${this.table}\``:`"${this.table}"`)}clock($){switch(this.dialect){case"postgres":return $`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return $`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return $`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms($,J){let Q=Math.max(0,Math.round(J));return this.dialect==="mysql"||this.dialect==="mariadb"?$`CAST(${Q} AS SIGNED)`:$`CAST(${Q} AS BIGINT)`}}function U8($,J){return J.map((Q)=>$`${Q}`).reduce((Q,Z)=>$`${Q}, ${Z}`)}function S$($){return $===void 0?null:JSON.stringify($)}function A$($){if($===null||$===void 0)return;return JSON.parse(String($))}function WJ($){let J=A$($.summary),Q=A$($.output),Z=A$($.error),W=A$($.usage);return{id:String($.id),threadId:String($.thread_id),runId:String($.run_id),toolCallId:String($.tool_call_id),toolName:String($.tool_name),owner:$.owner===null||$.owner===void 0?null:String($.owner),job:$.job===null||$.job===void 0?null:String($.job),...J!==void 0?{summary:J}:{},state:String($.state),...Q!==void 0?{output:Q}:{},...Z!==void 0?{error:Z}:{},...W!==void 0?{usage:W}:{},...Number($.orphaned)===1?{orphaned:!0}:{},attachmentScope:$.attachment_scope===null||$.attachment_scope===void 0?null:String($.attachment_scope),createdAt:Number($.created_at),updatedAt:Number($.updated_at),deadlineAt:Number($.deadline_at),...$.settled_at===null||$.settled_at===void 0?{}:{settledAt:Number($.settled_at)}}}function L8($){let J=$;return Math.max(Number(J.count??0),Number(J.affectedRows??0))}function
|
|
31
|
+
`;return L8(Q)}joinable(){if(this.connection===void 0)return;let $=o();if($===void 0||s()!==this.connection)return;return $}q(){return this.joinable()??this.sql}column($,J){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return $.unsafe(Q?`\`${J}\``:`"${J}"`)}name($){let J=this.dialect==="mysql"||this.dialect==="mariadb";return $.unsafe(J?`\`${this.table}\``:`"${this.table}"`)}clock($){switch(this.dialect){case"postgres":return $`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return $`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return $`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms($,J){let Q=Math.max(0,Math.round(J));return this.dialect==="mysql"||this.dialect==="mariadb"?$`CAST(${Q} AS SIGNED)`:$`CAST(${Q} AS BIGINT)`}}function U8($,J){return J.map((Q)=>$`${Q}`).reduce((Q,Z)=>$`${Q}, ${Z}`)}function S$($){return $===void 0?null:JSON.stringify($)}function A$($){if($===null||$===void 0)return;return JSON.parse(String($))}function WJ($){let J=A$($.summary),Q=A$($.output),Z=A$($.error),W=A$($.usage);return{id:String($.id),threadId:String($.thread_id),runId:String($.run_id),toolCallId:String($.tool_call_id),toolName:String($.tool_name),owner:$.owner===null||$.owner===void 0?null:String($.owner),job:$.job===null||$.job===void 0?null:String($.job),...J!==void 0?{summary:J}:{},state:String($.state),...Q!==void 0?{output:Q}:{},...Z!==void 0?{error:Z}:{},...W!==void 0?{usage:W}:{},...Number($.orphaned)===1?{orphaned:!0}:{},attachmentScope:$.attachment_scope===null||$.attachment_scope===void 0?null:String($.attachment_scope),createdAt:Number($.created_at),updatedAt:Number($.updated_at),deadlineAt:Number($.deadline_at),...$.settled_at===null||$.settled_at===void 0?{}:{settledAt:Number($.settled_at)}}}function L8($){let J=$;return Math.max(Number(J.count??0),Number(J.affectedRows??0))}function nQ($,J){if($==="mysql"||$==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${J}\` (
|
|
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 Z8,$c as Q6,Ac as e9,Bc as $Q,Cc as M8,Ec as S8,Fc as k8,Gc as E8,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 "${J}_thread_id_created_at_idx" ON "${J}"("thread_id", "created_at")`,`CREATE INDEX IF NOT EXISTS "${J}_state_deadline_at_idx" ON "${J}"("state", "deadline_at")`]}var A8=4;class YJ{table;sql;dialect;connection;constructor($,J={}){let Q=J.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=$.sql,this.dialect=$.dialect,this.connection=$.name}async createTable(){for(let $ of
|
|
75
|
+
)`,`CREATE INDEX IF NOT EXISTS "${J}_thread_id_created_at_idx" ON "${J}"("thread_id", "created_at")`,`CREATE INDEX IF NOT EXISTS "${J}_state_deadline_at_idx" ON "${J}"("state", "deadline_at")`]}var A8=4;class YJ{table;sql;dialect;connection;constructor($,J={}){let Q=J.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=$.sql,this.dialect=$.dialect,this.connection=$.name}async createTable(){for(let $ of oQ(this.dialect,this.table))await this.sql.unsafe($)}async list($,J={}){if($.length===0)return[];if(J.kinds!==void 0&&J.kinds.length===0)return[];let Q=this.q(),Z=[Q`scope IN (${Z$(Q,$)})`];if(J.kinds!==void 0)Z.push(Q`kind IN (${Z$(Q,J.kinds)})`);if(!J.includeExpired)Z.push(Q`(expires_at IS NULL OR expires_at > ${this.clock(Q)})`);if(J.after!==void 0){let[V]=await Q`
|
|
76
76
|
SELECT created_at, id FROM ${this.name(Q)}
|
|
77
77
|
WHERE id = ${J.after} AND scope IN (${Z$(Q,$)})
|
|
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=J.limit===void 0||J.tags!==void 0?void 0:Math.max(0,Math.floor(J.limit)),G=(K===void 0?await Q`
|
|
@@ -102,7 +102,7 @@ import{$b as Z8,$c as Q6,Ac as e9,Bc as $Q,Cc as M8,Ec as S8,Fc as k8,Gc as E8,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 = ${$} AND ${this.column(Q,"key")} = ${J}
|
|
105
|
-
`;return Z[0]?XJ(Z[0]):null}async mustGet($){let J=await this.get($);if(!J)throw Error(`The memory ${$} was not found after it was written.`);return J}joinable(){if(this.connection===void 0)return;let $=o();if($===void 0||s()!==this.connection)return;return $}q(){return this.joinable()??this.sql}column($,J){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return $.unsafe(Q?`\`${J}\``:`"${J}"`)}name($){let J=this.dialect==="mysql"||this.dialect==="mariadb";return $.unsafe(J?`\`${this.table}\``:`"${this.table}"`)}clock($){switch(this.dialect){case"postgres":return $`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return $`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return $`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms($,J){let Q=Math.max(0,Math.round(J));return this.dialect==="mysql"||this.dialect==="mariadb"?$`CAST(${Q} AS SIGNED)`:$`CAST(${Q} AS BIGINT)`}}function Z$($,J){return J.map((Q)=>$`${Q}`).reduce((Q,Z)=>$`${Q}, ${Z}`)}function R8($,J){if($===null||$===void 0||$==="")return J;try{return JSON.parse(String($))}catch{return J}}function XJ($){let J=R8($.tags,[]);return{id:String($.id),scope:String($.scope),kind:String($.kind),content:String($.content),key:$.key===null||$.key===void 0?null:String($.key),tags:Array.isArray(J)?J.map(String):[],pinned:Number($.pinned)===1,source:R8($.source,{by:"app"}),version:Number($.version),createdAt:Number($.created_at),updatedAt:Number($.updated_at),lastUsedAt:$.last_used_at===null||$.last_used_at===void 0?null:Number($.last_used_at),expiresAt:$.expires_at===null||$.expires_at===void 0?null:Number($.expires_at)}}function E$($){let J=$;return Math.max(Number(J.count??0),Number(J.affectedRows??0))}function
|
|
105
|
+
`;return Z[0]?XJ(Z[0]):null}async mustGet($){let J=await this.get($);if(!J)throw Error(`The memory ${$} was not found after it was written.`);return J}joinable(){if(this.connection===void 0)return;let $=o();if($===void 0||s()!==this.connection)return;return $}q(){return this.joinable()??this.sql}column($,J){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return $.unsafe(Q?`\`${J}\``:`"${J}"`)}name($){let J=this.dialect==="mysql"||this.dialect==="mariadb";return $.unsafe(J?`\`${this.table}\``:`"${this.table}"`)}clock($){switch(this.dialect){case"postgres":return $`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return $`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return $`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms($,J){let Q=Math.max(0,Math.round(J));return this.dialect==="mysql"||this.dialect==="mariadb"?$`CAST(${Q} AS SIGNED)`:$`CAST(${Q} AS BIGINT)`}}function Z$($,J){return J.map((Q)=>$`${Q}`).reduce((Q,Z)=>$`${Q}, ${Z}`)}function R8($,J){if($===null||$===void 0||$==="")return J;try{return JSON.parse(String($))}catch{return J}}function XJ($){let J=R8($.tags,[]);return{id:String($.id),scope:String($.scope),kind:String($.kind),content:String($.content),key:$.key===null||$.key===void 0?null:String($.key),tags:Array.isArray(J)?J.map(String):[],pinned:Number($.pinned)===1,source:R8($.source,{by:"app"}),version:Number($.version),createdAt:Number($.created_at),updatedAt:Number($.updated_at),lastUsedAt:$.last_used_at===null||$.last_used_at===void 0?null:Number($.last_used_at),expiresAt:$.expires_at===null||$.expires_at===void 0?null:Number($.expires_at)}}function E$($){let J=$;return Math.max(Number(J.count??0),Number(J.affectedRows??0))}function oQ($,J){if($==="mysql"||$==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${J}\` (
|
|
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 Z8,$c as Q6,Ac as e9,Bc as $Q,Cc as M8,Ec as S8,Fc as k8,Gc as E8,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 "${J}_scope_kind_created_at_idx" ON "${J}"("scope", "kind", "created_at")`,`CREATE INDEX IF NOT EXISTS "${J}_expires_at_idx" ON "${J}"("expires_at")`,`CREATE UNIQUE INDEX IF NOT EXISTS "${J}_scope_key_key" ON "${J}"("scope", "key")`]}var h8={n:0,mean:0,stddev:0,low:null,high:null};function y($){let J=[0.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-0.13857109526572012,0.000009984369578019572,0.00000015056327351493116];if($<0.5)return Math.log(Math.PI/Math.sin(Math.PI*$))-y(1-$);$-=1;let Q=J[0],Z=$+7.5;for(let W=1;W<9;W++)Q+=J[W]/($+W);return 0.5*Math.log(2*Math.PI)+($+0.5)*Math.log(Z)-Z+Math.log(Q)}function y8($,J,Q){let W=1,K=1-($+J)*Q/($+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*(J-G)*Q/(($+V-1)*($+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=-($+G)*($+J+G)*Q/(($+V)*($+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 nQ($,J,Q){if($<=0)return 0;if($>=1)return 1;let Z=Math.exp(y(J+Q)-y(J)-y(Q)+J*Math.log($)+Q*Math.log(1-$));return $<(J+1)/(J+Q+2)?Z*y8(J,Q,$)/J:1-Z*y8(Q,J,1-$)/Q}function GJ($,J){return nQ(J/(J+$*$),J/2,0.5)}function oQ($){if(!($>0))return Number.POSITIVE_INFINITY;let J=1.959964,Q=2;while(GJ(Q,$)>0.05)Q*=2;for(let Z=0;Z<100;Z++){let W=(J+Q)/2;if(GJ(W,$)>0.05)J=W;else Q=W}return(J+Q)/2}function sQ($,J,Q,Z){let W=$+Q,K=J+Z,X=(H,D)=>y(H+1)-y(D+1)-y(H-D+1),G=(H)=>Math.exp(X(J,H)+X(Z,W-H)-X(K,W)),V=G($),Y=0;for(let H=Math.max(0,W-Z);H<=Math.min(J,W);H++){let D=G(H);if(D<=V*1.0000001)Y+=D}return Math.min(1,Y)}function g8($,J){if($.length<2)return 0;let Q=$.reduce((W,K)=>W+(K-J)**2,0),Z=Math.sqrt(Q/($.length-1));return Z<0.000000000001*Math.max(1,Math.abs(J))?0:Z}function VJ($){let J=$.length;if(J===0)return h8;let Q=$.map((G)=>G?1:0),Z=Q.reduce((G,V)=>G+V,0)/J,W=3.841458881296,K=(Z+W/(2*J))/(1+W/J),X=1.959964*Math.sqrt(Z*(1-Z)/J+W/(4*J*J))/(1+W/J);return{n:J,mean:Z,stddev:g8(Q,Z),low:Math.max(0,K-X),high:Math.min(1,K+X)}}function HJ($){let J=$.length;if(J===0)return h8;let Q=$.reduce((K,X)=>K+X,0)/J,Z=g8($,Q);if(J<2||Z===0)return{n:J,mean:Q,stddev:Z,low:null,high:null};let W=oQ(J-1)*Z/Math.sqrt(J);return{n:J,mean:Q,stddev:Z,low:Q-W,high:Q+W}}function W$($,J,Q){return{before:$.mean,after:J.mean,delta:J.mean-$.mean,p:Q,pAdjusted:Q,significant:!1}}function u8($,J){if($.n===0||J.n===0)return W$($,J,null);let Q=(Z)=>Math.round(Z.mean*Z.n);return W$($,J,sQ(Q($),$.n,Q(J),J.n))}function c8($,J){if($.n<2||J.n<2)return W$($,J,null);let Q=$.stddev**2/$.n,Z=J.stddev**2/J.n,W=Math.sqrt(Q+Z);if(W===0)return W$($,J,null);let K=(Q+Z)**2/(Q**2/($.n-1)+Z**2/(J.n-1));return W$($,J,GJ((J.mean-$.mean)/W,K))}function m8($,J,Q){if(Q==="holm"){let Z=$.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 $)Z.pAdjusted=Z.p;for(let Z of $)Z.significant=Z.pAdjusted!==null&&Z.pAdjusted<J&&Z.delta!==0}class T${name;cases;runs;concurrency;graders;pricing;task;constructor($){this.name=$.name,this.cases=$.cases,this.runs=$.runs??1,this.concurrency=$.concurrency??1,this.task=$.task,this.graders=typeof $.graders==="function"?$.graders({judge:(J)=>T$.judge(J)}):$.graders,this.pricing=$.pricing}static create($){let J=`The eval "${$.name}"`;K$($.runs,J,"runs"),K$($.concurrency,J,"concurrency");let Q=new Set;for(let W of $.cases){if(Q.has(W.id))throw Error(`${J} has two cases with the id "${W.id}".`);Q.add(W.id)}let Z=new T$($);for(let[W,K]of Object.entries(Z.graders))if(typeof K!=="function"&&K.kind==="judge")K$(K.samples,`${J}'s judge "${W}"`,"samples");return Z}static judge($){return{...$,kind:"judge"}}static compare($,J,Q={}){return o8($,J,Q)}static format($,J={}){return eQ($,J)}async run($={}){let J=`${this.name}.run`;K$($.runs,J,"runs"),K$($.concurrency,J,"concurrency");let Q=$.only?new Set($.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=$.runs??this.runs,W=Date.now(),K=new AbortController,X=$.signal?AbortSignal.any([$.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,$.keepOutputs??!1);H[B]=L;try{$.onSample?.(L)}catch(O){z??={error:O},K.abort(O)}}},U=Math.min($.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 X$(async()=>{try{K=await this.task($.input,{case:$,run:J,signal:Q})}catch(U){X=a8(U)}}),V={},Y=!1,H=await X$(async()=>{if(X!==void 0)return;let U={case:$,input:$.input,run:J};for(let[N,B]of Object.entries(this.graders)){if($.skip?.includes(N))continue;let P=await p8(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?zJ(this.pricing,G.byModel).cost+zJ(this.pricing,H.byModel).cost:void 0;return{case:$.id,run:J,pass:X===void 0&&!z&&Object.values(V).every((U)=>U.pass),excluded:Y||z,...z?{ungraded:!0}:{},score:X!==void 0||z?0:s8(D),grades:V,...X!==void 0?{error:X}:{},...Z&&X===void 0?{output:K}:{},usage:G.usage,byModel:tQ(G.byModel,H.byModel),judgeUsage:H.usage,...F!==void 0?{cost:F}:{},durationMs:Date.now()-W}}async calibrate($,J){let Q=$.calibration,Z=[],W=0,K=await X$(async()=>{for(let[V,Y]of Q.examples.entries()){if(J.aborted)break;let H=Y.id??`example-${V+1}`,D={case:{id:H,input:Y.input},input:Y.input,run:0},z=await p8($,Y.output,D,J),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=$.filter((U)=>U.case===z.id);if(F.length===0)continue;G[z.id]={...l8(F),graders:d8(F,X)}}let V=S(),Y=S(),H={};for(let z of $){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?zJ(this.pricing,H):void 0;return{name:this.name,startedAt:Z,durationMs:W,runs:Q,aborted:K.aborted,planned:K.planned,samples:$,cases:G,graders:d8($,X),calibration:J,totals:{...l8($),usage:V,judgeUsage:Y,byModel:H,...D?{cost:D.cost}:{},unpriced:D?D.unpriced:Object.keys(H)}}}}async function p8($,J,Q,Z){let W=typeof $==="function"?0.5:$.threshold??0.5;try{if(typeof $==="function")return DJ(await $(J,Q),W);if($.kind!=="judge")return DJ(await $.check(J,Q),W);return await aQ($,J,Q,W,Z)}catch(K){return{pass:!1,score:0,error:a8(K)}}}async function aQ($,J,Q,Z,W){let K=await $.prompt(J,Q),X=typeof K==="string"?{prompt:K}:K,G=[];for(let D=0;D<($.samples??1)&&!W.aborted;D++){let z=await FJ({signal:W,provider:$.provider,...$.instructions!==void 0?{instructions:$.instructions}:{},...X,output:$.output,...$.reasoning!==void 0?{reasoning:$.reasoning}:{},...$.maxOutputTokens!==void 0?{maxOutputTokens:$.maxOutputTokens}:{},...$.temperature!==void 0?{temperature:$.temperature}:{},logErrors:!1});if(!z.ok){G.push({pass:!1,score:0,error:`The judge failed: ${z.error.message}`});continue}let F=DJ($.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:s8(G.map((D)=>D.score)),...Y.length>0?{note:Y.join(" | ")}:{},...H.length===G.length?{error:H.join(" | ")}:{}}}function DJ($,J){if($===null||$===void 0)return null;if(typeof $==="boolean")return{pass:$,score:$?1:0};if(typeof $==="number"){if(!Number.isFinite($))throw Error(`A grader answered the score ${$}.`);let Q=i8($);return{pass:Q>=J,score:Q}}return{pass:$.pass,score:$.score===void 0?$.pass?1:0:i8($.score),...$.note!==void 0?{note:$.note}:{}}}function l8($){let J=$.filter((Q)=>!Q.excluded);return{samples:$.length,kept:J.length,passed:J.filter((Q)=>Q.pass).length,errors:$.filter((Q)=>Q.error!==void 0).length,passRate:VJ(J.map((Q)=>Q.pass)),score:HJ(J.map((Q)=>Q.score))}}function d8($,J){let Q=$.filter((W)=>!W.excluded),Z=[...new Set($.flatMap((W)=>Object.keys(W.grades)))];return Object.fromEntries(Z.map((W)=>{let X=(J.has(W)?$:Q).flatMap((G)=>G.grades[W]?[G.grades[W]]:[]);return[W,{passRate:VJ(X.map((G)=>G.pass)),score:HJ(X.map((G)=>G.score))}]}))}function zJ($,J){let Q=0,Z=[];for(let[W,K]of Object.entries(J)){let X=n8($,W,K);if(X===void 0){Z.push(W);continue}Q+=X}return{cost:Q,unpriced:Z}}function tQ(...$){let J={};for(let Q of $)for(let[Z,W]of Object.entries(Q))J[Z]=A(J[Z]??S(),W);return J}function o8($,J,Q){for(let[B,P]of[["baseline",$],["current report",J]])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:u8(P.passRate,L.passRate),score:c8(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",$.totals,J.totals),H=G("case",$.cases,J.cases),D=G("grader",$.graders,J.graders),z=K.flatMap((B)=>[B.passRate,B.score]);m8(z,Z,W);let F={cases:V([...new Set([...$.planned??[],...Object.keys($.cases)])],[...new Set([...J.planned??[],...Object.keys(J.cases)])]),graders:V(Object.keys($.graders),Object.keys(J.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 = ${rQ(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 rQ($){return $<0.001?"<0.001":$.toFixed(3)}function eQ($,J){let Q=J.baseline&&!J.baseline.aborted&&!$.aborted?o8(J.baseline,$,J):void 0,{totals:Z}=$,W=[];if(W.push(`eval ${$.name}: ${Z.samples} samples, ${Z.kept} kept, ${Z.passed} passed, ${Z.errors} errors (${($.durationMs/1000).toFixed(1)}s)`),$.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($.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($.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($.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 s8($){return $.reduce((J,Q)=>J+Q,0)/$.length}function i8($){return Math.min(1,Math.max(0,$))}function a8($){return $ instanceof Error?$.message:String($)}function K$($,J,Q){if($===void 0||Number.isInteger($)&&$>=1)return;throw Error(`${J} sets \`${Q}\` to ${String($)}, but it has to be a whole number of at least 1.`)}var $Z=/^[A-Za-z0-9_-]{1,64}$/;function JZ($,J){let Q=QZ(J)?J:{filter:J},Z=Q.deferred===!0,W=$.descriptors(Q.filter);if(!Q.namespaces)return W.map((H)=>BJ($,H,Z));let K=Object.entries(Q.namespaces),X=new Set($.descriptors().flatMap((H)=>H.tags));for(let[H,D]of K){if(!$Z.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(BJ($,H,Z));else G.get(D).push(BJ($,H,!1))}let Y=[];for(let[H,D]of K){let z=G.get(H);if(z.length===0)continue;Y.push(PJ.create({name:H,description:D.description,tools:z,deferred:D.deferred??Z}))}return[...Y,...V]}function QZ($){return typeof $==="object"&&$!==null&&(("filter"in $)||("namespaces"in $)||("deferred"in $))}function BJ($,J,Q){if(J.kind==="tool")return ZZ($,J,Q);return j$.create({name:J.name,description:J.description,inputSchema:J.inputSchema,...J.outputSchema?{outputSchema:J.outputSchema}:{},requiresApproval:J.requiresApproval,deferred:Q,execute:(Z,W)=>{let K=h.getStore()?.req;if(!K)throw new g(`"${J.name}" calls an api route as the user who started this run, and this run was not started inside a request. Run it from an AgentController, or give this agent tools that do not go through the MCP registry.`);return $.execute({kind:"local",req:K},J.name,Z,W)}})}function ZZ($,J,Q){let Z=$.nativeTool(J.name);return j$.create({name:J.name,description:J.description,inputSchema:J.inputSchema,...J.outputSchema?{outputSchema:J.outputSchema}:{},requiresApproval:$.nativeApproval(J.name),deferred:Q,...Z.timeoutMs!==void 0?{timeoutMs:Z.timeoutMs}:{},...Z.async?{async:Z.async}:{},execute:(W,K)=>{let X=h.getStore()?.req;return $.startNative(X?{kind:"local",req:X}:void 0,J.name,W,K)}})}function WZ($){if($==="auto")return;let J=/^(\d+)x(\d+)$/.exec($);if(!J)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify($)}.`);let Q=Number(J[1]),Z=Number(J[2]);if(Q%16!==0||Z%16!==0)throw Error(`Image size ${$} is not supported: width and height must both be divisible by 16.`);if(Math.max(Q/Z,Z/Q)>3)throw Error(`Image size ${$} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function t8($,J){if($.size!==void 0)try{WZ($.size)}catch(Q){throw Error(`${J}: ${Q.message}`)}if($.background==="transparent"&&$.format==="jpeg")throw Error(`${J}: a transparent background needs "png"; JPEG has no alpha channel.`);if($.compression!==void 0){let Q=$.compression;if(!Number.isInteger(Q)||Q<0||Q>100)throw Error(`${J}: compression is an integer from 0 to 100; got ${Q}.`)}}function r8($,J){if($ instanceof File)return $;let Q=$.type||"image/png",Z=Q==="image/jpeg"?"jpg":Q.split("/")[1]??"png";return new File([$],`${J}.${Z}`,{type:Q})}class NJ{name;provider;settings;constructor($){let{name:J,provider:Q,...Z}=$;t8(Z,`ImageModel "${J}"`),this.name=J,this.provider=Q,this.settings=Z}static create($){return new NJ($)}async generate($){let J=this.merge($);return this.present(await this.provider.generate({prompt:$.prompt,...J,signal:$.signal}))}async edit($){let J=this.merge($);return this.present(await this.provider.edit({prompt:$.prompt,...J,images:$.images.map((Q,Z)=>r8(Q,`image-${Z}`)),...$.mask?{mask:r8($.mask,"mask")}:{},signal:$.signal}))}present($){return e8(this.provider.model,$.usage),KZ($)}merge($){let J={...this.settings,...$.size!==void 0?{size:$.size}:{},...$.quality!==void 0?{quality:$.quality}:{},...$.background!==void 0?{background:$.background}:{},...$.format!==void 0?{format:$.format}:{},...$.compression!==void 0?{compression:$.compression}:{}};return t8(J,`ImageModel "${this.name}"`),J}}function KZ($){return{image:new Blob([$.bytes],{type:$.mimeType}),mimeType:$.mimeType,size:$.size,usage:$.usage}}function u($){return typeof process>"u"?void 0:process.env?.[$]}var XZ="preview";function $9($){let J=$.trim().replace(/\/+$/,"");if(!J)return"";return`${J.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function YZ($){return/^\d{4}-\d{2}-\d{2}/.test($)?"":"/v1"}function Y$($,J={}){return{base:($.baseURL??u("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=$.apiKey??u("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...$.headers}},timeoutMs:$.timeoutMs??J.timeoutMs??120000,maxRetries:$.maxRetries??2}}function J9($){let J=$.baseURL??$.endpoint??u("AZURE_OPENAI_ENDPOINT");if(J)return $9(J);let Q=$.resourceName??u("AZURE_OPENAI_RESOURCE_NAME")??u("AZURE_RESOURCE_NAME");return Q?$9(`https://${Q.trim()}.cognitiveservices.azure.com`):""}function G$($,J={}){let Q=$.apiVersion??u("AZURE_OPENAI_API_VERSION")??XZ;return{base:`${J9($)}${YZ(Q)}`,query:`?api-version=${encodeURIComponent(Q)}`,headers:async()=>{if($.getToken)return{authorization:`Bearer ${await $.getToken()}`,...$.headers};let Z=$.apiKey??u("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...$.headers}},timeoutMs:$.timeoutMs??J.timeoutMs??120000,maxRetries:$.maxRetries??2}}function Q9($,J={}){return{...G$($,J),base:`${J9($)}/v1`,query:""}}var GZ=500,W9=20000;function VZ($,J){if(!$)return;let Q=$.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-J)}function k$($,J){let Q=Math.min(W9,GZ*2**$);return Math.round(Q*(0.5+J()*0.5))}function HZ($){return $===429||$===408||$===409||$>=500}function zZ($,J){return HZ($)&&T(J).retryable}function K9($){return $.reason??new DOMException("The operation was aborted.","AbortError")}function X9($,J){return new Promise((Q,Z)=>{let W=setTimeout(Q,$);J?.addEventListener("abort",()=>{clearTimeout(W),Z(K9(J))},{once:!0})})}async function UJ($,J,Q=X9){if(!J)return await Q($);J.throwIfAborted();let Z;try{await Promise.race([Q($,J),new Promise((W,K)=>{Z=()=>K(K9(J)),J.addEventListener("abort",Z,{once:!0})})])}finally{if(Z)J.removeEventListener("abort",Z)}}async function c($,J,Q){let Z=Q.fetchImpl??((H,D)=>fetch(H,D)),W=Q.sleep??X9,K=Q.random??Math.random,X=Q.now??Date.now,G=Math.max(0,Q.maxRetries),V=(H)=>UJ(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 Z9(Q.timeoutMs):O,F&&Q.retryTimeouts===!1)throw Y;if(H===G)throw Y;await V(k$(H,K));continue}if(U!==void 0)clearTimeout(U);if(N.ok)return N;Q.signal?.removeEventListener("abort",z);let B=await DZ(N),P=new I(N.status,B,N.headers.get("x-request-id")??void 0,VZ(N.headers.get("retry-after"),X()));if(H===G||!zZ(N.status,P))throw P;let L=P.retryAfter??(N.status===429?T(P).retryAfter:void 0);await V(L===void 0?k$(H,K):Math.min(L,W9)),Y=P}throw Y??Error("Provider request failed with no response.")}async function DZ($){let J;try{J=await $.text()}catch{return null}try{return JSON.parse(J)}catch{return J}}var LJ=300000;function OJ($){return{generationsUrl:`${$.base}/images/generations${$.query}`,editsUrl:`${$.base}/images/edits${$.query}`,headers:$.headers,timeoutMs:$.timeoutMs,maxRetries:$.maxRetries}}class x$ extends Error{code;retryable;retryAfter;constructor($,J={}){super($.message,J);if(this.name="ImageRequestError",this.code=$.code,this.retryable=$.retryable,$.retryAfter!==void 0)this.retryAfter=$.retryAfter}}var FZ={png:"image/png",jpeg:"image/jpeg"};function BZ($){let J=Number($?.input_tokens??0),Q=Number($?.output_tokens??0),Z={inputTokens:J,outputTokens:Q,totalTokens:Number($?.total_tokens??J+Q)},W=$?.input_tokens_details?.image_tokens;if(typeof W==="number")Z.imageInputTokens=W;let K=$?.output_tokens_details?.image_tokens;if(typeof K==="number")Z.imageOutputTokens=K;return Z}function PZ($){let J=atob($),Q=new Uint8Array(J.length);for(let Z=0;Z<J.length;Z++)Q[Z]=J.charCodeAt(Z);return Q}function NZ($){let Q=$?.data?.[0]?.b64_json;if(typeof Q!=="string"||Q.length===0)throw new x$({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let Z=typeof $.output_format==="string"?$.output_format:"png";return{bytes:PZ(Q),mimeType:FZ[Z]??`image/${Z}`,size:typeof $.size==="string"?$.size:"",...typeof $.background==="string"?{background:$.background}:{},usage:BZ($.usage)}}async function Y9($,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 x$(T(K),{cause:K})}return NZ(await W.json())}async function G9($,J,Q={}){return await Y9($.generationsUrl,{method:"POST",headers:{...await $.headers(),"content-type":"application/json"},body:JSON.stringify(J)},$,Q)}async function V9($,J,Q={}){return await Y9($.editsUrl,{method:"POST",headers:await $.headers(),body:J},$,Q)}class q${static models(){return[]}modelName(){return this.model}async generate($){return await G9(this.endpoint(),this.body($),{signal:$.signal})}async edit($){let J=new FormData;for(let[Q,Z]of Object.entries(this.body($)))if(Z!==void 0)J.set(Q,String(Z));for(let Q of $.images)J.append("image[]",Q,Q.name);if($.mask)J.set("mask",$.mask,$.mask.name);return await V9(this.endpoint(),J,{signal:$.signal})}body($){return{model:this.modelName(),prompt:$.prompt,...$.size?{size:$.size}:{},...$.quality?{quality:$.quality}:{},...$.background?{background:$.background}:{},...$.format?{output_format:$.format}:{},...$.compression!==void 0?{output_compression:$.compression}:{}}}normalizeError($){return T($)}}var H9=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class CJ extends q${model;config;constructor($,J={}){super();this.model=$,this.config=J}static model($,J){return new CJ($,J)}static models(){return H9}endpoint(){return OJ(Y$(this.config,{timeoutMs:LJ}))}}class _J extends q${model;config;constructor($,J={}){super();this.model=$,this.config=J}static model($,J){return new _J($,J)}static models(){return H9}modelName(){return this.config.deployment??this.model}endpoint(){return OJ(G$(this.config,{timeoutMs:LJ}))}}var F9=3;function MJ($){let J=new Map;for(let Q of $)for(let Z of Q.content??[]){if(Z.type!=="file"||!Z.fileId||J.has(Z.fileId))continue;J.set(Z.fileId,{name:Z.name,mimeType:Z.mimeType})}return J}function B9($,J,Q=new Map){if(!(J instanceof I))return[];if(J.status!==400&&J.status!==404)return[];let Z=LZ(J.body);if(!Z)return[];let W=UZ($.input);if(W.length===0)return[];let K=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(K){let Y=$.input[Number(K[1])],H=AJ(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=D9(W.map((Y)=>Y.fileId).filter((Y)=>OZ(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=D9(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 P9($,J,Q=new Map){return{...$,input:$.input.map((Z)=>{let W=AJ(Z);if(!W.some((K)=>z9(K,J)))return Z;return{...Z,content:W.map((K)=>z9(K,J)?{type:"input_text",text:SJ(Q.get(String(K.file_id))?.name)}:K)}})}}function SJ($){return`[${$?`attachment ${JSON.stringify($)}`:"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 z9($,J){return typeof $.file_id==="string"&&J.has($.file_id)}function AJ($){let J=$?.content;return Array.isArray(J)?J:[]}function UZ($){let J=[];for(let Q of $)for(let Z of AJ(Q))if(typeof Z.file_id==="string"&&Z.file_id)J.push({type:String(Z.type),fileId:Z.file_id});return J}function LZ($){if(!$||typeof $!=="object")return null;let J=$,Q=J.error&&typeof J.error==="object"?J.error:$;return{message:typeof Q.message==="string"?Q.message:void 0,param:typeof Q.param==="string"?Q.param:void 0}}function OZ($,J){let Q=J.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${Q}($|[^A-Za-z0-9_-])`).test($)}function D9($){return[...new Set($)]}async function*CZ($){let J="",Q="",Z=[],W,K=()=>{if(Z.length===0&&!Q)return null;let V={event:Q,data:Z.join(`
|
|
142
|
+
)`,`CREATE INDEX IF NOT EXISTS "${J}_scope_kind_created_at_idx" ON "${J}"("scope", "kind", "created_at")`,`CREATE INDEX IF NOT EXISTS "${J}_expires_at_idx" ON "${J}"("expires_at")`,`CREATE UNIQUE INDEX IF NOT EXISTS "${J}_scope_key_key" ON "${J}"("scope", "key")`]}var h8={n:0,mean:0,stddev:0,low:null,high:null};function h($){let J=[0.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-0.13857109526572012,0.000009984369578019572,0.00000015056327351493116];if($<0.5)return Math.log(Math.PI/Math.sin(Math.PI*$))-h(1-$);$-=1;let Q=J[0],Z=$+7.5;for(let W=1;W<9;W++)Q+=J[W]/($+W);return 0.5*Math.log(2*Math.PI)+($+0.5)*Math.log(Z)-Z+Math.log(Q)}function y8($,J,Q){let W=1,K=1-($+J)*Q/($+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*(J-G)*Q/(($+V-1)*($+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=-($+G)*($+J+G)*Q/(($+V)*($+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 sQ($,J,Q){if($<=0)return 0;if($>=1)return 1;let Z=Math.exp(h(J+Q)-h(J)-h(Q)+J*Math.log($)+Q*Math.log(1-$));return $<(J+1)/(J+Q+2)?Z*y8(J,Q,$)/J:1-Z*y8(Q,J,1-$)/Q}function GJ($,J){return sQ(J/(J+$*$),J/2,0.5)}function aQ($){if(!($>0))return Number.POSITIVE_INFINITY;let J=1.959964,Q=2;while(GJ(Q,$)>0.05)Q*=2;for(let Z=0;Z<100;Z++){let W=(J+Q)/2;if(GJ(W,$)>0.05)J=W;else Q=W}return(J+Q)/2}function tQ($,J,Q,Z){let W=$+Q,K=J+Z,X=(H,D)=>h(H+1)-h(D+1)-h(H-D+1),G=(H)=>Math.exp(X(J,H)+X(Z,W-H)-X(K,W)),V=G($),Y=0;for(let H=Math.max(0,W-Z);H<=Math.min(J,W);H++){let D=G(H);if(D<=V*1.0000001)Y+=D}return Math.min(1,Y)}function g8($,J){if($.length<2)return 0;let Q=$.reduce((W,K)=>W+(K-J)**2,0),Z=Math.sqrt(Q/($.length-1));return Z<0.000000000001*Math.max(1,Math.abs(J))?0:Z}function VJ($){let J=$.length;if(J===0)return h8;let Q=$.map((G)=>G?1:0),Z=Q.reduce((G,V)=>G+V,0)/J,W=3.841458881296,K=(Z+W/(2*J))/(1+W/J),X=1.959964*Math.sqrt(Z*(1-Z)/J+W/(4*J*J))/(1+W/J);return{n:J,mean:Z,stddev:g8(Q,Z),low:Math.max(0,K-X),high:Math.min(1,K+X)}}function HJ($){let J=$.length;if(J===0)return h8;let Q=$.reduce((K,X)=>K+X,0)/J,Z=g8($,Q);if(J<2||Z===0)return{n:J,mean:Q,stddev:Z,low:null,high:null};let W=aQ(J-1)*Z/Math.sqrt(J);return{n:J,mean:Q,stddev:Z,low:Q-W,high:Q+W}}function W$($,J,Q){return{before:$.mean,after:J.mean,delta:J.mean-$.mean,p:Q,pAdjusted:Q,significant:!1}}function u8($,J){if($.n===0||J.n===0)return W$($,J,null);let Q=(Z)=>Math.round(Z.mean*Z.n);return W$($,J,tQ(Q($),$.n,Q(J),J.n))}function c8($,J){if($.n<2||J.n<2)return W$($,J,null);let Q=$.stddev**2/$.n,Z=J.stddev**2/J.n,W=Math.sqrt(Q+Z);if(W===0)return W$($,J,null);let K=(Q+Z)**2/(Q**2/($.n-1)+Z**2/(J.n-1));return W$($,J,GJ((J.mean-$.mean)/W,K))}function m8($,J,Q){if(Q==="holm"){let Z=$.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 $)Z.pAdjusted=Z.p;for(let Z of $)Z.significant=Z.pAdjusted!==null&&Z.pAdjusted<J&&Z.delta!==0}class T${name;cases;runs;concurrency;graders;pricing;task;constructor($){this.name=$.name,this.cases=$.cases,this.runs=$.runs??1,this.concurrency=$.concurrency??1,this.task=$.task,this.graders=typeof $.graders==="function"?$.graders({judge:(J)=>T$.judge(J)}):$.graders,this.pricing=$.pricing}static create($){let J=`The eval "${$.name}"`;K$($.runs,J,"runs"),K$($.concurrency,J,"concurrency");let Q=new Set;for(let W of $.cases){if(Q.has(W.id))throw Error(`${J} has two cases with the id "${W.id}".`);Q.add(W.id)}let Z=new T$($);for(let[W,K]of Object.entries(Z.graders))if(typeof K!=="function"&&K.kind==="judge")K$(K.samples,`${J}'s judge "${W}"`,"samples");return Z}static judge($){return{...$,kind:"judge"}}static compare($,J,Q={}){return o8($,J,Q)}static format($,J={}){return JZ($,J)}async run($={}){let J=`${this.name}.run`;K$($.runs,J,"runs"),K$($.concurrency,J,"concurrency");let Q=$.only?new Set($.only):null;if(Q){let P=[...Q].filter((B)=>!this.cases.some((U)=>U.id===B));if(P.length>0)throw Error(`The eval "${this.name}" has no case ${P.map((B)=>`"${B}"`).join(", ")}.`)}let Z=$.runs??this.runs,W=Date.now(),K=new AbortController,X=$.signal?AbortSignal.any([$.signal,K.signal]):K.signal,G=this.cases.filter((P)=>!Q||Q.has(P.id)),V={};for(let[P,B]of Object.entries(this.graders)){if(X.aborted)break;if(typeof B==="function"||B.kind!=="judge"||!B.calibration)continue;V[P]=await this.calibrate(B,X)}let Y=G.flatMap((P)=>Array.from({length:Z},(B,U)=>({test:P,run:U+1}))),H=Array.from({length:Y.length}),D=0,z,F=async()=>{while(D<Y.length&&!X.aborted){let P=D++,B=Y[P],U=await this.sample(B.test,B.run,X,$.keepOutputs??!1);H[P]=U;try{$.onSample?.(U)}catch(L){z??={error:L},K.abort(L)}}},C=Math.min($.concurrency??this.concurrency,Y.length);if(await Promise.all(Array.from({length:C},F)),z)throw z.error;let N=H.filter((P)=>P!==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((P)=>P.id)})}async sample($,J,Q,Z){let W=Date.now(),K,X,G=await X$(async()=>{try{K=await this.task($.input,{case:$,run:J,signal:Q})}catch(C){X=a8(C)}}),V={},Y=!1,H=await X$(async()=>{if(X!==void 0)return;let C={case:$,input:$.input,run:J};for(let[N,P]of Object.entries(this.graders)){if($.skip?.includes(N))continue;let B=await p8(P,K,C,Q);if(!B)continue;if(V[N]=B,!B.pass&&typeof P!=="function"&&P.gate)Y=!0}}),D=Object.values(V).map((C)=>C.score),z=X===void 0&&D.length===0,F=this.pricing?zJ(this.pricing,G.byModel).cost+zJ(this.pricing,H.byModel).cost:void 0;return{case:$.id,run:J,pass:X===void 0&&!z&&Object.values(V).every((C)=>C.pass),excluded:Y||z,...z?{ungraded:!0}:{},score:X!==void 0||z?0:s8(D),grades:V,...X!==void 0?{error:X}:{},...Z&&X===void 0?{output:K}:{},usage:G.usage,byModel:eQ(G.byModel,H.byModel),judgeUsage:H.usage,...F!==void 0?{cost:F}:{},durationMs:Date.now()-W}}async calibrate($,J){let Q=$.calibration,Z=[],W=0,K=await X$(async()=>{for(let[V,Y]of Q.examples.entries()){if(J.aborted)break;let H=Y.id??`example-${V+1}`,D={case:{id:H,input:Y.input},input:Y.input,run:0},z=await p8($,Y.output,D,J),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=$.filter((C)=>C.case===z.id);if(F.length===0)continue;G[z.id]={...l8(F),graders:d8(F,X)}}let V=R(),Y=R(),H={};for(let z of $){V=E(V,z.usage),Y=E(Y,z.judgeUsage);for(let[F,C]of Object.entries(z.byModel))H[F]=E(H[F]??R(),C)}let D=this.pricing?zJ(this.pricing,H):void 0;return{name:this.name,startedAt:Z,durationMs:W,runs:Q,aborted:K.aborted,planned:K.planned,samples:$,cases:G,graders:d8($,X),calibration:J,totals:{...l8($),usage:V,judgeUsage:Y,byModel:H,...D?{cost:D.cost}:{},unpriced:D?D.unpriced:Object.keys(H)}}}}async function p8($,J,Q,Z){let W=typeof $==="function"?0.5:$.threshold??0.5;try{if(typeof $==="function")return DJ(await $(J,Q),W);if($.kind!=="judge")return DJ(await $.check(J,Q),W);return await rQ($,J,Q,W,Z)}catch(K){return{pass:!1,score:0,error:a8(K)}}}async function rQ($,J,Q,Z,W){let K=await $.prompt(J,Q),X=typeof K==="string"?{prompt:K}:K,G=[];for(let D=0;D<($.samples??1)&&!W.aborted;D++){let z=await FJ({signal:W,provider:$.provider,...$.instructions!==void 0?{instructions:$.instructions}:{},...X,output:$.output,...$.reasoning!==void 0?{reasoning:$.reasoning}:{},...$.maxOutputTokens!==void 0?{maxOutputTokens:$.maxOutputTokens}:{},...$.temperature!==void 0?{temperature:$.temperature}:{},logErrors:!1});if(!z.ok){G.push({pass:!1,score:0,error:`The judge failed: ${z.error.message}`});continue}let F=DJ($.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:s8(G.map((D)=>D.score)),...Y.length>0?{note:Y.join(" | ")}:{},...H.length===G.length?{error:H.join(" | ")}:{}}}function DJ($,J){if($===null||$===void 0)return null;if(typeof $==="boolean")return{pass:$,score:$?1:0};if(typeof $==="number"){if(!Number.isFinite($))throw Error(`A grader answered the score ${$}.`);let Q=i8($);return{pass:Q>=J,score:Q}}return{pass:$.pass,score:$.score===void 0?$.pass?1:0:i8($.score),...$.note!==void 0?{note:$.note}:{}}}function l8($){let J=$.filter((Q)=>!Q.excluded);return{samples:$.length,kept:J.length,passed:J.filter((Q)=>Q.pass).length,errors:$.filter((Q)=>Q.error!==void 0).length,passRate:VJ(J.map((Q)=>Q.pass)),score:HJ(J.map((Q)=>Q.score))}}function d8($,J){let Q=$.filter((W)=>!W.excluded),Z=[...new Set($.flatMap((W)=>Object.keys(W.grades)))];return Object.fromEntries(Z.map((W)=>{let X=(J.has(W)?$:Q).flatMap((G)=>G.grades[W]?[G.grades[W]]:[]);return[W,{passRate:VJ(X.map((G)=>G.pass)),score:HJ(X.map((G)=>G.score))}]}))}function zJ($,J){let Q=0,Z=[];for(let[W,K]of Object.entries(J)){let X=n8($,W,K);if(X===void 0){Z.push(W);continue}Q+=X}return{cost:Q,unpriced:Z}}function eQ(...$){let J={};for(let Q of $)for(let[Z,W]of Object.entries(Q))J[Z]=E(J[Z]??R(),W);return J}function o8($,J,Q){for(let[P,B]of[["baseline",$],["current report",J]])if(B.aborted)throw Error(`Eval.compare: the ${P} for "${B.name}" was aborted (${B.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=(P,B,U)=>{let L={label:P,passRate:u8(B.passRate,U.passRate),score:c8(B.score,U.score)};return K.push(L),{passRate:L.passRate,score:L.score}},G=(P,B,U)=>Object.fromEntries(Object.keys(U).filter((L)=>(L in B)).map((L)=>[L,X(`${P} ${L}`,B[L],U[L])])),V=(P,B)=>({fromCurrent:P.filter((U)=>!B.includes(U)),fromBaseline:B.filter((U)=>!P.includes(U))}),Y=X("total",$.totals,J.totals),H=G("case",$.cases,J.cases),D=G("grader",$.graders,J.graders),z=K.flatMap((P)=>[P.passRate,P.score]);m8(z,Z,W);let F={cases:V([...new Set([...$.planned??[],...Object.keys($.cases)])],[...new Set([...J.planned??[],...Object.keys(J.cases)])]),graders:V(Object.keys($.graders),Object.keys(J.graders))},C=[...F.cases.fromCurrent.map((P)=>`case ${P}: in the baseline, missing from this report`),...F.graders.fromCurrent.map((P)=>`grader ${P}: in the baseline, missing from this report`)],N=[];for(let P of K)for(let[B,U]of[["pass rate",P.passRate],["score",P.score]]){if(!U.significant)continue;let L=`${P.label}: ${B} ${U.before.toFixed(2)} \u2192 ${U.after.toFixed(2)} (p = ${$Z(U.pAdjusted)})`;(U.delta<0?C:N).push(L)}return{totals:Y,cases:H,graders:D,missing:F,comparisons:z.filter((P)=>P.p!==null).length,alpha:Z,adjust:W,regressions:C,improvements:N}}function $Z($){return $<0.001?"<0.001":$.toFixed(3)}function JZ($,J){let Q=J.baseline&&!J.baseline.aborted&&!$.aborted?o8(J.baseline,$,J):void 0,{totals:Z}=$,W=[];if(W.push(`eval ${$.name}: ${Z.samples} samples, ${Z.kept} kept, ${Z.passed} passed, ${Z.errors} errors (${($.durationMs/1000).toFixed(1)}s)`),$.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((C)=>C[F].length))),z=(F)=>F.map((C,N)=>C.padEnd(D[N])).join(" ").trimEnd();W.push("",z([Y,"n","pass rate","score"]),...H.map(z))};G("case",Object.entries($.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($.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($.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 s8($){return $.reduce((J,Q)=>J+Q,0)/$.length}function i8($){return Math.min(1,Math.max(0,$))}function a8($){return $ instanceof Error?$.message:String($)}function K$($,J,Q){if($===void 0||Number.isInteger($)&&$>=1)return;throw Error(`${J} sets \`${Q}\` to ${String($)}, but it has to be a whole number of at least 1.`)}var QZ=/^[A-Za-z0-9_-]{1,64}$/;function ZZ($,J){let Q=WZ(J)?J:{filter:J},Z=Q.deferred===!0,W=$.descriptors(Q.filter);if(!Q.namespaces)return W.map((H)=>BJ($,H,Z));let K=Object.entries(Q.namespaces),X=new Set($.descriptors().flatMap((H)=>H.tags));for(let[H,D]of K){if(!QZ.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(BJ($,H,Z));else G.get(D).push(BJ($,H,!1))}let Y=[];for(let[H,D]of K){let z=G.get(H);if(z.length===0)continue;Y.push(PJ.create({name:H,description:D.description,tools:z,deferred:D.deferred??Z}))}return[...Y,...V]}function WZ($){return typeof $==="object"&&$!==null&&(("filter"in $)||("namespaces"in $)||("deferred"in $))}function BJ($,J,Q){if(J.kind==="tool")return KZ($,J,Q);return j$.create({name:J.name,description:J.description,inputSchema:J.inputSchema,...J.outputSchema?{outputSchema:J.outputSchema}:{},requiresApproval:J.requiresApproval,deferred:Q,execute:(Z,W)=>{let K=g.getStore()?.req;if(!K)throw new u(`"${J.name}" calls an api route as the user who started this run, and this run was not started inside a request. Run it from an AgentController, or give this agent tools that do not go through the MCP registry.`);return $.execute({kind:"local",req:K},J.name,Z,W)}})}function KZ($,J,Q){let Z=$.nativeTool(J.name);return j$.create({name:J.name,description:J.description,inputSchema:J.inputSchema,...J.outputSchema?{outputSchema:J.outputSchema}:{},requiresApproval:$.nativeApproval(J.name),deferred:Q,...Z.timeoutMs!==void 0?{timeoutMs:Z.timeoutMs}:{},...Z.async?{async:Z.async}:{},execute:(W,K)=>{let X=g.getStore()?.req;return $.startNative(X?{kind:"local",req:X}:void 0,J.name,W,K)}})}function XZ($){if($==="auto")return;let J=/^(\d+)x(\d+)$/.exec($);if(!J)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify($)}.`);let Q=Number(J[1]),Z=Number(J[2]);if(Q%16!==0||Z%16!==0)throw Error(`Image size ${$} is not supported: width and height must both be divisible by 16.`);if(Math.max(Q/Z,Z/Q)>3)throw Error(`Image size ${$} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function t8($,J){if($.size!==void 0)try{XZ($.size)}catch(Q){throw Error(`${J}: ${Q.message}`)}if($.background==="transparent"&&$.format==="jpeg")throw Error(`${J}: a transparent background needs "png"; JPEG has no alpha channel.`);if($.compression!==void 0){let Q=$.compression;if(!Number.isInteger(Q)||Q<0||Q>100)throw Error(`${J}: compression is an integer from 0 to 100; got ${Q}.`)}}function r8($,J){if($ instanceof File)return $;let Q=$.type||"image/png",Z=Q==="image/jpeg"?"jpg":Q.split("/")[1]??"png";return new File([$],`${J}.${Z}`,{type:Q})}class NJ{name;provider;settings;constructor($){let{name:J,provider:Q,...Z}=$;t8(Z,`ImageModel "${J}"`),this.name=J,this.provider=Q,this.settings=Z}static create($){return new NJ($)}async generate($){let J=this.merge($);return this.present(await this.provider.generate({prompt:$.prompt,...J,signal:$.signal}))}async edit($){let J=this.merge($);return this.present(await this.provider.edit({prompt:$.prompt,...J,images:$.images.map((Q,Z)=>r8(Q,`image-${Z}`)),...$.mask?{mask:r8($.mask,"mask")}:{},signal:$.signal}))}present($){return e8(this.provider.model,$.usage),YZ($)}merge($){let J={...this.settings,...$.size!==void 0?{size:$.size}:{},...$.quality!==void 0?{quality:$.quality}:{},...$.background!==void 0?{background:$.background}:{},...$.format!==void 0?{format:$.format}:{},...$.compression!==void 0?{compression:$.compression}:{}};return t8(J,`ImageModel "${this.name}"`),J}}function YZ($){return{image:new Blob([$.bytes],{type:$.mimeType}),mimeType:$.mimeType,size:$.size,usage:$.usage}}function c($){return typeof process>"u"?void 0:process.env?.[$]}var GZ="preview";function $9($){let J=$.trim().replace(/\/+$/,"");if(!J)return"";return`${J.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function VZ($){return/^\d{4}-\d{2}-\d{2}/.test($)?"":"/v1"}function Y$($,J={}){return{base:($.baseURL??c("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=$.apiKey??c("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...$.headers}},timeoutMs:$.timeoutMs??J.timeoutMs??120000,streamIdleTimeoutMs:$.streamIdleTimeoutMs??120000,maxRetries:$.maxRetries??2}}function J9($){let J=$.baseURL??$.endpoint??c("AZURE_OPENAI_ENDPOINT");if(J)return $9(J);let Q=$.resourceName??c("AZURE_OPENAI_RESOURCE_NAME")??c("AZURE_RESOURCE_NAME");return Q?$9(`https://${Q.trim()}.cognitiveservices.azure.com`):""}function G$($,J={}){let Q=$.apiVersion??c("AZURE_OPENAI_API_VERSION")??GZ;return{base:`${J9($)}${VZ(Q)}`,query:`?api-version=${encodeURIComponent(Q)}`,headers:async()=>{if($.getToken)return{authorization:`Bearer ${await $.getToken()}`,...$.headers};let Z=$.apiKey??c("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...$.headers}},timeoutMs:$.timeoutMs??J.timeoutMs??120000,streamIdleTimeoutMs:$.streamIdleTimeoutMs??120000,maxRetries:$.maxRetries??2}}function Q9($,J={}){return{...G$($,J),base:`${J9($)}/v1`,query:""}}var HZ=500,W9=20000;function zZ($,J){if(!$)return;let Q=$.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-J)}function k$($,J){let Q=Math.min(W9,HZ*2**$);return Math.round(Q*(0.5+J()*0.5))}function DZ($){return $===429||$===408||$===409||$>=500}function FZ($,J){return DZ($)&&j(J).retryable}function K9($){return $.reason??new DOMException("The operation was aborted.","AbortError")}function X9($,J){return new Promise((Q,Z)=>{let W=setTimeout(Q,$);J?.addEventListener("abort",()=>{clearTimeout(W),Z(K9(J))},{once:!0})})}async function UJ($,J,Q=X9){if(!J)return await Q($);J.throwIfAborted();let Z;try{await Promise.race([Q($,J),new Promise((W,K)=>{Z=()=>K(K9(J)),J.addEventListener("abort",Z,{once:!0})})])}finally{if(Z)J.removeEventListener("abort",Z)}}async function m($,J,Q){let Z=Q.fetchImpl??((H,D)=>fetch(H,D)),W=Q.sleep??X9,K=Q.random??Math.random,X=Q.now??Date.now,G=Math.max(0,Q.maxRetries),V=(H)=>UJ(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,C=Q.timeoutMs>0?setTimeout(()=>{F=!0,D.abort()},Q.timeoutMs):void 0,N;try{N=await Z($,{...J,signal:D.signal})}catch(L){if(C!==void 0)clearTimeout(C);if(Q.signal?.removeEventListener("abort",z),Q.signal?.aborted)throw L;if(Y=F?new Z9(Q.timeoutMs):L,F&&Q.retryTimeouts===!1)throw Y;if(H===G)throw Y;await V(k$(H,K));continue}if(C!==void 0)clearTimeout(C);if(N.ok)return N;Q.signal?.removeEventListener("abort",z);let P=await BZ(N),B=new w(N.status,P,N.headers.get("x-request-id")??void 0,zZ(N.headers.get("retry-after"),X()));if(H===G||!FZ(N.status,B))throw B;let U=B.retryAfter??(N.status===429?j(B).retryAfter:void 0);await V(U===void 0?k$(H,K):Math.min(U,W9)),Y=B}throw Y??Error("Provider request failed with no response.")}async function BZ($){let J;try{J=await $.text()}catch{return null}try{return JSON.parse(J)}catch{return J}}function Y9($,J,Q){if(!$||!(J>0))return $;let Z=$.getReader();return new ReadableStream({async pull(W){let K,X,G=new Promise((V,Y)=>{K=setTimeout(()=>{X=Q(),Y(X)},J)});try{let V=await Promise.race([Z.read(),G]);if(V.done)W.close();else W.enqueue(V.value)}catch(V){let Y=X??V;W.error(Y),Z.cancel(Y).catch(()=>{})}finally{clearTimeout(K)}},cancel(W){return Z.cancel(W)}},{highWaterMark:0})}var LJ=300000;function CJ($){return{generationsUrl:`${$.base}/images/generations${$.query}`,editsUrl:`${$.base}/images/edits${$.query}`,headers:$.headers,timeoutMs:$.timeoutMs,maxRetries:$.maxRetries}}class x$ extends Error{code;retryable;retryAfter;constructor($,J={}){super($.message,J);if(this.name="ImageRequestError",this.code=$.code,this.retryable=$.retryable,$.retryAfter!==void 0)this.retryAfter=$.retryAfter}}var PZ={png:"image/png",jpeg:"image/jpeg"};function NZ($){let J=Number($?.input_tokens??0),Q=Number($?.output_tokens??0),Z={inputTokens:J,outputTokens:Q,totalTokens:Number($?.total_tokens??J+Q)},W=$?.input_tokens_details?.image_tokens;if(typeof W==="number")Z.imageInputTokens=W;let K=$?.output_tokens_details?.image_tokens;if(typeof K==="number")Z.imageOutputTokens=K;return Z}function UZ($){let J=atob($),Q=new Uint8Array(J.length);for(let Z=0;Z<J.length;Z++)Q[Z]=J.charCodeAt(Z);return Q}function LZ($){let Q=$?.data?.[0]?.b64_json;if(typeof Q!=="string"||Q.length===0)throw new x$({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let Z=typeof $.output_format==="string"?$.output_format:"png";return{bytes:UZ(Q),mimeType:PZ[Z]??`image/${Z}`,size:typeof $.size==="string"?$.size:"",...typeof $.background==="string"?{background:$.background}:{},usage:NZ($.usage)}}async function G9($,J,Q,Z){let W;try{W=await m($,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 x$(j(K),{cause:K})}return LZ(await W.json())}async function V9($,J,Q={}){return await G9($.generationsUrl,{method:"POST",headers:{...await $.headers(),"content-type":"application/json"},body:JSON.stringify(J)},$,Q)}async function H9($,J,Q={}){return await G9($.editsUrl,{method:"POST",headers:await $.headers(),body:J},$,Q)}class q${static models(){return[]}modelName(){return this.model}async generate($){return await V9(this.endpoint(),this.body($),{signal:$.signal})}async edit($){let J=new FormData;for(let[Q,Z]of Object.entries(this.body($)))if(Z!==void 0)J.set(Q,String(Z));for(let Q of $.images)J.append("image[]",Q,Q.name);if($.mask)J.set("mask",$.mask,$.mask.name);return await H9(this.endpoint(),J,{signal:$.signal})}body($){return{model:this.modelName(),prompt:$.prompt,...$.size?{size:$.size}:{},...$.quality?{quality:$.quality}:{},...$.background?{background:$.background}:{},...$.format?{output_format:$.format}:{},...$.compression!==void 0?{output_compression:$.compression}:{}}}normalizeError($){return j($)}}var z9=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class OJ extends q${model;config;constructor($,J={}){super();this.model=$,this.config=J}static model($,J){return new OJ($,J)}static models(){return z9}endpoint(){return CJ(Y$(this.config,{timeoutMs:LJ}))}}class _J extends q${model;config;constructor($,J={}){super();this.model=$,this.config=J}static model($,J){return new _J($,J)}static models(){return z9}modelName(){return this.config.deployment??this.model}endpoint(){return CJ(G$(this.config,{timeoutMs:LJ}))}}var B9=3;function MJ($){let J=new Map;for(let Q of $)for(let Z of Q.content??[]){if(Z.type!=="file"||!Z.fileId||J.has(Z.fileId))continue;J.set(Z.fileId,{name:Z.name,mimeType:Z.mimeType})}return J}function P9($,J,Q=new Map){if(!(J instanceof w))return[];if(J.status!==400&&J.status!==404)return[];let Z=OZ(J.body);if(!Z)return[];let W=CZ($.input);if(W.length===0)return[];let K=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(K){let Y=$.input[Number(K[1])],H=AJ(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=F9(W.map((Y)=>Y.fileId).filter((Y)=>_Z(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=F9(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 N9($,J,Q=new Map){return{...$,input:$.input.map((Z)=>{let W=AJ(Z);if(!W.some((K)=>D9(K,J)))return Z;return{...Z,content:W.map((K)=>D9(K,J)?{type:"input_text",text:SJ(Q.get(String(K.file_id))?.name)}:K)}})}}function SJ($){return`[${$?`attachment ${JSON.stringify($)}`:"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 D9($,J){return typeof $.file_id==="string"&&J.has($.file_id)}function AJ($){let J=$?.content;return Array.isArray(J)?J:[]}function CZ($){let J=[];for(let Q of $)for(let Z of AJ(Q))if(typeof Z.file_id==="string"&&Z.file_id)J.push({type:String(Z.type),fileId:Z.file_id});return J}function OZ($){if(!$||typeof $!=="object")return null;let J=$,Q=J.error&&typeof J.error==="object"?J.error:$;return{message:typeof Q.message==="string"?Q.message:void 0,param:typeof Q.param==="string"?Q.param:void 0}}function _Z($,J){let Q=J.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${Q}($|[^A-Za-z0-9_-])`).test($)}function F9($){return[...new Set($)]}async function*MZ($){let J="",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=J.indexOf(`
|
|
145
145
|
`);while(Y!==-1){let H=J.slice(0,Y);J=J.slice(Y+1);let D=X(H);if(D)yield D;Y=J.indexOf(`
|
|
146
|
-
`)}}if(J.length>0){let V=X(J);if(V)yield V}let G=K();if(G)yield G}async function*N9($,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 CZ($)){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 J.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=_Z(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",RJ(Y.response?.usage));break}case"response.incomplete":{K=!0;let z=RJ(Y.response?.usage),F=Y.response?.incomplete_details?.reason;if(F==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:MZ(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:SZ(z)},yield G("error",RJ(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",w())}function _Z($){let J=[],Q=[];return U9($.results??$.tools??$.loaded??$.output,J,Q,0),{loaded:EJ(J),namespaces:EJ(Q)}}function U9($,J,Q,Z){if(!Array.isArray($)||Z>4)return;for(let W of $){if(typeof W==="string"){J.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);U9(G,J,Q,Z+1);continue}if(X)J.push(X)}}function EJ($){return $.filter((J,Q)=>$.indexOf(J)===Q)}function MZ($){if(!Array.isArray($))return"The provider's content filter blocked this request.";let Q=[];for(let Z of $){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: ${EJ(Q).join(", ")}.`}function SZ($){let J=typeof $?.message==="string"?$.message:"The provider stream failed.",Q=String($?.code??"").toLowerCase();if(Q==="rate_limit_exceeded")return{code:"rate_limited",message:J,retryable:!0};if(Q==="context_length_exceeded")return{code:"context_length_exceeded",message:J,retryable:!1};if(Q.includes("content_filter"))return{code:"content_filtered",message:J,retryable:!1};return{code:"provider_error",message:J,retryable:!0}}function w(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function RJ($){if(!$)return w();let J=Number($.input_tokens??0),Q=Number($.output_tokens??0),Z={inputTokens:J,outputTokens:Q,totalTokens:Number($.total_tokens??J+Q)},W=$.output_tokens_details?.reasoning_tokens;if(typeof W==="number")Z.reasoningTokens=W;let K=$.input_tokens_details?.cached_tokens;if(typeof K==="number")Z.cachedInputTokens=K;return Z}async function*L9($){if(!$)return;let J=$.getReader(),Q=new TextDecoder;try{while(!0){let{done:W,value:K}=await J.read();if(W)break;if(K)yield Q.decode(K,{stream:!0})}let Z=Q.decode();if(Z)yield Z}finally{J.releaseLock()}}function TJ($){return{responsesUrl:`${$.base}/responses${$.query}`,filesUrl:`${$.base}/files${$.query}`,headers:$.headers,timeoutMs:$.timeoutMs,maxRetries:$.maxRetries}}async function*jJ($,J,Q){let Z=J,W=new Set,K=0,X=Math.max(0,$.maxRetries),G=$.random??Math.random,V,Y=(D)=>{if(!V)return D;let z=A(A(w(),V),D.usage);return V=void 0,{...D,usage:z}},H=()=>Y({type:"finish",reason:"aborted",usage:w()});for(let D=0;;D++){let z;while(z===void 0)try{z=await c($.responsesUrl,{method:"POST",headers:{...await $.headers(),"content-type":"application/json"},body:JSON.stringify(Z)},{maxRetries:$.maxRetries,timeoutMs:$.timeoutMs,signal:Q.signal,fetchImpl:$.fetchImpl,sleep:$.sleep,random:$.random})}catch(B){let P=K<F9?B9(Z,B,Q.files).filter((O)=>!W.has(O)):[];if(P.length>0){K++;let O=T(B).message;for(let j of P)W.add(j),yield{type:"file-rejected",fileId:j,message:O,...a(B)};Z=P9(Z,new Set(P),Q.files);continue}let L=T(B);if(L.code==="aborted"){yield H();return}yield{type:"error",error:L,...a(B)},yield Y({type:"finish",reason:"error",usage:w()});return}let F=[],U=!1,N;try{for await(let B of N9(L9(z.body),{structuredOutput:Q.structuredOutput})){if(U){yield B.type==="finish"?Y(B):B;continue}if(I$(B)){U=!0,yield*F.splice(0),yield B;continue}if(B.type==="error")N=B.error;F.push(B)}}catch(B){let P=T(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:w()});return}N=P,F.push({type:"error",error:P},{type:"finish",reason:"error",usage:w()})}if(U)return;if(N?.retryable&&D<X&&!Q.signal?.aborted){for(let B of F)if(B.type==="finish")V=A(V??w(),B.usage);try{await UJ(k$(D,G),Q.signal,$.sleep)}catch{yield H();return}continue}for(let B of F)yield B.type==="finish"?Y(B):B;return}}async function kJ($,J,Q="user_data"){let Z=new FormData;Z.set("purpose",Q),Z.set("file",J);let K=await(await c($.filesUrl,{method:"POST",headers:await $.headers(),body:Z},{maxRetries:$.maxRetries,timeoutMs:$.timeoutMs,fetchImpl:$.fetchImpl})).json();if(!K?.id)throw Error("The provider accepted the upload but returned no file id.");return K.id}function xJ($){let J=AZ($);if(J.startsWith("gpt-3.5")||J.startsWith("text-")||J.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Q=RZ(J);if(Q?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Q.major>1,toolSearch:O9(Q)};if(Q?.kind==="gpt")return{reasoning:Q.major>=5,structuredOutput:Q.major>4||J.startsWith("gpt-4o")||J.startsWith("gpt-4.1"),fileInput:Q.major>4||J.startsWith("gpt-4o")||J.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:O9(Q)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function O9($){if($.kind==="o")return $.major>=5;return $.major>5||$.major===5&&$.minor>=2}function AZ($){return $.trim().toLowerCase()}function RZ($){let J=/^gpt-(\d+)(?:\.(\d+))?/.exec($);if(J?.[1])return{kind:"gpt",major:Number(J[1]),minor:Number(J[2]??0)};let Q=/^o(\d+)(?:[-.]|$)/.exec($);if(Q?.[1])return{kind:"o",major:Number(Q[1]),minor:0};return null}var EZ={"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 TZ($){if(typeof $!=="string")return;let J;try{J=JSON.parse($)}catch{return}if(!J||typeof J!=="object"||typeof J.type!=="string")return;let Q=EZ[J.type];if(Q)J.type=Q;if(J.type==="response.done"&&J.response?.usage)J.usage=w$(J.response.usage);if(J.type==="conversation.item.input_audio_transcription.completed"&&J.usage)if(J.usage.type==="duration"){let Z=Number(J.usage.seconds);if(Number.isFinite(Z))J.transcriptionSeconds=Z}else J.transcriptionUsage=w$(J.usage);return J}var C9=1,jZ=500;function kZ($,J){let Q=globalThis.WebSocket;if(!Q)throw Error("No global WebSocket: the realtime sideband needs Bun or Node 22+.");return new Q($,{headers:J.headers})}class b${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($){this.init=$,this.callId=$.callId,this.ready=new Promise((J,Q)=>{this.resolveReady=J,this.rejectReady=Q}),this.ready.catch(()=>{}),this.closed=new Promise((J)=>this.resolveClosed=J),this.open()}send($){if(this.finished||this.closing)return;let J=JSON.stringify($);if(this.socket?.readyState===C9)this.socket.send(J);else this.outbox.push(J)}updateSession($){this.send({type:"session.update",session:f$($)})}addItem($){this.send({type:"conversation.item.create",item:$})}addNote($){this.addItem({type:"message",role:"system",content:[{type:"input_text",text:$}]})}functionOutput($,J){this.addItem({type:"function_call_output",call_id:$,output:typeof J==="string"?J:JSON.stringify(J)})}createResponse($={}){let J={};if($.instructions!==void 0)J.instructions=$.instructions;if($.toolChoice!==void 0)J.tool_choice=typeof $.toolChoice==="string"?$.toolChoice:{type:"function",name:$.toolChoice.name};if($.outputModalities)J.output_modalities=$.outputModalities;if($.conversation)J.conversation=$.conversation;if($.metadata)J.metadata=$.metadata;Object.assign(J,$.vendor),this.send(Object.keys(J).length?{type:"response.create",response:J}:{type:"response.create"})}cancelResponse($){this.send($?{type:"response.cancel",response_id:$}:{type:"response.cancel"})}on($){return this.listeners.add($),()=>this.listeners.delete($)}[Symbol.asyncIterator](){let $={queue:this.backlog??[],done:this.finished};return this.backlog=void 0,this.subscribers.add($),{next:async()=>{for(;;){let Q=$.queue.shift();if(Q)return{value:Q,done:!1};if($.done)return this.subscribers.delete($),{value:void 0,done:!0};await new Promise((Z)=>$.wake=Z),$.wake=void 0}},return:async()=>{return $.done=!0,$.queue.length=0,this.subscribers.delete($),{value:void 0,done:!0}}}}close($=1000,J="closed"){if(this.finished||this.closing)return;if(this.closing=!0,this.socket&&this.socket.readyState<=C9)this.socket.close($,J);else this.finish($,J,!0)}async hangup(){try{await this.init.hangup()}catch($){if(this.finalEvent&&!this.finalEvent.byClient&&this.finalEvent.code===1000)return;throw $}this.close(1000,"hangup")}async open(){let $;try{let Q=await this.init.headers();if(this.closing)return this.finish(1000,"closed",!0);$=(this.init.webSocket??kZ)(this.init.url,{headers:Q})}catch(Q){return this.dropped(1006,Q instanceof Error?Q.message:String(Q),!1)}this.socket=$;let J=!1;$.addEventListener("open",()=>{J=!0;let Q=this.everOpened;this.everOpened=!0;let Z=this.failures;this.failures=0;for(let W of this.outbox.splice(0))$.send(W);if(this.resolveReady(),Q)this.emit({type:"sideband.reconnected",attempt:Z})}),$.addEventListener("message",(Q)=>{let Z=TZ(Q.data);if(Z)this.emit(Z)}),$.addEventListener("close",(Q)=>{if(this.socket!==$)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(!(($!==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:$,reason:J,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($){if(this.backlog){if(this.backlog.push($),this.backlog.length>jZ)this.backlog.shift()}for(let J of this.subscribers){if(J.done)continue;J.queue.push($),J.wake?.()}for(let J of this.listeners)try{J($)}catch{}}}var qJ=30000,_9=10,M9=7200,xZ=600,A9="gpt-live-transcribe";function qZ($){return $.type==="transcription"}function IZ($){if($.language!==void 0&&$.languages!==void 0)throw TypeError("A transcription session takes `languages` or `language`, not both (gpt-live-transcribe reads `languages`).");for(let W of $.keywords??[])if(/[<>\r\n]/.test(W))throw TypeError(`Transcription keywords must be one line without "<" or ">", got ${JSON.stringify(W)}.`);let J={model:$.model??A9};if($.prompt!==void 0)J.prompt=$.prompt;if($.keywords?.length)J.keywords=$.keywords;if($.languages?.length)J.languages=$.languages;if($.language!==void 0)J.language=$.language;if($.delay!==void 0)J.delay=$.delay;let Q={transcription:J,turn_detection:$.turnDetection?R9($.turnDetection):null};if($.noiseReduction!==void 0)Q.noise_reduction=$.noiseReduction&&{type:$.noiseReduction};let Z={type:"transcription",audio:{input:Q}};if($.logprobs)Z.include=["item.input_audio_transcription.logprobs"];return{...Z,...$.vendor}}function wZ($){if(!$)return{type:"object",properties:{}};return S9($)?$.toJSONSchema():$}function f$($,J){if(qZ($))return IZ($);let Q={type:"realtime"},Z=$.model??J;if(Z)Q.model=Z;if($.instructions!==void 0)Q.instructions=$.instructions;if($.outputModalities)Q.output_modalities=$.outputModalities;if($.maxOutputTokens!==void 0)Q.max_output_tokens=$.maxOutputTokens;if($.truncation!==void 0)Q.truncation=$.truncation;if($.tools)Q.tools=$.tools.map((X)=>({type:"function",name:X.name,...X.description?{description:X.description}:{},parameters:wZ(X.parameters)}));if($.toolChoice!==void 0)Q.tool_choice=typeof $.toolChoice==="string"?$.toolChoice:{type:"function",name:$.toolChoice.name};let W={};if($.turnDetection!==void 0)W.turn_detection=$.turnDetection&&R9($.turnDetection);if($.transcription!==void 0)W.transcription=$.transcription;if($.noiseReduction!==void 0)W.noise_reduction=$.noiseReduction&&{type:$.noiseReduction};let K={};if($.voice!==void 0)K.voice=$.voice;if($.speed!==void 0)K.speed=$.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,...$.vendor}}function R9($){let J={type:$.type};if($.createResponse!==void 0)J.create_response=$.createResponse;if($.interruptResponse!==void 0)J.interrupt_response=$.interruptResponse;if($.type==="semantic_vad"){if($.eagerness!==void 0)J.eagerness=$.eagerness}else{if($.threshold!==void 0)J.threshold=$.threshold;if($.prefixPaddingMs!==void 0)J.prefix_padding_ms=$.prefixPaddingMs;if($.silenceDurationMs!==void 0)J.silence_duration_ms=$.silenceDurationMs;if($.idleTimeoutMs!==void 0)J.idle_timeout_ms=$.idleTimeoutMs}return J}function w$($){let J=Number($?.input_tokens??0),Q=Number($?.output_tokens??0),Z={inputTokens:J,outputTokens:Q,totalTokens:Number($?.total_tokens??J+Q)},W=$?.input_token_details??$?.input_tokens_details,K=$?.output_token_details??$?.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 b extends Error{code;retryable;status;constructor($,J={}){super($.message,{cause:J.cause});if(this.name="RealtimeRequestError",this.code=$.code,this.retryable=$.retryable,J.status!==void 0)this.status=J.status}}var bZ=60;class V${model;target;options;constructor($,J){this.target=$,this.options=J,this.model=J.model}url($){return`${this.target.base}/realtime${$}${this.target.query}`}sidebandUrl($){let J=this.target.base.replace(/^http(s?):/i,(Z,W)=>`ws${W}:`),Q=this.target.query?`${this.target.query}&`:"?";return`${J}/realtime${Q}call_id=${encodeURIComponent($)}`}async createCall($){let J=$.flow??this.options.callFlow??"unified",Q,Z;if(J==="ephemeral")Q={authorization:`Bearer ${(await this.clientSecret({session:$.session,ttlSeconds:bZ,signal:$.signal})).value}`,"content-type":"application/sdp"},Z=$.sdp;else{let V=new FormData;V.set("sdp",$.sdp),V.set("session",JSON.stringify(f$($.session??{},this.model))),Q=await this.target.headers(),Z=V}if($.safetyIdentifier)Q["OpenAI-Safety-Identifier"]=$.safetyIdentifier;let W=this.url("/calls"),K=await this.request($.webrtcFilter?`${W}${W.includes("?")?"&":"?"}webrtcfilter=on`:W,{method:"POST",headers:Q,body:Z},$.signal),X=await K.text(),G=fZ(K);if(!G)throw new b({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($={}){let J=$.ttlSeconds??xZ;if(!Number.isInteger(J)||J<_9||J>M9)throw RangeError(`ttlSeconds must be a whole number from ${_9} to ${M9}, got ${J}.`);let Q={...await this.target.headers(),"content-type":"application/json"};if($.safetyIdentifier)Q["OpenAI-Safety-Identifier"]=$.safetyIdentifier;let W=await(await this.request(this.url("/client_secrets"),{method:"POST",headers:Q,body:JSON.stringify({expires_after:{anchor:"created_at",seconds:J},session:f$($.session??{},this.model)})},$.signal)).json();if(typeof W?.value!=="string")throw new b({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($)}/hangup`),{method:"POST",headers:await this.target.headers()},J.signal)}catch(Q){if(E9(Q,$))return;throw Q}}sideband($,J={}){return new b$({...J,callId:$,url:this.sidebandUrl($),headers:this.target.headers,webSocket:J.webSocket??this.options.webSocket,hangup:()=>this.hangup($)})}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 b(T(Z),{cause:Z,...Z instanceof I?{status:Z.status}:{}})}}}function E9($,J){if(!($ instanceof b)||$.status!==404)return!1;let Q=$.cause instanceof I?$.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(J.toLowerCase()))return!0;return/\bcall\b/.test(K)&&/not (be )?found|does not exist|no longer|ended/.test(K)}function fZ($){let J=$.headers.get("location");if(!J)return;let Q=J.split("?")[0].replace(/\/+$/,""),Z=Q.slice(Q.lastIndexOf("/")+1);return Z?decodeURIComponent(Z):void 0}function wJ($,J){let{capabilities:Q}=J,Z={model:J.model,input:vZ($.messages,Q,$.tools),stream:!0};if($.systemPrompt)Z.instructions=$.systemPrompt;let W=iZ($.tools,Q);if(W.length>0){if(Z.tools=W,!Q.parallelToolCalls)Z.parallel_tool_calls=!1}if($.output)Z.text={format:{type:"json_schema",name:$.output.name,schema:$.output.schema,strict:$.output.strict}};if($.reasoning&&Q.reasoning)Z.reasoning=$.reasoning==="none"?{effort:"none"}:{effort:$.reasoning,summary:"auto"};if(typeof $.temperature==="number")Z.temperature=$.temperature;if(typeof $.maxOutputTokens==="number")Z.max_output_tokens=$.maxOutputTokens;return Z}function vZ($,J,Q){let Z=[],W=new Map;if(J.toolSearch){for(let K of Q??[])if(v$(K))W.set(K.name,K)}for(let K of $){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(t(X,Y.text));break}case"output":{if(Y.partial)break;G.push(t(X,JSON.stringify(Y.value)));break}case"file":{if(X==="assistant")break;let H=gZ(Y);if(!J.fileInput){if(H)G.push(t(X,IJ(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(t(X,IJ(Y,!1)));G.push(t(X,SJ(Y.name)));break}if(H)G.push(t(X,IJ(Y,!!Y.fileId)));if(Y.fileId)G.push(uZ(Y));break}case"reasoning":{V();let H=pZ(Y);if(H)Z.push(H);break}case"tool-call":{if(Y.partial)break;if(V(),J.toolSearch&&Array.isArray(Y.toolSearches))for(let D of Y.toolSearches)Z.push(...dZ(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:lZ(Y)});break}}V()}return hZ(Z)}var yZ="No result was recorded for this tool call. Assume it did not complete.";function hZ($){let J=new Set,Q=new Set,Z=[];for(let K of $){if(K.type==="function_call"){let X=String(K.call_id);if(J.has(X))continue;J.add(X)}else if(K.type==="function_call_output"){let X=String(K.call_id);if(!J.has(X)||Q.has(X))continue;Q.add(X)}Z.push(K)}if(Q.size===J.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:yZ})}return W}function t($,J){return{type:$==="assistant"?"output_text":"input_text",text:J}}function gZ($){let J=$.attachmentId;return typeof J==="string"&&J.startsWith(m)?J:void 0}function IJ($,J){let Q=[`id=${JSON.stringify($.attachmentId)}`];if($.name)Q.push(`name=${JSON.stringify($.name)}`);if($.mimeType)Q.push(`mimeType=${JSON.stringify($.mimeType)}`);let Z=`attachment ${Q.join(" ")}`;return J?`[${Z}]`:`[${Z} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function uZ($){let J=$.mimeType?.trim().toLowerCase()??"";return{type:(J?J.startsWith("image/")&&J!=="image/svg+xml":cZ($.name))?"input_image":"input_file",file_id:$.fileId}}function cZ($){let J=/\.([a-z0-9]+)$/.exec($?.trim().toLowerCase()??"");return J?.[1]!==void 0&&mZ.has(J[1])}var mZ=new Set(["jpeg","jpg","png","gif","webp"]);function pZ($){if(!$.id)return null;let J={type:"reasoning",id:$.id};return J.summary=$.text?[{type:"summary_text",text:$.text}]:[],J}function lZ($){if($.status==="ok"){let J=$.modelOutput!==void 0?$.modelOutput:$.output;return typeof J==="string"?J:JSON.stringify(J??null)}if($.status==="running"){let J=$.job?.summary===void 0?"":` Started with: ${JSON.stringify($.job.summary)}.`;return`Started background job ${$.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.${J}`}if($.status==="denied"){let J=$.reason?` Reason given: ${$.reason}`:"";if($.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${J}`;if($.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.${J}`;return`The user declined this tool call, so it did not run.${J}`}return`The tool call failed and produced no result. Error (${$.error?.code??"unknown"}): ${$.error?.message??"no message"}`}function dZ($,J){let Q=new Set(T9($?.loaded)),Z=T9($?.namespaces),W=new Set(Z),K=[];for(let G of J)if(v$(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)=>r(Y,!0))})}else if(G.deferred&&Q.has(G.name))K.push(r(G,!0));if(K.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:$.arguments&&typeof $.arguments==="object"?$.arguments:{paths:Z.length>0?Z:[...Q]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:K}]}function T9($){return Array.isArray($)?$.filter((J)=>typeof J==="string"):[]}function v$($){return Array.isArray($.tools)}function iZ($,J){if(!$||$.length===0)return[];if(!J.toolSearch){let W=[];for(let K of $)if(v$(K))for(let X of K.tools)W.push(r(X,!1));else W.push(r(K,!1));return W}let Q=[],Z=!1;for(let W of $)if(v$(W)){let K=W.tools.map((X)=>{if(X.deferred)Z=!0;return r(X,!0)});Q.push({type:"namespace",name:W.name,description:W.description,tools:K})}else{if(W.deferred)Z=!0;Q.push(r(W,!0))}if(Z)Q.push({type:"tool_search"});return Q}function r($,J){let Q={type:"function",name:$.name,description:$.description,parameters:$.parameters,strict:$.strict};if(J&&$.deferred)Q.defer_loading=!0;return Q}class e{static models(){return[]}normalizeError($){return T($)}}var j9=["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 bJ extends e{model;capabilities;config;constructor($,J={}){super();this.model=$,this.capabilities=xJ($),this.config=J}static model($,J){return new bJ($,J)}static models(){return j9}stream($){let J=wJ($,{model:this.model,capabilities:this.capabilities});return jJ(this.endpoint(),J,{signal:$.signal,structuredOutput:Boolean($.output),files:MJ($.messages)})}upload($){return kJ(this.endpoint(),$)}endpoint(){return TJ(Y$(this.config))}get realtime(){return new V$(Y$(this.config,{timeoutMs:qJ}),{model:this.model})}}class fJ extends e{model;capabilities;config;constructor($,J={}){super();this.model=$,this.capabilities=xJ($),this.config=J}static model($,J){return new fJ($,J)}static models(){return j9}stream($){let J=wJ($,{model:this.deployment(),capabilities:this.capabilities});return jJ(this.endpoint(),J,{signal:$.signal,structuredOutput:Boolean($.output),files:MJ($.messages)})}upload($){return kJ(this.endpoint(),$,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return TJ(G$(this.config))}get realtime(){return new V$(Q9(this.config,{timeoutMs:qJ}),{model:this.deployment(),callFlow:"ephemeral"})}}class y${now;entries=new Map;constructor($=Date.now){this.now=$}allow($,J){let Q=this.entries.get($);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+J.cooldownMs,!0}record($,J,Q){let Z=this.entries.get($)??{failures:0},W=Z.openUntil!==void 0;if(J==="success")return this.entries.delete($),W?"closed":void 0;if(J==="none"){delete Z.probeUntil;return}if(Z.failures+=1,this.entries.set($,Z),W||Z.failures>=Q.failures)return Z.openUntil=this.now()+Q.cooldownMs,delete Z.probeUntil,W?void 0:"open";return}state($){let J=this.entries.get($);if(J?.openUntil===void 0)return"closed";return this.now()<J.openUntil?"open":"half-open"}}var k9=Symbol("timed-out");class H$ extends e{model;capabilities;entries;options;circuit;constructor($,J={}){super();if($.length===0)throw Error("FallbackProvider needs at least one provider.");for(let Z of $)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=[...$];let Q=J.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 $){let V=vJ(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 y$;this.options={...J,circuit:{...Q,store:X}},this.circuit={policy:{failures:Z,cooldownMs:W},store:X,...Q.onStateChange?{onStateChange:Q.onStateChange}:{}}}else this.options=J,this.circuit=void 0;this.model=$[0].provider.model,this.capabilities=nZ($.map((Z)=>Z.provider.capabilities))}static chain($,J){return new H$($,J)}from($){if(!Number.isInteger($)||$<0||$>=this.entries.length)throw RangeError(`FallbackProvider.from(${$}): the chain has ${this.entries.length} entries.`);return new H$(this.entries.slice($),this.options)}leg($){let J=this.from($).entries[0];return new H$([J],this.options)}upload($){return this.entries[0].provider.upload($)}normalizeError($){return this.entries[0].provider.normalizeError($)}stream($){return this.run($)}async*run($){let J,Q=$.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(C)=>{if(V)return;V=!0,await this.record(W,K,C)},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,R=(C)=>{let k=J?A(A(S(),J),C.usage):C.usage;return J=void 0,{...C,usage:k}};try{O=K.provider.stream({...$,...K.reasoning!==void 0?{reasoning:K.reasoning}:{},signal:H.signal})[Symbol.asyncIterator]();let C=!0;for(;;){let k=C&&K.timeoutMs!==void 0?await oZ(O.next(),K.timeoutMs):await O.next();if(k===k9){L=!0,P={error:{code:"provider_error",message:`${G} sent nothing within ${K.timeoutMs}ms.`,retryable:!0}};break}if(C=!1,k.done){j=!0;break}let _=k.value;if(_.type==="finish"&&_.model)B=_.model;if(F){if(_.type==="finish")N=A(N??S(),_.usage),U=!0,yield R(_);else{if(_.type==="error")P={error:_.error};yield _}continue}if(I$(_)){F=!0,await Y("success"),yield*z.splice(0),yield _;continue}if(_.type==="error")P={error:_.error,..._.status!==void 0?{status:_.status}:{},..._.requestId!==void 0?{requestId:_.requestId}:{}};else if(_.type==="finish"){if(N=A(N??S(),_.usage),_.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(_)}}catch(C){let k=K.provider.normalizeError(C);if(F){if(k.code!=="aborted")yield{type:"error",error:k,...a(C)};this.report({index:W,model:G,responseModel:B,attempt:Z,usage:N,outcome:yJ(k),error:k}),yield R({type:"finish",reason:k.code==="aborted"?"aborted":"error",usage:S(),...B?{model:B}:{}});return}P={error:k,...a(C)}}finally{if(Q?.removeEventListener("abort",D),!j)H.abort(),O?.return?.()?.catch(()=>{})}if(F){if(!U&&J)yield{type:"finish",reason:P?"error":"stop",usage:J},J=void 0;this.report({index:W,model:G,responseModel:B,attempt:Z,usage:N,outcome:P?yJ(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 R({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 C of z)yield C.type==="finish"?R(C):C;return}let q=!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(q?"failure":"none"),this.report({index:W,model:G,responseModel:B,attempt:Z,usage:N,outcome:q?"fallback":yJ(P.error),error:P.error}),q){if(N)J=A(J??S(),N);continue}let d=!1,i;for(let C of z){if(C.type==="finish"){i=C;continue}if(C.type==="error")d=!0;yield C}if(!d&&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 R({type:"finish",reason:P.error.code==="aborted"?"aborted":i?.reason??"error",usage:N??S(),...B?{model:B}:{}});return}}async allow($){if(!this.circuit)return!0;try{return await this.circuit.store.allow(vJ($),this.circuit.policy)}catch{return!0}}async record($,J,Q){if(!this.circuit)return;let Z=vJ(J),W;try{W=await this.circuit.store.record(Z,Q,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:$,model:J.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($){if($.usage===void 0)delete $.usage;if($.responseModel===void 0)delete $.responseModel;try{this.options.onUsage?.($)}catch{}}}function vJ($){return $.circuitKey??$.provider.model}function yJ($){return $.code==="aborted"?"aborted":"failed"}function nZ($){return{reasoning:$.every((J)=>J.reasoning),structuredOutput:$.every((J)=>J.structuredOutput),fileInput:$.every((J)=>J.fileInput),parallelToolCalls:$.every((J)=>J.parallelToolCalls),toolSearch:$.every((J)=>J.toolSearch)}}function oZ($,J){let Q,Z=new Promise((W)=>{Q=setTimeout(()=>W(k9),J)});return Promise.race([$,Z]).finally(()=>clearTimeout(Q))}async function sZ($,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<$.entries.length;K++){let X=$.leg(K),G={index:K,model:X.model,results:[],errors:[]};for(let V=0;V<Z;V++)try{G.results.push(await J(X,{index:K,sample:V}))}catch(Y){G.errors.push({sample:V,error:Y})}W.push(G)}return W}class g$ extends Error{line;constructor($){super($??"Voice session ended by the app.");this.name="VoiceHangup",this.line=$}}var D$="ask_agent",aZ={maxDurationMs:900000,idleTimeoutMs:120000,maxQueued:3,progressIntervalMs:4000,closingLineMs:1e4,tickMs:60000,hangupGraceMs:30000,toolTimeoutMs:60000,maxToolCallsPerMinute:20,toolOutputChars:8000},tZ={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 z$($={}){return[{name:$.name??D$,description:$.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 h$=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($){return new p($)}static get($){return h$.get($)}static async endAll($){await Promise.all([...h$.values()].map((J)=>J.end("hangup",$)))}constructor($){this.params=$,this.sessionId=$.sessionId??crypto.randomUUID(),this.threadId=$.threadId,this.body=$.body??{},this.limits={...aZ,...x9($.limits)},this.lines={...tZ,...x9($.lines)},this.delegateName=$.delegate?.name??D$;let J=new Set(z$($.delegate).map((Q)=>Q.name));for(let Q of $.tools??[]){if(J.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 $.call){let{realtime:Q,callId:Z}=$.call;this.callId=Z,this.sideband=Q.sideband(Z),this.hangupCall=()=>this.sideband.hangup()}else this.callId=$.call.callId??$.call.sideband.callId,this.sideband=$.call.sideband,this.hangupCall=()=>this.sideband.hangup();this.ended=new Promise((Q)=>this.resolveEnded=Q),h$.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($){this.body=$;let J=this.params.contextNote?.($);if(J)this.sideband.addNote(J)}end($="hangup",J){return this.ending??=this.finish($,J??null)}async listen(){for await(let $ of this.sideband){try{this.params.onEvent?.($)}catch{}this.closingWaiter?.($),await this.handle($)}}async handle($){switch($.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(J){this.usage=A(this.usage,J);let Q=this.info();this.hook(()=>this.params.onUsage?.(J,Q))}return}case"conversation.item.input_audio_transcription.completed":{let J=$;if(this.say("user",String(J.transcript??"")),J.transcriptionUsage||J.transcriptionSeconds!==void 0){this.transcription={usage:J.transcriptionUsage?A(this.transcription.usage,J.transcriptionUsage):this.transcription.usage,seconds:this.transcription.seconds+(J.transcriptionSeconds??0)};let Q=this.info(),Z={...J.transcriptionUsage?{usage:J.transcriptionUsage}:{},...J.transcriptionSeconds!==void 0?{seconds:J.transcriptionSeconds}:{}};this.hook(()=>this.params.onTranscriptionUsage?.(Z,Q))}return}case"response.output_audio_transcript.done":this.say("assistant",String($.transcript??""));return;case"response.output_text.done":this.say("assistant",String($.text??""));return;case"response.function_call_arguments.done":{let J=$;if(this.touch(),!this.ending)this.call(J.call_id,J.name,J.arguments);return}case"session.updated":if(this.tampered($.session))this.end("session_tampered",null);return;case"error":{let J=$.error;if(this.errors.push({code:J?.code,message:String(J?.message??"")}),this.pendingCreate&&J?.event_id===this.pendingCreate)if(this.pendingCreate=void 0,J.code==="conversation_already_has_active_response")this.responseActive=!0,this.responseWanted=!0;else this.responseActive=!1;return}case"sideband.closed":{let J=$;if(!this.ending&&!J.byClient)this.end(J.code===1000?"call_ended":"sideband_lost",null);return}}}say($,J){if(J.trim())this.transcript.push({role:$,text:J,at:Date.now()})}call($,J,Q){let Z=rZ(Q);if(J===this.delegateName){let K=typeof Z.request==="string"?Z.request.trim():"";if(!K)return this.answer($,{status:"error",message:"The request was empty."});return this.enqueue({record:{request:K,status:"queued"},turn:{text:K},callId:$})}let W=this.toolHandlers.get(J);if(W)return void this.runTool($,W,Z);switch(J){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($,{stopped:Boolean(K),dropped:X})}case"work_status":return this.answer($,{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($,{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)=>eZ(V,K,X));return this.pending=[],this.enqueue({record:{request:`(answer) ${K}`,status:"queued"},turn:{toolResults:G},callId:$})}default:return this.answer($,{status:"error",message:`There is no tool called ${J}.`})}}enqueue($){if(!this.running){this.requests.push($.record),this.run($);return}if(this.queue.length>=this.limits.maxQueued)return this.answer($.callId,{status:"busy",message:"Too many requests are waiting. Ask the user to wait for the current one."});this.requests.push($.record),this.queue.push($),this.answer($.callId,{status:"queued",position:this.queue.length,message:"It will start when the current request is done."}),$.callId=void 0}async run($){this.running=$,$.record.status="running",this.lastProgress=void 0,this.pauseIdle();try{let J=new Set;await this.waitForThread(J);let Q=await this.latestBody();while(!$.stopRequested&&await this.waitForThread(J));if($.stopRequested||this.ending){$.record.status="dropped",this.complete($,{status:"stopped"});return}let Z;try{Z=await this.params.controller.startTurn({threadId:this.threadId,user:this.params.user,body:Q,turn:$.turn})}catch(K){$.record.status="refused",this.complete($,{status:"refused",message:K instanceof Error?K.message:"The request could not be started."});return}$.handle=Z,$.record.runId=Z.runId,this.follow(Z);let W=await Z.result();if($.record.status="done",$.record.finishReason=W.finishReason,W.finishReason==="awaiting-input"&&W.pending.length)this.pending=W.pending,this.complete($,{status:"needs_input",text:W.text,questions:this.questions()});else if(W.finishReason==="error")this.complete($,{status:"failed",message:W.error?.message??"The work failed."});else if(W.finishReason==="aborted")this.complete($,{status:"stopped",text:W.text});else this.complete($,{status:"done",text:W.text})}catch(J){$.record.status="done",this.complete($,{status:"failed",message:J instanceof Error?J.message:"The work failed."})}finally{this.running=void 0,this.flushNote();let J=this.queue.shift();if(J&&!this.ending)this.run(J);else this.touch()}}async runTool($,J,Q){let Z=J.tool.name,W=Date.now();if(this.toolCallTimes=this.toolCallTimes.filter((D)=>W-D<60000),this.toolCallTimes.length>=this.limits.maxToolCallsPerMinute){let D={name:Z,status:"busy"};this.toolCalls.push(D),this.answer($,{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=J.timeoutMs??this.limits.toolTimeoutMs,V,Y;try{let D=await Promise.race([J.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 g$){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($,Y)}clip($){let J;try{J=JSON.stringify($)}catch{return String($)}if(J===void 0||J.length<=this.limits.toolOutputChars)return $;return`${J.slice(0,this.limits.toolOutputChars)}\u2026 (cut: ${J.length} characters in all)`}async waitForThread($=new Set){let J=this.params.liveRuns;if(!J)return!1;let Q=await J.find({threadId:this.threadId}),Z=Q&&!$.has(Q.runId)?J.get(Q.runId):null;if(!Q||!Z)return!1;return $.add(Q.runId),await Z.result().catch(()=>{return}),!0}async latestBody(){let $=this.params.store;if(!$)return this.body;let J=await $.get(this.sessionId).catch(()=>null);if(J)this.body=J.body;return this.body}async follow($){let J=this.params.progress??$0();try{for await(let Q of $.run){let Z=J(Q);if(Z)this.note(Z)}}catch{}}complete($,J){if(this.ending)return;if($.callId)this.sideband.functionOutput($.callId,J),$.callId=void 0;else this.sideband.addNote(`Update on the earlier request "${$.record.request}": ${JSON.stringify(J)}`);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 $=`gemi_voice_${crypto.randomUUID()}`;this.pendingCreate=$,this.sideband.send({type:"response.create",event_id:$})}questions(){return this.pending.map(($)=>({kind:$.kind,tool:String($.name),input:$.input}))}dropQueue(){let $=this.queue.splice(0);for(let J of $)J.record.status="dropped";return $.length}note($){if($===this.lastProgress)return;this.lastProgress=$;let J=this.lastNoteAt+this.limits.progressIntervalMs-Date.now();if(J<=0)return this.flushNote();this.noteTimer??=setTimeout(()=>this.flushNote(),J)}flushNote(){if(this.noteTimer)clearTimeout(this.noteTimer);if(this.noteTimer=void 0,!this.lastProgress||this.ending||!this.running)return;this.lastNoteAt=Date.now(),this.sideband.addNote(`Progress on "${this.running.record.request}": ${this.lastProgress}`)}touch(){if(this.idleTimer)clearTimeout(this.idleTimer);if(this.idleTimer=void 0,this.running||this.toolsRunning>0||this.ending)return;this.idleTimer=setTimeout(()=>void this.end("idle",this.lines.idle),this.limits.idleTimeoutMs)}pauseIdle(){if(this.idleTimer)clearTimeout(this.idleTimer);this.idleTimer=void 0}info(){return{sessionId:this.sessionId,total:this.usage,elapsedMs:Date.now()-this.startedAt,transcription:this.transcription}}tick(){if(this.ending)return;let $=this.info();this.hook(()=>this.params.onTick?.($))}hook($){this.hooks=this.hooks.then(async()=>{try{await $()}catch(J){if(J instanceof g$)this.end("usage",J.line??null);else console.error("[gemi/ai] a voice hook threw; ending the call.",J),this.end("error",this.lines.error)}})}tampered($){let J=this.params.session;if(!J||!$)return!1;if(J.instructions!==void 0&&$.instructions!==void 0&&$.instructions!==J.instructions)return!0;if(Array.isArray($.tools)){let Q=new Set([...z$(this.params.delegate),...J.tools??[]].map((W)=>W.name)),Z=new Set($.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"&&$!=="sideband_lost"))await this.closingLine(J);if($!=="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:$,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};h$.delete(this.sessionId),await this.params.store?.update(this.sessionId,{endedAt:Z,endReason:$}).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($){console.error("[gemi/ai] a voice call could not be hung up; waiting for the vendor.",$),this.errors.push({code:"hangup_failed",message:$ instanceof Error?$.message:String($)});let J;await Promise.race([this.sideband.closed,new Promise((Q)=>J=setTimeout(Q,this.limits.hangupGraceMs))]),clearTimeout(J),this.sideband.close()}}async closingLine($){await new Promise((J)=>{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),J()}let V=()=>{W="asked",this.sideband.send({type:"response.create",event_id:Q,response:{instructions:`Say exactly this to the user, and nothing else: "${$}"`,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 x9($){if(!$)return{};return Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))}function rZ($){try{let J=JSON.parse($);return J&&typeof J==="object"&&!Array.isArray(J)?J:{}}catch{return{}}}function eZ($,J,Q){let Z={toolCallId:$.toolCallId,signature:$.signature,...$.path?{path:$.path}:{}};if($.kind==="question")return{...Z,output:J};if($.kind==="approval")return{...Z,approve:Q===!0,...J?{reason:J}:{}};return{...Z,approve:!1,reason:"Not available in a voice call."}}function $0(){let $=new Set;return(J)=>{if(J.type==="tool-call"){if(J.part.partial||J.resent||$.has(J.part.toolCallId))return;return $.add(J.part.toolCallId),`running ${String(J.part.name)}`}if(J.type==="tool-progress"){let Q=J.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 q9="http://gemi.internal/__gemi__/voice/mcp";async function hJ($,J){if(!J.user)throw Error("Voice MCP tools run as the signed-in user, and this voice session has none. Give `mcp` only to a signed-in user's session.");let{registry:Q}=$,Z=$.scopes??Q.scopes().map((X)=>X.name),W=(X)=>({kind:"remote",req:X,principal:{user:J.user,via:"voice",id:`voice:${J.sessionId}`,scopes:Z}});return(await Q.available(W(I9()),$.filter)).filter((X)=>!X.requiresApproval).map((X)=>({tool:{name:X.name,description:X.description,parameters:X.inputSchema},...$.timeoutMs!==void 0?{timeoutMs:$.timeoutMs}:{},run:(G,V)=>{let Y=I9();return h.run(Y,async()=>{return await $.authorize?.({name:X.name,input:G,sessionId:V.sessionId}),Q.execute(W(Y),X.name,G,void 0,{signal:V.signal})},{user:J.user})}}))}function I9(){return new x(new Request(q9,{method:"POST"}),{},"api",new URL(q9).pathname)}class gJ{records=new Map;retainEndedMs;constructor($={}){this.retainEndedMs=$.retainEndedMs??600000}async create($){this.sweep(),this.records.set($.id,structuredClone($))}async get($){let J=this.records.get($);return J?structuredClone(J):null}async update($,J){let Q=this.records.get($);if(!Q)return;this.records.set($,{...Q,...structuredClone(J),id:$})}sweep(){let $=Date.now()-this.retainEndedMs;for(let[J,Q]of this.records)if(Q.endedAt!==void 0&&Q.endedAt<$)this.records.delete(J)}}var uJ=new gJ;var w9=new WeakMap,b9=100;class u9{threadsTable;messagesTable;sql;dialect;connection;constructor($,J={}){this.threadsTable=f9(J.threadsTable??"gemi_agent_threads","threads"),this.messagesTable=f9(J.messagesTable??"gemi_agent_messages","messages"),this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name}async createTable(){let $=Z0(this.dialect,this.threadsTable,this.messagesTable);for(let J of $)await this.sql.unsafe(J)}async createThread($){let J=this.q(),Q=crypto.randomUUID(),Z=$.userId===void 0||$.userId===null?null:String($.userId),W=this.clock(J);return await J`
|
|
146
|
+
`)}}if(J.length>0){let V=X(J);if(V)yield V}let G=K();if(G)yield G}async function*U9($,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 MZ($)){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 J.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??""),C=Q.get(F);if(C?.done)break;let N=(typeof z.namespace==="string"?z.namespace:"")||C?.namespace;if(yield{type:"tool-call",toolCallId:String(z.call_id??F),name:String(z.name??C?.name??""),args:String(z.arguments??""),...N?{namespace:N}:{}},C)C.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=SZ(z);if(F.loaded.length===0&&F.namespaces.length===0)break;let C=String(z.tool_search_call_id??z.id??"");if(Z.has(C))break;Z.add(C);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",RJ(Y.response?.usage));break}case"response.incomplete":{K=!0;let z=RJ(Y.response?.usage),F=Y.response?.incomplete_details?.reason;if(F==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:AZ(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:RZ(z)},yield G("error",RJ(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 SZ($){let J=[],Q=[];return L9($.results??$.tools??$.loaded??$.output,J,Q,0),{loaded:EJ(J),namespaces:EJ(Q)}}function L9($,J,Q,Z){if(!Array.isArray($)||Z>4)return;for(let W of $){if(typeof W==="string"){J.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);L9(G,J,Q,Z+1);continue}if(X)J.push(X)}}function EJ($){return $.filter((J,Q)=>$.indexOf(J)===Q)}function AZ($){if(!Array.isArray($))return"The provider's content filter blocked this request.";let Q=[];for(let Z of $){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: ${EJ(Q).join(", ")}.`}function RZ($){let J=typeof $?.message==="string"?$.message:"The provider stream failed.",Q=String($?.code??"").toLowerCase();if(Q==="rate_limit_exceeded")return{code:"rate_limited",message:J,retryable:!0};if(Q==="context_length_exceeded")return{code:"context_length_exceeded",message:J,retryable:!1};if(Q.includes("content_filter"))return{code:"content_filtered",message:J,retryable:!1};return{code:"provider_error",message:J,retryable:!0}}function b(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function RJ($){if(!$)return b();let J=Number($.input_tokens??0),Q=Number($.output_tokens??0),Z={inputTokens:J,outputTokens:Q,totalTokens:Number($.total_tokens??J+Q)},W=$.output_tokens_details?.reasoning_tokens;if(typeof W==="number")Z.reasoningTokens=W;let K=$.input_tokens_details?.cached_tokens;if(typeof K==="number")Z.cachedInputTokens=K;return Z}async function*C9($){if(!$)return;let J=$.getReader(),Q=new TextDecoder;try{while(!0){let{done:W,value:K}=await J.read();if(W)break;if(K)yield Q.decode(K,{stream:!0})}let Z=Q.decode();if(Z)yield Z}finally{J.releaseLock()}}function TJ($){return{responsesUrl:`${$.base}/responses${$.query}`,filesUrl:`${$.base}/files${$.query}`,headers:$.headers,timeoutMs:$.timeoutMs,streamIdleTimeoutMs:$.streamIdleTimeoutMs,maxRetries:$.maxRetries}}async function*jJ($,J,Q){let Z=J,W=new Set,K=0,X=Math.max(0,$.maxRetries),G=$.random??Math.random,V,Y=(z)=>{if(!V)return z;let F=E(E(b(),V),z.usage);return V=void 0,{...z,usage:F}},H=()=>Y({type:"finish",reason:"aborted",usage:b()}),D=$.streamIdleTimeoutMs??0;for(let z=0;;z++){let F=new AbortController,C=Q.signal?AbortSignal.any([Q.signal,F.signal]):F.signal,N;while(N===void 0)try{N=await m($.responsesUrl,{method:"POST",headers:{...await $.headers(),"content-type":"application/json"},body:JSON.stringify(Z)},{maxRetries:$.maxRetries,timeoutMs:$.timeoutMs,signal:C,fetchImpl:$.fetchImpl,sleep:$.sleep,random:$.random})}catch(L){let O=K<B9?P9(Z,L,Q.files).filter((x)=>!W.has(x)):[];if(O.length>0){K++;let x=j(L).message;for(let I of O)W.add(I),yield{type:"file-rejected",fileId:I,message:x,...a(L)};Z=N9(Z,new Set(O),Q.files);continue}let A=j(L);if(A.code==="aborted"){yield H();return}yield{type:"error",error:A,...a(L)},yield Y({type:"finish",reason:"error",usage:b()});return}let P=[],B=!1,U;try{let L=Y9(N.body,D,()=>{let O=new O9(D);return F.abort(O),O});for await(let O of U9(C9(L),{structuredOutput:Q.structuredOutput})){if(B){yield O.type==="finish"?Y(O):O;continue}if(I$(O)){B=!0,yield*P.splice(0),yield O;continue}if(O.type==="error")U=O.error;P.push(O)}}catch(L){let O=j(L);if(O.code==="aborted"||Q.signal?.aborted){yield H();return}if(B){yield{type:"error",error:O},yield Y({type:"finish",reason:"error",usage:b()});return}U=O,P.push({type:"error",error:O},{type:"finish",reason:"error",usage:b()})}if(B)return;if(U?.retryable&&z<X&&!Q.signal?.aborted){for(let L of P)if(L.type==="finish")V=E(V??b(),L.usage);try{await UJ(k$(z,G),Q.signal,$.sleep)}catch{yield H();return}continue}for(let L of P)yield L.type==="finish"?Y(L):L;return}}async function kJ($,J,Q="user_data"){let Z=new FormData;Z.set("purpose",Q),Z.set("file",J);let K=await(await m($.filesUrl,{method:"POST",headers:await $.headers(),body:Z},{maxRetries:$.maxRetries,timeoutMs:$.timeoutMs,fetchImpl:$.fetchImpl})).json();if(!K?.id)throw Error("The provider accepted the upload but returned no file id.");return K.id}function xJ($){let J=EZ($);if(J.startsWith("gpt-3.5")||J.startsWith("text-")||J.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Q=TZ(J);if(Q?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Q.major>1,toolSearch:_9(Q)};if(Q?.kind==="gpt")return{reasoning:Q.major>=5,structuredOutput:Q.major>4||J.startsWith("gpt-4o")||J.startsWith("gpt-4.1"),fileInput:Q.major>4||J.startsWith("gpt-4o")||J.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:_9(Q)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function _9($){if($.kind==="o")return $.major>=5;return $.major>5||$.major===5&&$.minor>=2}function EZ($){return $.trim().toLowerCase()}function TZ($){let J=/^gpt-(\d+)(?:\.(\d+))?/.exec($);if(J?.[1])return{kind:"gpt",major:Number(J[1]),minor:Number(J[2]??0)};let Q=/^o(\d+)(?:[-.]|$)/.exec($);if(Q?.[1])return{kind:"o",major:Number(Q[1]),minor:0};return null}var jZ={"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 kZ($){if(typeof $!=="string")return;let J;try{J=JSON.parse($)}catch{return}if(!J||typeof J!=="object"||typeof J.type!=="string")return;let Q=jZ[J.type];if(Q)J.type=Q;if(J.type==="response.done"&&J.response?.usage)J.usage=w$(J.response.usage);if(J.type==="conversation.item.input_audio_transcription.completed"&&J.usage)if(J.usage.type==="duration"){let Z=Number(J.usage.seconds);if(Number.isFinite(Z))J.transcriptionSeconds=Z}else J.transcriptionUsage=w$(J.usage);return J}var M9=1,xZ=500;function qZ($,J){let Q=globalThis.WebSocket;if(!Q)throw Error("No global WebSocket: the realtime sideband needs Bun or Node 22+.");return new Q($,{headers:J.headers})}class b${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($){this.init=$,this.callId=$.callId,this.ready=new Promise((J,Q)=>{this.resolveReady=J,this.rejectReady=Q}),this.ready.catch(()=>{}),this.closed=new Promise((J)=>this.resolveClosed=J),this.open()}send($){if(this.finished||this.closing)return;let J=JSON.stringify($);if(this.socket?.readyState===M9)this.socket.send(J);else this.outbox.push(J)}updateSession($){this.send({type:"session.update",session:f$($)})}addItem($){this.send({type:"conversation.item.create",item:$})}addNote($){this.addItem({type:"message",role:"system",content:[{type:"input_text",text:$}]})}functionOutput($,J){this.addItem({type:"function_call_output",call_id:$,output:typeof J==="string"?J:JSON.stringify(J)})}createResponse($={}){let J={};if($.instructions!==void 0)J.instructions=$.instructions;if($.toolChoice!==void 0)J.tool_choice=typeof $.toolChoice==="string"?$.toolChoice:{type:"function",name:$.toolChoice.name};if($.outputModalities)J.output_modalities=$.outputModalities;if($.conversation)J.conversation=$.conversation;if($.metadata)J.metadata=$.metadata;Object.assign(J,$.vendor),this.send(Object.keys(J).length?{type:"response.create",response:J}:{type:"response.create"})}cancelResponse($){this.send($?{type:"response.cancel",response_id:$}:{type:"response.cancel"})}on($){return this.listeners.add($),()=>this.listeners.delete($)}[Symbol.asyncIterator](){let $={queue:this.backlog??[],done:this.finished};return this.backlog=void 0,this.subscribers.add($),{next:async()=>{for(;;){let Q=$.queue.shift();if(Q)return{value:Q,done:!1};if($.done)return this.subscribers.delete($),{value:void 0,done:!0};await new Promise((Z)=>$.wake=Z),$.wake=void 0}},return:async()=>{return $.done=!0,$.queue.length=0,this.subscribers.delete($),{value:void 0,done:!0}}}}close($=1000,J="closed"){if(this.finished||this.closing)return;if(this.closing=!0,this.socket&&this.socket.readyState<=M9)this.socket.close($,J);else this.finish($,J,!0)}async hangup(){try{await this.init.hangup()}catch($){if(this.finalEvent&&!this.finalEvent.byClient&&this.finalEvent.code===1000)return;throw $}this.close(1000,"hangup")}async open(){let $;try{let Q=await this.init.headers();if(this.closing)return this.finish(1000,"closed",!0);$=(this.init.webSocket??qZ)(this.init.url,{headers:Q})}catch(Q){return this.dropped(1006,Q instanceof Error?Q.message:String(Q),!1)}this.socket=$;let J=!1;$.addEventListener("open",()=>{J=!0;let Q=this.everOpened;this.everOpened=!0;let Z=this.failures;this.failures=0;for(let W of this.outbox.splice(0))$.send(W);if(this.resolveReady(),Q)this.emit({type:"sideband.reconnected",attempt:Z})}),$.addEventListener("message",(Q)=>{let Z=kZ(Q.data);if(Z)this.emit(Z)}),$.addEventListener("close",(Q)=>{if(this.socket!==$)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(!(($!==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:$,reason:J,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($){if(this.backlog){if(this.backlog.push($),this.backlog.length>xZ)this.backlog.shift()}for(let J of this.subscribers){if(J.done)continue;J.queue.push($),J.wake?.()}for(let J of this.listeners)try{J($)}catch{}}}var qJ=30000,S9=10,A9=7200,IZ=600,E9="gpt-live-transcribe";function wZ($){return $.type==="transcription"}function bZ($){if($.language!==void 0&&$.languages!==void 0)throw TypeError("A transcription session takes `languages` or `language`, not both (gpt-live-transcribe reads `languages`).");for(let W of $.keywords??[])if(/[<>\r\n]/.test(W))throw TypeError(`Transcription keywords must be one line without "<" or ">", got ${JSON.stringify(W)}.`);let J={model:$.model??E9};if($.prompt!==void 0)J.prompt=$.prompt;if($.keywords?.length)J.keywords=$.keywords;if($.languages?.length)J.languages=$.languages;if($.language!==void 0)J.language=$.language;if($.delay!==void 0)J.delay=$.delay;let Q={transcription:J,turn_detection:$.turnDetection?T9($.turnDetection):null};if($.noiseReduction!==void 0)Q.noise_reduction=$.noiseReduction&&{type:$.noiseReduction};let Z={type:"transcription",audio:{input:Q}};if($.logprobs)Z.include=["item.input_audio_transcription.logprobs"];return{...Z,...$.vendor}}function fZ($){if(!$)return{type:"object",properties:{}};return R9($)?$.toJSONSchema():$}function f$($,J){if(wZ($))return bZ($);let Q={type:"realtime"},Z=$.model??J;if(Z)Q.model=Z;if($.instructions!==void 0)Q.instructions=$.instructions;if($.outputModalities)Q.output_modalities=$.outputModalities;if($.maxOutputTokens!==void 0)Q.max_output_tokens=$.maxOutputTokens;if($.truncation!==void 0)Q.truncation=$.truncation;if($.tools)Q.tools=$.tools.map((X)=>({type:"function",name:X.name,...X.description?{description:X.description}:{},parameters:fZ(X.parameters)}));if($.toolChoice!==void 0)Q.tool_choice=typeof $.toolChoice==="string"?$.toolChoice:{type:"function",name:$.toolChoice.name};let W={};if($.turnDetection!==void 0)W.turn_detection=$.turnDetection&&T9($.turnDetection);if($.transcription!==void 0)W.transcription=$.transcription;if($.noiseReduction!==void 0)W.noise_reduction=$.noiseReduction&&{type:$.noiseReduction};let K={};if($.voice!==void 0)K.voice=$.voice;if($.speed!==void 0)K.speed=$.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,...$.vendor}}function T9($){let J={type:$.type};if($.createResponse!==void 0)J.create_response=$.createResponse;if($.interruptResponse!==void 0)J.interrupt_response=$.interruptResponse;if($.type==="semantic_vad"){if($.eagerness!==void 0)J.eagerness=$.eagerness}else{if($.threshold!==void 0)J.threshold=$.threshold;if($.prefixPaddingMs!==void 0)J.prefix_padding_ms=$.prefixPaddingMs;if($.silenceDurationMs!==void 0)J.silence_duration_ms=$.silenceDurationMs;if($.idleTimeoutMs!==void 0)J.idle_timeout_ms=$.idleTimeoutMs}return J}function w$($){let J=Number($?.input_tokens??0),Q=Number($?.output_tokens??0),Z={inputTokens:J,outputTokens:Q,totalTokens:Number($?.total_tokens??J+Q)},W=$?.input_token_details??$?.input_tokens_details,K=$?.output_token_details??$?.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($.message,{cause:J.cause});if(this.name="RealtimeRequestError",this.code=$.code,this.retryable=$.retryable,J.status!==void 0)this.status=J.status}}var vZ=60;class V${model;target;options;constructor($,J){this.target=$,this.options=J,this.model=J.model}url($){return`${this.target.base}/realtime${$}${this.target.query}`}sidebandUrl($){let J=this.target.base.replace(/^http(s?):/i,(Z,W)=>`ws${W}:`),Q=this.target.query?`${this.target.query}&`:"?";return`${J}/realtime${Q}call_id=${encodeURIComponent($)}`}async createCall($){let J=$.flow??this.options.callFlow??"unified",Q,Z;if(J==="ephemeral")Q={authorization:`Bearer ${(await this.clientSecret({session:$.session,ttlSeconds:vZ,signal:$.signal})).value}`,"content-type":"application/sdp"},Z=$.sdp;else{let V=new FormData;V.set("sdp",$.sdp),V.set("session",JSON.stringify(f$($.session??{},this.model))),Q=await this.target.headers(),Z=V}if($.safetyIdentifier)Q["OpenAI-Safety-Identifier"]=$.safetyIdentifier;let W=this.url("/calls"),K=await this.request($.webrtcFilter?`${W}${W.includes("?")?"&":"?"}webrtcfilter=on`:W,{method:"POST",headers:Q,body:Z},$.signal),X=await K.text(),G=yZ(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($={}){let J=$.ttlSeconds??IZ;if(!Number.isInteger(J)||J<S9||J>A9)throw RangeError(`ttlSeconds must be a whole number from ${S9} to ${A9}, got ${J}.`);let Q={...await this.target.headers(),"content-type":"application/json"};if($.safetyIdentifier)Q["OpenAI-Safety-Identifier"]=$.safetyIdentifier;let W=await(await this.request(this.url("/client_secrets"),{method:"POST",headers:Q,body:JSON.stringify({expires_after:{anchor:"created_at",seconds:J},session:f$($.session??{},this.model)})},$.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($)}/hangup`),{method:"POST",headers:await this.target.headers()},J.signal)}catch(Q){if(j9(Q,$))return;throw Q}}sideband($,J={}){return new b$({...J,callId:$,url:this.sidebandUrl($),headers:this.target.headers,webSocket:J.webSocket??this.options.webSocket,hangup:()=>this.hangup($)})}async request($,J,Q){try{return await m($,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(j(Z),{cause:Z,...Z instanceof w?{status:Z.status}:{}})}}}function j9($,J){if(!($ instanceof f)||$.status!==404)return!1;let Q=$.cause instanceof w?$.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(J.toLowerCase()))return!0;return/\bcall\b/.test(K)&&/not (be )?found|does not exist|no longer|ended/.test(K)}function yZ($){let J=$.headers.get("location");if(!J)return;let Q=J.split("?")[0].replace(/\/+$/,""),Z=Q.slice(Q.lastIndexOf("/")+1);return Z?decodeURIComponent(Z):void 0}function wJ($,J){let{capabilities:Q}=J,Z={model:J.model,input:hZ($.messages,Q,$.tools),stream:!0};if($.systemPrompt)Z.instructions=$.systemPrompt;let W=oZ($.tools,Q);if(W.length>0){if(Z.tools=W,!Q.parallelToolCalls)Z.parallel_tool_calls=!1}if($.output)Z.text={format:{type:"json_schema",name:$.output.name,schema:$.output.schema,strict:$.output.strict}};if($.reasoning&&Q.reasoning)Z.reasoning=$.reasoning==="none"?{effort:"none"}:{effort:$.reasoning,summary:"auto"};if(typeof $.temperature==="number")Z.temperature=$.temperature;if(typeof $.maxOutputTokens==="number")Z.max_output_tokens=$.maxOutputTokens;return Z}function hZ($,J,Q){let Z=[],W=new Map;if(J.toolSearch){for(let K of Q??[])if(v$(K))W.set(K.name,K)}for(let K of $){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(t(X,Y.text));break}case"output":{if(Y.partial)break;G.push(t(X,JSON.stringify(Y.value)));break}case"file":{if(X==="assistant")break;let H=cZ(Y);if(!J.fileInput){if(H)G.push(t(X,IJ(Y,!1)));break}if(Y.fileId?.startsWith(p))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(t(X,IJ(Y,!1)));G.push(t(X,SJ(Y.name)));break}if(H)G.push(t(X,IJ(Y,!!Y.fileId)));if(Y.fileId)G.push(mZ(Y));break}case"reasoning":{V();let H=dZ(Y);if(H)Z.push(H);break}case"tool-call":{if(Y.partial)break;if(V(),J.toolSearch&&Array.isArray(Y.toolSearches))for(let D of Y.toolSearches)Z.push(...nZ(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:iZ(Y)});break}}V()}return uZ(Z)}var gZ="No result was recorded for this tool call. Assume it did not complete.";function uZ($){let J=new Set,Q=new Set,Z=[];for(let K of $){if(K.type==="function_call"){let X=String(K.call_id);if(J.has(X))continue;J.add(X)}else if(K.type==="function_call_output"){let X=String(K.call_id);if(!J.has(X)||Q.has(X))continue;Q.add(X)}Z.push(K)}if(Q.size===J.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:gZ})}return W}function t($,J){return{type:$==="assistant"?"output_text":"input_text",text:J}}function cZ($){let J=$.attachmentId;return typeof J==="string"&&J.startsWith(p)?J:void 0}function IJ($,J){let Q=[`id=${JSON.stringify($.attachmentId)}`];if($.name)Q.push(`name=${JSON.stringify($.name)}`);if($.mimeType)Q.push(`mimeType=${JSON.stringify($.mimeType)}`);let Z=`attachment ${Q.join(" ")}`;return J?`[${Z}]`:`[${Z} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function mZ($){let J=$.mimeType?.trim().toLowerCase()??"";return{type:(J?J.startsWith("image/")&&J!=="image/svg+xml":pZ($.name))?"input_image":"input_file",file_id:$.fileId}}function pZ($){let J=/\.([a-z0-9]+)$/.exec($?.trim().toLowerCase()??"");return J?.[1]!==void 0&&lZ.has(J[1])}var lZ=new Set(["jpeg","jpg","png","gif","webp"]);function dZ($){if(!$.id)return null;let J={type:"reasoning",id:$.id};return J.summary=$.text?[{type:"summary_text",text:$.text}]:[],J}function iZ($){if($.status==="ok"){let J=$.modelOutput!==void 0?$.modelOutput:$.output;return typeof J==="string"?J:JSON.stringify(J??null)}if($.status==="running"){let J=$.job?.summary===void 0?"":` Started with: ${JSON.stringify($.job.summary)}.`;return`Started background job ${$.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.${J}`}if($.status==="denied"){let J=$.reason?` Reason given: ${$.reason}`:"";if($.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${J}`;if($.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.${J}`;return`The user declined this tool call, so it did not run.${J}`}return`The tool call failed and produced no result. Error (${$.error?.code??"unknown"}): ${$.error?.message??"no message"}`}function nZ($,J){let Q=new Set(k9($?.loaded)),Z=k9($?.namespaces),W=new Set(Z),K=[];for(let G of J)if(v$(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)=>r(Y,!0))})}else if(G.deferred&&Q.has(G.name))K.push(r(G,!0));if(K.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:$.arguments&&typeof $.arguments==="object"?$.arguments:{paths:Z.length>0?Z:[...Q]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:K}]}function k9($){return Array.isArray($)?$.filter((J)=>typeof J==="string"):[]}function v$($){return Array.isArray($.tools)}function oZ($,J){if(!$||$.length===0)return[];if(!J.toolSearch){let W=[];for(let K of $)if(v$(K))for(let X of K.tools)W.push(r(X,!1));else W.push(r(K,!1));return W}let Q=[],Z=!1;for(let W of $)if(v$(W)){let K=W.tools.map((X)=>{if(X.deferred)Z=!0;return r(X,!0)});Q.push({type:"namespace",name:W.name,description:W.description,tools:K})}else{if(W.deferred)Z=!0;Q.push(r(W,!0))}if(Z)Q.push({type:"tool_search"});return Q}function r($,J){let Q={type:"function",name:$.name,description:$.description,parameters:$.parameters,strict:$.strict};if(J&&$.deferred)Q.defer_loading=!0;return Q}class e{static models(){return[]}normalizeError($){return j($)}}var x9=["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 bJ extends e{model;capabilities;config;constructor($,J={}){super();this.model=$,this.capabilities=xJ($),this.config=J}static model($,J){return new bJ($,J)}static models(){return x9}stream($){let J=wJ($,{model:this.model,capabilities:this.capabilities});return jJ(this.endpoint(),J,{signal:$.signal,structuredOutput:Boolean($.output),files:MJ($.messages)})}upload($){return kJ(this.endpoint(),$)}endpoint(){return TJ(Y$(this.config))}get realtime(){return new V$(Y$(this.config,{timeoutMs:qJ}),{model:this.model})}}class fJ extends e{model;capabilities;config;constructor($,J={}){super();this.model=$,this.capabilities=xJ($),this.config=J}static model($,J){return new fJ($,J)}static models(){return x9}stream($){let J=wJ($,{model:this.deployment(),capabilities:this.capabilities});return jJ(this.endpoint(),J,{signal:$.signal,structuredOutput:Boolean($.output),files:MJ($.messages)})}upload($){return kJ(this.endpoint(),$,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return TJ(G$(this.config))}get realtime(){return new V$(Q9(this.config,{timeoutMs:qJ}),{model:this.deployment(),callFlow:"ephemeral"})}}class y${now;entries=new Map;constructor($=Date.now){this.now=$}allow($,J){let Q=this.entries.get($);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+J.cooldownMs,!0}record($,J,Q){let Z=this.entries.get($)??{failures:0},W=Z.openUntil!==void 0;if(J==="success")return this.entries.delete($),W?"closed":void 0;if(J==="none"){delete Z.probeUntil;return}if(Z.failures+=1,this.entries.set($,Z),W||Z.failures>=Q.failures)return Z.openUntil=this.now()+Q.cooldownMs,delete Z.probeUntil,W?void 0:"open";return}state($){let J=this.entries.get($);if(J?.openUntil===void 0)return"closed";return this.now()<J.openUntil?"open":"half-open"}}var q9=Symbol("timed-out");class H$ extends e{model;capabilities;entries;options;circuit;constructor($,J={}){super();if($.length===0)throw Error("FallbackProvider needs at least one provider.");for(let Z of $)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=[...$];let Q=J.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 $){let V=vJ(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 y$;this.options={...J,circuit:{...Q,store:X}},this.circuit={policy:{failures:Z,cooldownMs:W},store:X,...Q.onStateChange?{onStateChange:Q.onStateChange}:{}}}else this.options=J,this.circuit=void 0;this.model=$[0].provider.model,this.capabilities=sZ($.map((Z)=>Z.provider.capabilities))}static chain($,J){return new H$($,J)}from($){if(!Number.isInteger($)||$<0||$>=this.entries.length)throw RangeError(`FallbackProvider.from(${$}): the chain has ${this.entries.length} entries.`);return new H$(this.entries.slice($),this.options)}leg($){let J=this.from($).entries[0];return new H$([J],this.options)}upload($){return this.entries[0].provider.upload($)}normalizeError($){return this.entries[0].provider.normalizeError($)}stream($){return this.run($)}async*run($){let J,Q=$.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,C=!1,N,P,B,U=!1,L,O=!1,A=(_)=>{let k=J?E(E(R(),J),_.usage):_.usage;return J=void 0,{..._,usage:k}};try{L=K.provider.stream({...$,...K.reasoning!==void 0?{reasoning:K.reasoning}:{},signal:H.signal})[Symbol.asyncIterator]();let _=!0;for(;;){let k=_&&K.timeoutMs!==void 0?await aZ(L.next(),K.timeoutMs):await L.next();if(k===q9){U=!0,B={error:{code:"provider_error",message:`${G} sent nothing within ${K.timeoutMs}ms.`,retryable:!0}};break}if(_=!1,k.done){O=!0;break}let M=k.value;if(M.type==="finish"&&M.model)P=M.model;if(F){if(M.type==="finish")N=E(N??R(),M.usage),C=!0,yield A(M);else{if(M.type==="error")B={error:M.error};yield M}continue}if(I$(M)){F=!0,await Y("success"),yield*z.splice(0),yield M;continue}if(M.type==="error")B={error:M.error,...M.status!==void 0?{status:M.status}:{},...M.requestId!==void 0?{requestId:M.requestId}:{}};else if(M.type==="finish"){if(N=E(N??R(),M.usage),M.reason==="error"&&!B)B={error:{code:"provider_error",message:`${G} ended the call with an error and did not say which.`,retryable:!1}}}z.push(M)}}catch(_){let k=K.provider.normalizeError(_);if(F){if(k.code!=="aborted")yield{type:"error",error:k,...a(_)};this.report({index:W,model:G,responseModel:P,attempt:Z,usage:N,outcome:yJ(k),error:k}),yield A({type:"finish",reason:k.code==="aborted"?"aborted":"error",usage:R(),...P?{model:P}:{}});return}B={error:k,...a(_)}}finally{if(Q?.removeEventListener("abort",D),!O)H.abort(),L?.return?.()?.catch(()=>{})}if(F){if(!C&&J)yield{type:"finish",reason:B?"error":"stop",usage:J},J=void 0;this.report({index:W,model:G,responseModel:P,attempt:Z,usage:N,outcome:B?yJ(B.error):"ok",...B?{error:B.error}:{}});return}if(Q?.aborted){await Y("none"),this.report({index:W,model:G,responseModel:P,attempt:Z,usage:N,outcome:"aborted"}),yield A({type:"finish",reason:"aborted",usage:N??R(),...P?{model:P}:{}});return}if(!B){await Y("success"),this.report({index:W,model:G,responseModel:P,attempt:Z,usage:N,outcome:"ok"});for(let _ of z)yield _.type==="finish"?A(_):_;return}let x=!X&&B.error.code!=="aborted"&&this.shouldFallBack(B.error,{index:W,model:G,timedOut:U,...B.status!==void 0?{status:B.status}:{},...B.requestId!==void 0?{requestId:B.requestId}:{}});if(await Y(x?"failure":"none"),this.report({index:W,model:G,responseModel:P,attempt:Z,usage:N,outcome:x?"fallback":yJ(B.error),error:B.error}),x){if(N)J=E(J??R(),N);continue}let I=!1,i;for(let _ of z){if(_.type==="finish"){i=_;continue}if(_.type==="error")I=!0;yield _}if(!I&&B.error.code!=="aborted")yield{type:"error",error:B.error,...B.status!==void 0?{status:B.status}:{},...B.requestId!==void 0?{requestId:B.requestId}:{}};yield A({type:"finish",reason:B.error.code==="aborted"?"aborted":i?.reason??"error",usage:N??R(),...P?{model:P}:{}});return}}async allow($){if(!this.circuit)return!0;try{return await this.circuit.store.allow(vJ($),this.circuit.policy)}catch{return!0}}async record($,J,Q){if(!this.circuit)return;let Z=vJ(J),W;try{W=await this.circuit.store.record(Z,Q,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:$,model:J.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($){if($.usage===void 0)delete $.usage;if($.responseModel===void 0)delete $.responseModel;try{this.options.onUsage?.($)}catch{}}}function vJ($){return $.circuitKey??$.provider.model}function yJ($){return $.code==="aborted"?"aborted":"failed"}function sZ($){return{reasoning:$.every((J)=>J.reasoning),structuredOutput:$.every((J)=>J.structuredOutput),fileInput:$.every((J)=>J.fileInput),parallelToolCalls:$.every((J)=>J.parallelToolCalls),toolSearch:$.every((J)=>J.toolSearch)}}function aZ($,J){let Q,Z=new Promise((W)=>{Q=setTimeout(()=>W(q9),J)});return Promise.race([$,Z]).finally(()=>clearTimeout(Q))}async function tZ($,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<$.entries.length;K++){let X=$.leg(K),G={index:K,model:X.model,results:[],errors:[]};for(let V=0;V<Z;V++)try{G.results.push(await J(X,{index:K,sample:V}))}catch(Y){G.errors.push({sample:V,error:Y})}W.push(G)}return W}class g$ extends Error{line;constructor($){super($??"Voice session ended by the app.");this.name="VoiceHangup",this.line=$}}var D$="ask_agent",rZ={maxDurationMs:900000,idleTimeoutMs:120000,maxQueued:3,progressIntervalMs:4000,closingLineMs:1e4,tickMs:60000,hangupGraceMs:30000,toolTimeoutMs:60000,maxToolCallsPerMinute:20,toolOutputChars:8000},eZ={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 z$($={}){return[{name:$.name??D$,description:$.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 h$=new Map;class l{sessionId;threadId;callId;ended;params;sideband;hangupCall;limits;lines;delegateName;startedAt=Date.now();body;usage=R();transcription={usage:R(),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($){return new l($)}static get($){return h$.get($)}static async endAll($){await Promise.all([...h$.values()].map((J)=>J.end("hangup",$)))}constructor($){this.params=$,this.sessionId=$.sessionId??crypto.randomUUID(),this.threadId=$.threadId,this.body=$.body??{},this.limits={...rZ,...I9($.limits)},this.lines={...eZ,...I9($.lines)},this.delegateName=$.delegate?.name??D$;let J=new Set(z$($.delegate).map((Q)=>Q.name));for(let Q of $.tools??[]){if(J.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 $.call){let{realtime:Q,callId:Z}=$.call;this.callId=Z,this.sideband=Q.sideband(Z),this.hangupCall=()=>this.sideband.hangup()}else this.callId=$.call.callId??$.call.sideband.callId,this.sideband=$.call.sideband,this.hangupCall=()=>this.sideband.hangup();this.ended=new Promise((Q)=>this.resolveEnded=Q),h$.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($){this.body=$;let J=this.params.contextNote?.($);if(J)this.sideband.addNote(J)}end($="hangup",J){return this.ending??=this.finish($,J??null)}async listen(){for await(let $ of this.sideband){try{this.params.onEvent?.($)}catch{}this.closingWaiter?.($),await this.handle($)}}async handle($){switch($.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(J){this.usage=E(this.usage,J);let Q=this.info();this.hook(()=>this.params.onUsage?.(J,Q))}return}case"conversation.item.input_audio_transcription.completed":{let J=$;if(this.say("user",String(J.transcript??"")),J.transcriptionUsage||J.transcriptionSeconds!==void 0){this.transcription={usage:J.transcriptionUsage?E(this.transcription.usage,J.transcriptionUsage):this.transcription.usage,seconds:this.transcription.seconds+(J.transcriptionSeconds??0)};let Q=this.info(),Z={...J.transcriptionUsage?{usage:J.transcriptionUsage}:{},...J.transcriptionSeconds!==void 0?{seconds:J.transcriptionSeconds}:{}};this.hook(()=>this.params.onTranscriptionUsage?.(Z,Q))}return}case"response.output_audio_transcript.done":this.say("assistant",String($.transcript??""));return;case"response.output_text.done":this.say("assistant",String($.text??""));return;case"response.function_call_arguments.done":{let J=$;if(this.touch(),!this.ending)this.call(J.call_id,J.name,J.arguments);return}case"session.updated":if(this.tampered($.session))this.end("session_tampered",null);return;case"error":{let J=$.error;if(this.errors.push({code:J?.code,message:String(J?.message??"")}),this.pendingCreate&&J?.event_id===this.pendingCreate)if(this.pendingCreate=void 0,J.code==="conversation_already_has_active_response")this.responseActive=!0,this.responseWanted=!0;else this.responseActive=!1;return}case"sideband.closed":{let J=$;if(!this.ending&&!J.byClient)this.end(J.code===1000?"call_ended":"sideband_lost",null);return}}}say($,J){if(J.trim())this.transcript.push({role:$,text:J,at:Date.now()})}call($,J,Q){let Z=$0(Q);if(J===this.delegateName){let K=typeof Z.request==="string"?Z.request.trim():"";if(!K)return this.answer($,{status:"error",message:"The request was empty."});return this.enqueue({record:{request:K,status:"queued"},turn:{text:K},callId:$})}let W=this.toolHandlers.get(J);if(W)return void this.runTool($,W,Z);switch(J){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($,{stopped:Boolean(K),dropped:X})}case"work_status":return this.answer($,{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($,{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)=>J0(V,K,X));return this.pending=[],this.enqueue({record:{request:`(answer) ${K}`,status:"queued"},turn:{toolResults:G},callId:$})}default:return this.answer($,{status:"error",message:`There is no tool called ${J}.`})}}enqueue($){if(!this.running){this.requests.push($.record),this.run($);return}if(this.queue.length>=this.limits.maxQueued)return this.answer($.callId,{status:"busy",message:"Too many requests are waiting. Ask the user to wait for the current one."});this.requests.push($.record),this.queue.push($),this.answer($.callId,{status:"queued",position:this.queue.length,message:"It will start when the current request is done."}),$.callId=void 0}async run($){this.running=$,$.record.status="running",this.lastProgress=void 0,this.pauseIdle();try{let J=new Set;await this.waitForThread(J);let Q=await this.latestBody();while(!$.stopRequested&&await this.waitForThread(J));if($.stopRequested||this.ending){$.record.status="dropped",this.complete($,{status:"stopped"});return}let Z;try{Z=await this.params.controller.startTurn({threadId:this.threadId,user:this.params.user,body:Q,turn:$.turn})}catch(K){$.record.status="refused",this.complete($,{status:"refused",message:K instanceof Error?K.message:"The request could not be started."});return}$.handle=Z,$.record.runId=Z.runId,this.follow(Z);let W=await Z.result();if($.record.status="done",$.record.finishReason=W.finishReason,W.finishReason==="awaiting-input"&&W.pending.length)this.pending=W.pending,this.complete($,{status:"needs_input",text:W.text,questions:this.questions()});else if(W.finishReason==="error")this.complete($,{status:"failed",message:W.error?.message??"The work failed."});else if(W.finishReason==="aborted")this.complete($,{status:"stopped",text:W.text});else this.complete($,{status:"done",text:W.text})}catch(J){$.record.status="done",this.complete($,{status:"failed",message:J instanceof Error?J.message:"The work failed."})}finally{this.running=void 0,this.flushNote();let J=this.queue.shift();if(J&&!this.ending)this.run(J);else this.touch()}}async runTool($,J,Q){let Z=J.tool.name,W=Date.now();if(this.toolCallTimes=this.toolCallTimes.filter((D)=>W-D<60000),this.toolCallTimes.length>=this.limits.maxToolCallsPerMinute){let D={name:Z,status:"busy"};this.toolCalls.push(D),this.answer($,{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=J.timeoutMs??this.limits.toolTimeoutMs,V,Y;try{let D=await Promise.race([J.run(Q,{sessionId:this.sessionId,signal:X.signal}),new Promise((z,F)=>{V=setTimeout(()=>{F(new u(`"${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 g$){K.status="refused",K.message=D.message,this.end("usage",D.line??null);return}let z=D instanceof u?D.message:"The tool failed.";if(!(D instanceof u))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($,Y)}clip($){let J;try{J=JSON.stringify($)}catch{return String($)}if(J===void 0||J.length<=this.limits.toolOutputChars)return $;return`${J.slice(0,this.limits.toolOutputChars)}\u2026 (cut: ${J.length} characters in all)`}async waitForThread($=new Set){let J=this.params.liveRuns;if(!J)return!1;let Q=await J.find({threadId:this.threadId}),Z=Q&&!$.has(Q.runId)?J.get(Q.runId):null;if(!Q||!Z)return!1;return $.add(Q.runId),await Z.result().catch(()=>{return}),!0}async latestBody(){let $=this.params.store;if(!$)return this.body;let J=await $.get(this.sessionId).catch(()=>null);if(J)this.body=J.body;return this.body}async follow($){let J=this.params.progress??Q0();try{for await(let Q of $.run){let Z=J(Q);if(Z)this.note(Z)}}catch{}}complete($,J){if(this.ending)return;if($.callId)this.sideband.functionOutput($.callId,J),$.callId=void 0;else this.sideband.addNote(`Update on the earlier request "${$.record.request}": ${JSON.stringify(J)}`);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 $=`gemi_voice_${crypto.randomUUID()}`;this.pendingCreate=$,this.sideband.send({type:"response.create",event_id:$})}questions(){return this.pending.map(($)=>({kind:$.kind,tool:String($.name),input:$.input}))}dropQueue(){let $=this.queue.splice(0);for(let J of $)J.record.status="dropped";return $.length}note($){if($===this.lastProgress)return;this.lastProgress=$;let J=this.lastNoteAt+this.limits.progressIntervalMs-Date.now();if(J<=0)return this.flushNote();this.noteTimer??=setTimeout(()=>this.flushNote(),J)}flushNote(){if(this.noteTimer)clearTimeout(this.noteTimer);if(this.noteTimer=void 0,!this.lastProgress||this.ending||!this.running)return;this.lastNoteAt=Date.now(),this.sideband.addNote(`Progress on "${this.running.record.request}": ${this.lastProgress}`)}touch(){if(this.idleTimer)clearTimeout(this.idleTimer);if(this.idleTimer=void 0,this.running||this.toolsRunning>0||this.ending)return;this.idleTimer=setTimeout(()=>void this.end("idle",this.lines.idle),this.limits.idleTimeoutMs)}pauseIdle(){if(this.idleTimer)clearTimeout(this.idleTimer);this.idleTimer=void 0}info(){return{sessionId:this.sessionId,total:this.usage,elapsedMs:Date.now()-this.startedAt,transcription:this.transcription}}tick(){if(this.ending)return;let $=this.info();this.hook(()=>this.params.onTick?.($))}hook($){this.hooks=this.hooks.then(async()=>{try{await $()}catch(J){if(J instanceof g$)this.end("usage",J.line??null);else console.error("[gemi/ai] a voice hook threw; ending the call.",J),this.end("error",this.lines.error)}})}tampered($){let J=this.params.session;if(!J||!$)return!1;if(J.instructions!==void 0&&$.instructions!==void 0&&$.instructions!==J.instructions)return!0;if(Array.isArray($.tools)){let Q=new Set([...z$(this.params.delegate),...J.tools??[]].map((W)=>W.name)),Z=new Set($.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"&&$!=="sideband_lost"))await this.closingLine(J);if($!=="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:$,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};h$.delete(this.sessionId),await this.params.store?.update(this.sessionId,{endedAt:Z,endReason:$}).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($){console.error("[gemi/ai] a voice call could not be hung up; waiting for the vendor.",$),this.errors.push({code:"hangup_failed",message:$ instanceof Error?$.message:String($)});let J;await Promise.race([this.sideband.closed,new Promise((Q)=>J=setTimeout(Q,this.limits.hangupGraceMs))]),clearTimeout(J),this.sideband.close()}}async closingLine($){await new Promise((J)=>{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),J()}let V=()=>{W="asked",this.sideband.send({type:"response.create",event_id:Q,response:{instructions:`Say exactly this to the user, and nothing else: "${$}"`,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 I9($){if(!$)return{};return Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))}function $0($){try{let J=JSON.parse($);return J&&typeof J==="object"&&!Array.isArray(J)?J:{}}catch{return{}}}function J0($,J,Q){let Z={toolCallId:$.toolCallId,signature:$.signature,...$.path?{path:$.path}:{}};if($.kind==="question")return{...Z,output:J};if($.kind==="approval")return{...Z,approve:Q===!0,...J?{reason:J}:{}};return{...Z,approve:!1,reason:"Not available in a voice call."}}function Q0(){let $=new Set;return(J)=>{if(J.type==="tool-call"){if(J.part.partial||J.resent||$.has(J.part.toolCallId))return;return $.add(J.part.toolCallId),`running ${String(J.part.name)}`}if(J.type==="tool-progress"){let Q=J.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 w9="http://gemi.internal/__gemi__/voice/mcp";async function hJ($,J){if(!J.user)throw Error("Voice MCP tools run as the signed-in user, and this voice session has none. Give `mcp` only to a signed-in user's session.");let{registry:Q}=$,Z=$.scopes??Q.scopes().map((X)=>X.name),W=(X)=>({kind:"remote",req:X,principal:{user:J.user,via:"voice",id:`voice:${J.sessionId}`,scopes:Z}});return(await Q.available(W(b9()),$.filter)).filter((X)=>!X.requiresApproval).map((X)=>({tool:{name:X.name,description:X.description,parameters:X.inputSchema},...$.timeoutMs!==void 0?{timeoutMs:$.timeoutMs}:{},run:(G,V)=>{let Y=b9();return g.run(Y,async()=>{return await $.authorize?.({name:X.name,input:G,sessionId:V.sessionId}),Q.execute(W(Y),X.name,G,void 0,{signal:V.signal})},{user:J.user})}}))}function b9(){return new q(new Request(w9,{method:"POST"}),{},"api",new URL(w9).pathname)}class gJ{records=new Map;retainEndedMs;constructor($={}){this.retainEndedMs=$.retainEndedMs??600000}async create($){this.sweep(),this.records.set($.id,structuredClone($))}async get($){let J=this.records.get($);return J?structuredClone(J):null}async update($,J){let Q=this.records.get($);if(!Q)return;this.records.set($,{...Q,...structuredClone(J),id:$})}sweep(){let $=Date.now()-this.retainEndedMs;for(let[J,Q]of this.records)if(Q.endedAt!==void 0&&Q.endedAt<$)this.records.delete(J)}}var uJ=new gJ;var f9=new WeakMap,v9=100;class m9{threadsTable;messagesTable;sql;dialect;connection;constructor($,J={}){this.threadsTable=y9(J.threadsTable??"gemi_agent_threads","threads"),this.messagesTable=y9(J.messagesTable??"gemi_agent_messages","messages"),this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name}async createTable(){let $=K0(this.dialect,this.threadsTable,this.messagesTable);for(let J of $)await this.sql.unsafe(J)}async createThread($){let J=this.q(),Q=crypto.randomUUID(),Z=$.userId===void 0||$.userId===null?null:String($.userId),W=this.clock(J);return await J`
|
|
147
147
|
INSERT INTO ${this.threads(J)} (id, user_id, created_at, updated_at)
|
|
148
148
|
VALUES (${Q}, ${Z}, ${W}, ${W})
|
|
149
149
|
`,{threadId:Q}}async loadThread($){let J=this.q();if((await J`SELECT id FROM ${this.threads(J)} WHERE id = ${$}`).length===0)return null;return(await J`
|
|
150
150
|
SELECT message FROM ${this.messages(J)}
|
|
151
151
|
WHERE thread_id = ${$}
|
|
152
152
|
ORDER BY position
|
|
153
|
-
`).map((W)=>JSON.parse(String(W.message)))}async appendMessages($,J){if(J.length===0){if(await this.getThread($)===null)throw
|
|
153
|
+
`).map((W)=>JSON.parse(String(W.message)))}async appendMessages($,J){if(J.length===0){if(await this.getThread($)===null)throw h9($);return}await this.atomically(async(Q)=>{await Q`UPDATE ${this.threads(Q)} SET updated_at = ${this.clock(Q)} WHERE id = ${$}`;let Z=await Q`
|
|
154
154
|
SELECT title FROM ${this.threads(Q)} WHERE id = ${$}
|
|
155
|
-
`;if(Z.length===0)throw
|
|
155
|
+
`;if(Z.length===0)throw h9($);let W=[...new Set(J.map((Y)=>Y.id))],K=await Q`
|
|
156
156
|
SELECT id FROM ${this.messages(Q)}
|
|
157
|
-
WHERE thread_id = ${$} AND id IN (${
|
|
157
|
+
WHERE thread_id = ${$} AND id IN (${g9(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 = ${$}
|
|
160
160
|
`,V=G?.position===null||G?.position===void 0?0:Number(G.position)+1;for(let Y of J){let H=JSON.stringify(Y);if(X.has(Y.id))await Q`
|
|
@@ -163,35 +163,35 @@ import{$b as Z8,$c as Q6,Ac as e9,Bc as $Q,Cc as M8,Ec as S8,Fc as k8,Gc as E8,H
|
|
|
163
163
|
`;else await Q`
|
|
164
164
|
INSERT INTO ${this.messages(Q)} (thread_id, id, position, message, created_at)
|
|
165
165
|
VALUES (${$}, ${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=Z0(J);if(Y!==null)await Q`
|
|
167
167
|
UPDATE ${this.threads(Q)} SET title = ${Y}
|
|
168
168
|
WHERE id = ${$} AND title IS NULL
|
|
169
169
|
`}})}async removeMessages($,J){if(J.length===0)return;let Q=this.q();await Q`
|
|
170
170
|
DELETE FROM ${this.messages(Q)}
|
|
171
|
-
WHERE thread_id = ${$} AND id IN (${
|
|
171
|
+
WHERE thread_id = ${$} AND id IN (${g9(Q,[...new Set(J)])})
|
|
172
172
|
`}async loadSummaries($){let J=this.q(),[Q]=await J`
|
|
173
173
|
SELECT summaries FROM ${this.threads(J)} WHERE id = ${$}
|
|
174
|
-
`;return Q?
|
|
174
|
+
`;return Q?u9(Q.summaries):[]}async saveSummary($,J){await this.atomically(async(Q)=>{await Q`UPDATE ${this.threads(Q)} SET updated_at = updated_at WHERE id = ${$}`;let[Z]=await Q`
|
|
175
175
|
SELECT summaries FROM ${this.threads(Q)} WHERE id = ${$}
|
|
176
|
-
`;if(!Z)return;let W=F$(
|
|
176
|
+
`;if(!Z)return;let W=F$(u9(Z.summaries),J);await Q`
|
|
177
177
|
UPDATE ${this.threads(Q)} SET summaries = ${JSON.stringify(W)}
|
|
178
178
|
WHERE id = ${$}
|
|
179
179
|
`})}async lockSummary($,J,Q){let Z=this.q(),W=`${J}:${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 = ${$} AND (summary_lock_until IS NULL OR summary_lock_until <= ${K})
|
|
183
|
-
`;if(
|
|
183
|
+
`;if(W0(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 = ${$} AND summary_lock = ${W}
|
|
186
186
|
`}}async getThread($){let J=this.q(),[Q]=await J`
|
|
187
187
|
SELECT id, user_id, title, created_at, updated_at FROM ${this.threads(J)}
|
|
188
188
|
WHERE id = ${$}
|
|
189
|
-
`;return Q?
|
|
189
|
+
`;return Q?c9(Q):null}async listThreads($={}){let J=this.q(),Q=Math.max(0,Math.floor($.limit??50)),Z=Math.max(0,Math.floor($.offset??0)),W=$.userId===void 0?J`1 = 1`:$.userId===null?J`user_id IS NULL`:J`user_id = ${String($.userId)}`;return(await J`
|
|
190
190
|
SELECT id, user_id, title, created_at, updated_at FROM ${this.threads(J)}
|
|
191
191
|
WHERE ${W}
|
|
192
192
|
ORDER BY updated_at DESC, id DESC
|
|
193
193
|
LIMIT ${Q} OFFSET ${Z}
|
|
194
|
-
`).map(
|
|
194
|
+
`).map(c9)}async deleteThread($){await this.atomically(async(J)=>{await J`DELETE FROM ${this.messages(J)} WHERE thread_id = ${$}`,await J`DELETE FROM ${this.threads(J)} WHERE id = ${$}`})}atomically($){if(this.joinable())return R$(this.sql,(W)=>$(W),{connection:this.connection});let J=()=>this.sql.begin((W)=>$(W));if(this.dialect!=="sqlite")return J();let Z=(f9.get(this.sql)??Promise.resolve()).then(J,J);return f9.set(this.sql,Z.then(()=>{},()=>{})),Z}joinable(){if(this.connection===void 0)return;let $=o();if($===void 0||s()!==this.connection)return;return $}q(){return this.joinable()??this.sql}quote($){return this.dialect==="mysql"||this.dialect==="mariadb"?`\`${$}\``:`"${$}"`}threads($){return $.unsafe(this.quote(this.threadsTable))}messages($){return $.unsafe(this.quote(this.messagesTable))}clock($){switch(this.dialect){case"postgres":return $`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return $`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return $`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms($,J){let Q=Math.max(0,Math.round(J));return this.dialect==="mysql"||this.dialect==="mariadb"?$`CAST(${Q} AS SIGNED)`:$`CAST(${Q} AS BIGINT)`}}function y9($,J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test($))throw Error(`The agent ${J} table name "${$}" is not a plain identifier. Use letters, digits and underscores.`);return $}function h9($){return Error(`Thread ${$} does not exist here, or has been deleted.`)}function g9($,J){return J.map((Q)=>$`${Q}`).reduce((Q,Z)=>$`${Q}, ${Z}`)}function Z0($){for(let J of $){if(J.role!=="user")continue;let Q=J.content.map((Z)=>Z.type==="text"?Z.text:"").join(" ").replace(/\s+/g," ").trim();if(Q)return Q.length>v9?`${Q.slice(0,v9-1)}\u2026`:Q}return null}function u9($){if($===null||$===void 0||$==="")return[];let J=JSON.parse(String($));return Array.isArray(J)?J:[]}function c9($){return{id:String($.id),userId:$.user_id===null||$.user_id===void 0?null:String($.user_id),title:$.title===null||$.title===void 0?null:String($.title),createdAt:Number($.created_at),updatedAt:Number($.updated_at)}}function W0($){let J=$;return Math.max(Number(J.count??0),Number(J.affectedRows??0))}function K0($,J,Q){if($==="mysql"||$==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${J}\` (
|
|
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 Z8,$c as Q6,Ac as e9,Bc as $Q,Cc as M8,Ec as S8,Fc as k8,Gc as E8,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 $$ extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor($,J,Q){super(`Frame ${J} of run ${$} has been evicted; the oldest frame still buffered is ${Q}. Reload the thread instead of resuming.`);this.runId=$;this.requested=J;this.oldest=Q}}class B$ extends Error{runId;code="live_run_not_found";constructor($){super(`No live run ${$} in this process.`);this.runId=$}}class u${ttlMs;maxFrames;maxAgeMs;runs=new Map;byThread=new Map;byClientRun=new Map;constructor($={}){this.ttlMs=$.ttlMs??60000,this.maxFrames=$.maxFrames??4096,this.maxAgeMs=$.maxAgeMs===void 0?3600000:$.maxAgeMs}register($,J={}){let Q={run:$,threadId:J.threadId,owner:J.owner??null,clientRunId:J.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evicted:!1,evictAt:null,expireAt:null,wake:new Set,version:0};if(this.runs.set($.runId,Q),J.threadId)this.byThread.set(J.threadId,$.runId);if(J.clientRunId)this.byClientRun.set(J.clientRunId,$.runId);return this.scheduleExpiry(Q,J.maxRunDurationMs),this.pump(Q,J)}findByClientRunId($){let J=this.byClientRun.get($);return J&&this.runs.has(J)?J:null}async find($){let J=this.byThread.get($.threadId);if(!J)return null;let Q=this.runs.get(J);if(!Q)return null;return{runId:J,seq:Q.lastSeq}}get($){return this.runs.get($)?.run??null}ownerOf($){return this.runs.get($)?.owner??null}mayAccess($,J){let Q=this.ownerOf($);return Q===null||Q===J}isRunning($){let J=this.runs.get($);return!!J&&!J.ended&&!J.evicted}replay($,J){let Q=this.runs.get($);if(!Q)throw new B$($);if(J!==void 0&&J<Q.lostBefore)throw new $$($,J,Q.lostBefore);let Z=Q.frames[0]?.seq;return this.drain(Q,$,J??Z??Q.lastSeq+1)}clear(){for(let $ of this.runs.values()){if($.evictAt)clearTimeout($.evictAt);if($.expireAt)clearTimeout($.expireAt);$.ended=!0,this.notify($)}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 $.run.frames()){if($.evicted){let K=J.onEvent;if(K)Q=Q.then(()=>K(Z.event)).catch((X)=>cJ(J,X));continue}if($.frames.push(Z),$.lastSeq=Z.seq,$.frames.length>this.maxFrames){let K=$.frames.shift();if(K)$.lostBefore=K.seq+1}this.notify($);let W=J.onEvent;if(W)Q=Q.then(()=>W(Z.event)).catch((K)=>cJ(J,K))}}catch(Z){cJ(J,Z)}finally{if($.ended=!0,$.expireAt)clearTimeout($.expireAt),$.expireAt=null;this.notify($),this.scheduleEviction($),await Q}}async*drain($,J,Q){let Z=Q;while(!0){let W=$.version;for(;;){if(Z<$.lostBefore)throw new $$(J,Z,$.lostBefore);let K=$.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($.ended&&Z>$.lastSeq||$.evicted)return;await this.wait($,W)}}wait($,J){if($.version!==J)return Promise.resolve();return new Promise((Q)=>$.wake.add(Q))}notify($){$.version++;let J=Array.from($.wake);$.wake.clear();for(let Q of J)Q()}scheduleEviction($){if($.evictAt)return;let J=setTimeout(()=>{let Q=$.run.runId;if(!$.ended)$.evicted=!0,$.frames=[];if(this.runs.get(Q)===$)this.runs.delete(Q);if($.threadId&&this.byThread.get($.threadId)===Q)this.byThread.delete($.threadId);if($.clientRunId&&this.byClientRun.get($.clientRunId)===Q)this.byClientRun.delete($.clientRunId);this.notify($)},this.ttlMs);J.unref?.(),$.evictAt=J}scheduleExpiry($,J){if(this.maxAgeMs===null||J===null)return;let Q=J===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,J+this.ttlMs);if(!Number.isFinite(Q)||Q>2147483647)return;let Z=setTimeout(()=>{if($.expireAt=null,$.ended)return;try{$.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($)},Q);Z.unref?.(),$.expireAt=Z}}var mJ=new u$;function cJ($,J){try{$.onInternalError?.(J)}catch{}}class c${maxEntries;records=new Map;constructor($=1e5){this.maxEntries=$}async record($,J){if(this.records.has($))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($){let J=this.records.get($);return J?{...J}:null}}var pJ=new c$;class iJ{now;receipts=new Map;sweepAt=1024;constructor($=Date.now){this.now=$}async claim($,J){let Q=this.now();if(this.receipts.size>=this.sweepAt)this.sweep(Q);let Z=this.receipts.get($);if(Z&&Z.expiresAt>Q)return Z.result?{status:"replay",result:structuredClone(Z.result)}:{status:"blocked"};return this.receipts.set($,{expiresAt:J}),{status:"claimed"}}async complete($,J,Q){this.receipts.set($,{result:structuredClone(J),expiresAt:Q})}async release($){let J=this.receipts.get($);if(J&&!J.result)this.receipts.delete($)}get size(){return this.receipts.size}sweep($){for(let[J,Q]of this.receipts)if(Q.expiresAt<=$)this.receipts.delete(J);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var
|
|
234
|
+
)`,`CREATE UNIQUE INDEX IF NOT EXISTS "${Q}_thread_id_position_key" ON "${Q}"("thread_id", "position")`]}class $$ extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor($,J,Q){super(`Frame ${J} of run ${$} has been evicted; the oldest frame still buffered is ${Q}. Reload the thread instead of resuming.`);this.runId=$;this.requested=J;this.oldest=Q}}class B$ extends Error{runId;code="live_run_not_found";constructor($){super(`No live run ${$} in this process.`);this.runId=$}}class u${ttlMs;maxFrames;maxAgeMs;runs=new Map;byThread=new Map;byClientRun=new Map;constructor($={}){this.ttlMs=$.ttlMs??60000,this.maxFrames=$.maxFrames??4096,this.maxAgeMs=$.maxAgeMs===void 0?3600000:$.maxAgeMs}register($,J={}){let Q={run:$,threadId:J.threadId,owner:J.owner??null,clientRunId:J.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evicted:!1,evictAt:null,expireAt:null,wake:new Set,version:0};if(this.runs.set($.runId,Q),J.threadId)this.byThread.set(J.threadId,$.runId);if(J.clientRunId)this.byClientRun.set(J.clientRunId,$.runId);return this.scheduleExpiry(Q,J.maxRunDurationMs),this.pump(Q,J)}findByClientRunId($){let J=this.byClientRun.get($);return J&&this.runs.has(J)?J:null}async find($){let J=this.byThread.get($.threadId);if(!J)return null;let Q=this.runs.get(J);if(!Q)return null;return{runId:J,seq:Q.lastSeq}}get($){return this.runs.get($)?.run??null}ownerOf($){return this.runs.get($)?.owner??null}mayAccess($,J){let Q=this.ownerOf($);return Q===null||Q===J}isRunning($){let J=this.runs.get($);return!!J&&!J.ended&&!J.evicted}replay($,J){let Q=this.runs.get($);if(!Q)throw new B$($);if(J!==void 0&&J<Q.lostBefore)throw new $$($,J,Q.lostBefore);let Z=Q.frames[0]?.seq;return this.drain(Q,$,J??Z??Q.lastSeq+1)}clear(){for(let $ of this.runs.values()){if($.evictAt)clearTimeout($.evictAt);if($.expireAt)clearTimeout($.expireAt);$.ended=!0,this.notify($)}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 $.run.frames()){if($.evicted){let K=J.onEvent;if(K)Q=Q.then(()=>K(Z.event)).catch((X)=>cJ(J,X));continue}if($.frames.push(Z),$.lastSeq=Z.seq,$.frames.length>this.maxFrames){let K=$.frames.shift();if(K)$.lostBefore=K.seq+1}this.notify($);let W=J.onEvent;if(W)Q=Q.then(()=>W(Z.event)).catch((K)=>cJ(J,K))}}catch(Z){cJ(J,Z)}finally{if($.ended=!0,$.expireAt)clearTimeout($.expireAt),$.expireAt=null;this.notify($),this.scheduleEviction($),await Q}}async*drain($,J,Q){let Z=Q;while(!0){let W=$.version;for(;;){if(Z<$.lostBefore)throw new $$(J,Z,$.lostBefore);let K=$.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($.ended&&Z>$.lastSeq||$.evicted)return;await this.wait($,W)}}wait($,J){if($.version!==J)return Promise.resolve();return new Promise((Q)=>$.wake.add(Q))}notify($){$.version++;let J=Array.from($.wake);$.wake.clear();for(let Q of J)Q()}scheduleEviction($){if($.evictAt)return;let J=setTimeout(()=>{let Q=$.run.runId;if(!$.ended)$.evicted=!0,$.frames=[];if(this.runs.get(Q)===$)this.runs.delete(Q);if($.threadId&&this.byThread.get($.threadId)===Q)this.byThread.delete($.threadId);if($.clientRunId&&this.byClientRun.get($.clientRunId)===Q)this.byClientRun.delete($.clientRunId);this.notify($)},this.ttlMs);J.unref?.(),$.evictAt=J}scheduleExpiry($,J){if(this.maxAgeMs===null||J===null)return;let Q=J===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,J+this.ttlMs);if(!Number.isFinite(Q)||Q>2147483647)return;let Z=setTimeout(()=>{if($.expireAt=null,$.ended)return;try{$.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($)},Q);Z.unref?.(),$.expireAt=Z}}var mJ=new u$;function cJ($,J){try{$.onInternalError?.(J)}catch{}}class c${maxEntries;records=new Map;constructor($=1e5){this.maxEntries=$}async record($,J){if(this.records.has($))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($){let J=this.records.get($);return J?{...J}:null}}var pJ=new c$;class iJ{now;receipts=new Map;sweepAt=1024;constructor($=Date.now){this.now=$}async claim($,J){let Q=this.now();if(this.receipts.size>=this.sweepAt)this.sweep(Q);let Z=this.receipts.get($);if(Z&&Z.expiresAt>Q)return Z.result?{status:"replay",result:structuredClone(Z.result)}:{status:"blocked"};return this.receipts.set($,{expiresAt:J}),{status:"claimed"}}async complete($,J,Q){this.receipts.set($,{result:structuredClone(J),expiresAt:Q})}async release($){let J=this.receipts.get($);if(J&&!J.result)this.receipts.delete($)}get size(){return this.receipts.size}sweep($){for(let[J,Q]of this.receipts)if(Q.expiresAt<=$)this.receipts.delete(J);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var p9="pending",lJ="done:",X0=`
|
|
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`,Y0=`
|
|
239
239
|
if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end
|
|
240
|
-
return 0`;class nJ{injectedClient;prefix;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:ai:receipt"}async claim($,J){let Q=await this.client.send("EVAL",[W0,"1",this.key($),c9,m9(J)]);if(Q==="claimed")return{status:"claimed"};let Z=String(Q??"");if(Z.startsWith(lJ))return{status:"replay",result:JSON.parse(Z.slice(lJ.length))};return{status:"blocked"}}async complete($,J,Q){await this.client.send("SET",[this.key($),lJ+JSON.stringify(J),"PX",m9(Q)])}async release($){await this.client.send("EVAL",[K0,"1",this.key($),c9])}key($){return`${this.prefix}:${$}`}get client(){if(this.injectedClient)return this.injectedClient;let $=p9(),J=$.bound(dJ)?$.make(dJ).client:void 0;if(!J)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return J}}function m9($){return String(Math.max(1,Math.ceil($-Date.now())))}var X0=86400000,Y0=60000;class m${ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor($={}){this.ttlMs=$.ttlMs??X0,this.clientOwnedIds=$.clientOwnedIds??!1}async createThread($){let J=crypto.randomUUID();return this.threads.set(J,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:J}}async loadThread($){this.sweep();let J=this.threads.get($);if(!J)return this.clientOwnedIds?[]:null;return J.touchedAt=Date.now(),J.messages.slice()}async appendMessages($,J){this.sweep();let Q=this.threads.get($);if(!Q){if(!this.clientOwnedIds)throw Error(`Thread ${$} does not exist here, or has expired.`);Q={messages:[],touchedAt:Date.now()},this.threads.set($,Q)}for(let Z of J){let W=JSON.parse(JSON.stringify(Z)),K=Q.messages.findIndex((X)=>X.id===W.id);if(K===-1)Q.messages.push(W);else Q.messages[K]=W}Q.touchedAt=Date.now()}async removeMessages($,J){this.sweep();let Q=this.threads.get($);if(!Q)return;let Z=new Set(J);Q.messages=Q.messages.filter((W)=>!Z.has(W.id)),Q.touchedAt=Date.now()}async loadSummaries($){return this.threads.get($)?.summaries?.slice()??[]}async saveSummary($,J){let Q=this.threads.get($);if(!Q)return;Q.summaries=F$(Q.summaries??[],J)}delete($){this.threads.delete($)}get size(){return this.threads.size}sweep($=Date.now()){if($-this.lastSweep<Y0)return;this.lastSweep=$;for(let[J,Q]of this.threads)if($-Q.touchedAt>this.ttlMs)this.threads.delete(J)}}var oJ=new m$;function n9($={}){return{messages:$.messages?[...$.messages]:[],pending:$.pending?[...$.pending]:[],error:null,threadId:$.threadId,seq:$.seq??-1,cursorRunId:$.cursorRunId,runMessageIds:[],loadedTools:[]}}function o9($,J,Q=new Date().toISOString()){if(!(J.event.type==="run-start"&&J.event.runId!==$.cursorRunId)&&J.seq<=$.seq)return $;return{...s9($,J.event,Q),seq:J.seq}}function s9($,J,Q){switch(J.type){case"run-start":return{...$,messages:G0($.messages,J.runId),runId:J.runId,cursorRunId:J.runId,threadId:J.threadId??$.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return l($,J.messageId,Q,(Z)=>({...Z,role:J.role}));case"text-delta":if(d9($,J.messageId))return $;return l($,J.messageId,Q,(Z)=>({...Z,content:F0(Z.content,J.delta)}));case"reasoning-delta":if(d9($,J.messageId))return $;return l($,J.messageId,Q,(Z)=>({...Z,content:B0(Z.content,J.delta,J.id)}));case"output-delta":return l($,J.messageId,Q,(Z)=>({...Z,content:i9(Z.content,{type:"output",value:J.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===J.part.toolCallId),K=W===-1?void 0:Z.content[W],X=J.part.progress??K?.progress,G=J.part.nested??K?.nested,V=J.part.attachments??K?.attachments,Y={...J.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=J.loaded.filter((W)=>!$.loadedTools.includes(W));if(Z.length===0)return $;return{...$,loadedTools:[...$.loadedTools,...Z]}}case"tool-progress":return l9($,J.toolCallId,(Z)=>({...Z,progress:[...Z.progress??[],J.data]}));case"nested-event":{let Z=J;return l9($,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=z0(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:i9(W.content,J.part,(K)=>K.type==="tool-result"&&K.toolCallId===J.part.toolCallId)}));return{...Z,pending:Z.pending.filter((W)=>W.toolCallId!==J.part.toolCallId)}}case"message":{let Z=$.messages.findIndex((X)=>X.id===J.message.id),W=$.messages.slice();if(Z===-1)W.push(J.message);else W[Z]=J.message;let K=$.runMessageIds.includes(J.message.id)?$.runMessageIds:[...$.runMessageIds,J.message.id];return{...$,messages:W,runMessageIds:K}}case"message-id":{let Z=$.messages.findIndex((G)=>G.id===J.localId);if(Z===-1){if(!J.message||$.messages.some((G)=>G.id===J.messageId))return $;return{...$,messages:[...$.messages,J.message]}}let W=$.messages[Z],K={localId:W.localId??W.id,...W.metadata?{metadata:W.metadata}:{}},X=$.messages.some((G)=>G.id===J.messageId)?$.messages.filter((G,V)=>V!==Z).map((G)=>G.id===J.messageId?{...G,...K}:G):$.messages.map((G,V)=>V===Z?{...G,...K,id:J.messageId}:G);return{...$,messages:X}}case"awaiting-input":return{...$,runId:J.runId,pending:[...J.pending]};case"message-end":return l($,J.messageId,Q,(Z)=>({...Z,finishReason:J.finishReason,...J.outputTruncated?{outputTruncated:!0}:{},...J.usage?{usage:J.usage}:{},content:J.outputTruncated||J.finishReason==="length"?Z.content.filter((W)=>!(W.type==="output"&&W.partial)):Z.content.map((W)=>W.type==="output"&&W.partial?{...W,partial:!1}:W)}));case"usage":return{...$,usage:J.usage};case"error":return{...$,error:J.error,pending:[]};case"run-end":return{...$,runId:void 0,finishReason:J.finishReason,messages:a9($,J.finishReason)};default:return $}}function G0($,J){if(!$.some((Q)=>Q.runId===J&&Q.finishReason===void 0))return $;return $.map((Q)=>{if(Q.runId!==J||Q.finishReason!==void 0)return Q;let{runId:Z,...W}=Q;return{...W,content:[]}})}function a9($,J){return $.messages.map((Q)=>Q.role==="assistant"&&$.runMessageIds.includes(Q.id)?V0(Q,J):Q)}function V0($,J){let Q=$.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?H0(K,J):K)}:W);if($.finishReason===void 0)return{...$,finishReason:J,content:Q};return Q.some((W,K)=>W!==$.content[K])?{...$,content:Q}:$}function H0($,J){let Q={messages:$.messages,pending:[],error:null,seq:-1,runMessageIds:$.messages.map((Z)=>Z.id),loadedTools:[]};return{...$,finishReason:J,messages:a9(Q,J)}}function l9($,J,Q){for(let Z=$.messages.length-1;Z>=0;Z--){let W=$.messages[Z],K=W.content.findIndex((Y)=>Y.type==="tool-call"&&Y.toolCallId===J);if(K===-1)continue;if(W.finishReason!==void 0&&!D0($,W,J))return $;let X=W.content.slice();X[K]=Q(X[K]);let G=$.messages.slice();G[Z]={...W,content:X};let V=$.runMessageIds.includes(W.id)?$.runMessageIds:[...$.runMessageIds,W.id];return{...$,runMessageIds:V,messages:G}}return $}function z0($,J,Q){let Z={messages:$.messages,pending:[],error:null,seq:-1,runMessageIds:$.messages.map((K)=>K.id),loadedTools:[],finishReason:$.finishReason},W=s9(Z,J.event,Q);return{...$,...J.label!==void 0?{label:J.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function D0($,J,Q){if(J.finishReason!=="awaiting-input")return!1;return!$.messages.some((Z)=>Z.content.some((W)=>W.type==="tool-result"&&W.toolCallId===Q))}function d9($,J){let Q=$.messages.find((Z)=>Z.id===J);return Q!==void 0&&Q.finishReason!==void 0}function l($,J,Q,Z){let W=$.messages.findIndex((G)=>G.id===J),K=$.runMessageIds.includes(J)?$.runMessageIds:[...$.runMessageIds,J];if(W===-1){let G={id:J,role:"assistant",content:[],createdAt:Q};return{...$,runMessageIds:K,messages:[...$.messages,Z(G)]}}let X=$.messages.slice();return X[W]=Z(X[W]),{...$,runMessageIds:K,messages:X}}function F0($,J){let Q=$[$.length-1];if(Q&&Q.type==="text")return[...$.slice(0,-1),{type:"text",text:Q.text+J}];return[...$,{type:"text",text:J}]}function B0($,J,Q){let Z=$[$.length-1];if(Z&&Z.type==="reasoning"&&Z.id===Q)return[...$.slice(0,-1),{...Z,text:(Z.text??"")+J}];return[...$,Q?{type:"reasoning",id:Q,text:J}:{type:"reasoning",text:J}]}function i9($,J,Q){let Z=$.findIndex(Q);if(Z===-1)return[...$,J];let W=$.slice();return W[Z]=J,W}class aJ{store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor($,J,Q,Z){this.store=$;this.threadId=J;this.report=Z;this.state=n9({messages:Q})}finish($){if(this.closed)return;this.done.add($.id),this.write(()=>[sJ($)])}frame($){if(this.closed)return;let J=$.event;if(J.type==="run-start")this.runId=J.runId;switch(this.state=o9(this.state,$),J.type){case"message":this.write(()=>[sJ(J.message)]);return;case"tool-call":if(J.part.partial)return;this.checkpoint(J.messageId);return;case"message-start":case"tool-result":this.checkpoint(J.messageId);return;default:return}}close($=[]){this.closed=!0;for(let J of $)this.done.add(J.id)}settled(){return this.chain}checkpoint($){if(this.done.has($))return;let J=this.state.messages.find((Z)=>Z.id===$);if(!J)return;let Q=this.runId;this.write(()=>{let Z=sJ(J);if(Z.finishReason===void 0&&Q)Z.runId=Q;return[Z]})}write($){let J;try{J=$()}catch(Q){this.report(Q);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,J)).catch((Q)=>this.report(Q))}}function sJ($){return structuredClone($)}async function t9($,J){let Q=[],Z=null,W=$.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 J(X.runId))continue;Z??=new Set($.flatMap((Y)=>Y.content.flatMap((H)=>H.type==="tool-result"?[H.toolCallId]:[])));let G=X.content.map((Y)=>Y.type==="tool-call"?r9(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 r9($){let{partial:J,...Q}=$;if(!Q.nested?.some((Z)=>Z.finishReason===void 0))return Q;return{...Q,nested:Q.nested.map(P0)}}function P0($){if($.finishReason!==void 0)return $;return{...$,finishReason:"interrupted",messages:$.messages.map((J)=>J.role==="assistant"&&J.finishReason===void 0?{...J,finishReason:"interrupted",content:J.content.map((Q)=>Q.type==="tool-call"?r9(Q):Q)}:J)}}var N0=50,U0=["running","ok","error"];async function JQ($,J){let{store:Q,threadId:Z}=J,W=Math.max(N0,J.scan??0),K=await Q.listForThread(Z,{limit:W}),X,G=async(F)=>{if(F.state!=="running")return F;if(X??=await e9(Q),F.deadlineAt>X)return F;return await $Q(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=$.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]=L0(P,O,J.outputSchemaFor,J.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 J.isRunLive(F.runId))continue;z.push(F)}return{messages:Y,settled:H,orphans:z,jobs:K}}async function QQ($,J,Q){for(let Z of J)try{await $.transition(Z.id,U0,{orphaned:!0})}catch(W){Q(W)}}function L0($,J,Q,Z){let W={type:"tool-result",toolCallId:$.toolCallId,name:$.name},K=(V,Y)=>{let H=Z?.(String($.name),V);return{...W,status:"ok",job:Y,output:V,...H!==void 0?{modelOutput:H}:{}}};if(!J)return{...W,status:"error",job:$.job,error:{code:"tool_error",message:`The background job for "${String($.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:$.toolCallId,retryable:!0}};let X={id:J.id,...J.summary!==void 0?{summary:J.summary}:{},...J.usage?{usage:J.usage}:{}};if(J.state==="error")return{...W,status:"error",job:X,error:J.error??{code:"tool_error",message:`The background job for "${String($.name)}" failed.`,toolCallId:$.toolCallId,retryable:!0}};let G=Q?.(String($.name));if(G){let V=G.safeParse(J.output);if(V.ok===!1)return{...W,status:"error",job:X,error:{code:"invalid_tool_result",message:`The background job for "${String($.name)}" finished with an output that does not match the tool's output schema: ${V.errors.join(", ")}`,toolCallId:$.toolCallId,retryable:!0}};return K(V.value,X)}return K(J.output,X)}class r$ extends Error{status;code;kind;constructor($,J){super($);this.name="AgentTurnError",this.status=J.status,this.code=J.code,this.kind=J.kind}static async from($){let J={};try{let Z=await $.json();if(Z?.error&&typeof Z.error==="object")J=Z.error}catch{}let Q=(Z)=>typeof J[Z]==="string"?J[Z]:void 0;return new r$(Q("message")??`The agent turn was refused with status ${$.status}.`,{status:$.status,code:Q("code"),kind:Q("kind")})}}function O0($){for(let J=$.length-1;J>=0;J--){let Q=$[J];if(Q.role!=="assistant")continue;return Q.content.map((Z)=>Z.type==="text"?Z.text:"").join("")}return""}var C0=FQ,p$=new Map,ZQ=new WeakMap,P$=new WeakMap,WQ="http://gemi.internal/__gemi/agent-turn",l$=new Map,_0=4194304,M0=1000,S0=5,d$=65536,i$=()=>{};class kQ{byKey=new Map;take($,J,Q){let Z=this.byKey.get($);if(!Z?.has(J)&&(Z?.size??0)>=Q)return null;if(!Z)Z=new Map,this.byKey.set($,Z);Z.set(J,(Z.get(J)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let K=this.byKey.get($),X=(K?.get(J)??1)-1;if(!K)return;if(X>0)K.set(J,X);else if(K.delete(J),K.size===0)this.byKey.delete($)}}}var KQ=new WeakMap;function A0($){let J=KQ.get($);if(!J)J=new kQ,KQ.set($,J);return J}function R0($){return $}class X8 extends C0{static kind="agent-controller";hooks;store=oJ;liveRuns=mJ;voice;voiceStore=uJ;attachments=t$;attachmentStorage=NQ;fileOwners=pJ;nonces=Z8;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)}runTools($,J){return this.hooks?.runTools?.($,J)}usageLimits($,J){return this.hooks?.usageLimits?.($,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=_0;maxHistoryMessages=M0;contextWindow=void 0;prepareStep($,J){return this.hooks?.prepareStep?.($,J)}maxConcurrentRuns=S0;runLimitKey($,J){let Q=this.hooks?.runLimitKey;if(Q)return Q($,J);return J.owner}authorizeRequest($,J){let Q=this.hooks?.authorizeRequest;if(Q)return Q($,J);return this.resource?.authorize($,J)}resource;runOwner($){let J=this.hooks?.runOwner;if(J)return J($);let Q=$.ctx?.()?.user,Z=Q?.id??Q?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}static async startTurn($){let{threadId:J}=$;if(typeof J!=="string"||J==="")throw TypeError("AgentController.startTurn needs a `threadId`: a server turn is stored on a thread. Create one with the store's `createThread`.");let Q={...$.turn,...$.text!==void 0?{text:$.text}:{}},Z={...$.body,threadId:J,turn:Q},W=new x(new Request(WQ,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Z)}),{},"api",new URL(WQ).pathname),K=new this;P$.set(W,null);let X=await h.run(W,()=>K.stream(W),{user:$.user??null}),G=P$.get(W);if(!G)throw await r$.from(X);P$.delete(W),X.body?.cancel().catch(i$);let{run:V,hooks:Y}=G,H=[],D=(async()=>{for await(let F of V)if(F.type==="awaiting-input")H=F.pending})().catch(i$),z;return{runId:V.runId,threadId:J,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:J,text:O0(U),pending:F.finishReason==="awaiting-input"?H:[]}})()}}async stream($=new x){let J=await N$($,this.maxBodyBytes);if(J.error)return J$(J);let Q=J.body,Z=typeof Q.threadId==="string"?Q.threadId:void 0,W=w0(Q);if(W.error)return J$({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=n$(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 J8(413,"history_too_long",`The conversation has ${Q.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let Y=await this.runOwner($),H=G?{cancelled:!1,owner:Y}:null;if(H)l$.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 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 n=await this.settleThread(Z,E,{write:!0});if(N=n.messages,B=this.jobsBlock(n.jobs),X){let Q$=y0(N);if(!Q$)return M(409,{code:"nothing_to_regenerate",message:`Thread ${Z} has no user turn to answer again.`});z=N.slice(Q$.index),await this.store.removeMessages(Z,z.map((bQ)=>bQ.id)),N=N.slice(0,Q$.index),K=K?.localId?{...Q$.turn,localId:K.localId}:Q$.turn}}else N=Array.isArray(Q.messages)?Q.messages:[],d0(this.nonces);let P=[await this.instructions($,{body:V})||void 0,B??void 0].filter(Boolean).join(`
|
|
240
|
+
return 0`;class nJ{injectedClient;prefix;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:ai:receipt"}async claim($,J){let Q=await this.client.send("EVAL",[X0,"1",this.key($),p9,l9(J)]);if(Q==="claimed")return{status:"claimed"};let Z=String(Q??"");if(Z.startsWith(lJ))return{status:"replay",result:JSON.parse(Z.slice(lJ.length))};return{status:"blocked"}}async complete($,J,Q){await this.client.send("SET",[this.key($),lJ+JSON.stringify(J),"PX",l9(Q)])}async release($){await this.client.send("EVAL",[Y0,"1",this.key($),p9])}key($){return`${this.prefix}:${$}`}get client(){if(this.injectedClient)return this.injectedClient;let $=d9(),J=$.bound(dJ)?$.make(dJ).client:void 0;if(!J)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return J}}function l9($){return String(Math.max(1,Math.ceil($-Date.now())))}var G0=86400000,V0=60000;class m${ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor($={}){this.ttlMs=$.ttlMs??G0,this.clientOwnedIds=$.clientOwnedIds??!1}async createThread($){let J=crypto.randomUUID();return this.threads.set(J,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:J}}async loadThread($){this.sweep();let J=this.threads.get($);if(!J)return this.clientOwnedIds?[]:null;return J.touchedAt=Date.now(),J.messages.slice()}async appendMessages($,J){this.sweep();let Q=this.threads.get($);if(!Q){if(!this.clientOwnedIds)throw Error(`Thread ${$} does not exist here, or has expired.`);Q={messages:[],touchedAt:Date.now()},this.threads.set($,Q)}for(let Z of J){let W=JSON.parse(JSON.stringify(Z)),K=Q.messages.findIndex((X)=>X.id===W.id);if(K===-1)Q.messages.push(W);else Q.messages[K]=W}Q.touchedAt=Date.now()}async removeMessages($,J){this.sweep();let Q=this.threads.get($);if(!Q)return;let Z=new Set(J);Q.messages=Q.messages.filter((W)=>!Z.has(W.id)),Q.touchedAt=Date.now()}async loadSummaries($){return this.threads.get($)?.summaries?.slice()??[]}async saveSummary($,J){let Q=this.threads.get($);if(!Q)return;Q.summaries=F$(Q.summaries??[],J)}delete($){this.threads.delete($)}get size(){return this.threads.size}sweep($=Date.now()){if($-this.lastSweep<V0)return;this.lastSweep=$;for(let[J,Q]of this.threads)if($-Q.touchedAt>this.ttlMs)this.threads.delete(J)}}var oJ=new m$;function s9($={}){return{messages:$.messages?[...$.messages]:[],pending:$.pending?[...$.pending]:[],error:null,threadId:$.threadId,seq:$.seq??-1,cursorRunId:$.cursorRunId,runMessageIds:[],loadedTools:[]}}function a9($,J,Q=new Date().toISOString()){if(!(J.event.type==="run-start"&&J.event.runId!==$.cursorRunId)&&J.seq<=$.seq)return $;return{...t9($,J.event,Q),seq:J.seq}}function t9($,J,Q){switch(J.type){case"run-start":return{...$,messages:H0($.messages,J.runId),runId:J.runId,cursorRunId:J.runId,threadId:J.threadId??$.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return d($,J.messageId,Q,(Z)=>({...Z,role:J.role}));case"text-delta":if(n9($,J.messageId))return $;return d($,J.messageId,Q,(Z)=>({...Z,content:P0(Z.content,J.delta)}));case"reasoning-delta":if(n9($,J.messageId))return $;return d($,J.messageId,Q,(Z)=>({...Z,content:N0(Z.content,J.delta,J.id)}));case"output-delta":return d($,J.messageId,Q,(Z)=>({...Z,content:o9(Z.content,{type:"output",value:J.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return d($,J.messageId,Q,(Z)=>{let W=Z.content.findIndex((D)=>D.type==="tool-call"&&D.toolCallId===J.part.toolCallId),K=W===-1?void 0:Z.content[W],X=J.part.progress??K?.progress,G=J.part.nested??K?.nested,V=J.part.attachments??K?.attachments,Y={...J.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=J.loaded.filter((W)=>!$.loadedTools.includes(W));if(Z.length===0)return $;return{...$,loadedTools:[...$.loadedTools,...Z]}}case"tool-progress":return i9($,J.toolCallId,(Z)=>({...Z,progress:[...Z.progress??[],J.data]}));case"nested-event":{let Z=J;return i9($,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=F0(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=d($,J.messageId,Q,(W)=>({...W,content:o9(W.content,J.part,(K)=>K.type==="tool-result"&&K.toolCallId===J.part.toolCallId)}));return{...Z,pending:Z.pending.filter((W)=>W.toolCallId!==J.part.toolCallId)}}case"message":{let Z=$.messages.findIndex((X)=>X.id===J.message.id),W=$.messages.slice();if(Z===-1)W.push(J.message);else W[Z]=J.message;let K=$.runMessageIds.includes(J.message.id)?$.runMessageIds:[...$.runMessageIds,J.message.id];return{...$,messages:W,runMessageIds:K}}case"message-id":{let Z=$.messages.findIndex((G)=>G.id===J.localId);if(Z===-1){if(!J.message||$.messages.some((G)=>G.id===J.messageId))return $;return{...$,messages:[...$.messages,J.message]}}let W=$.messages[Z],K={localId:W.localId??W.id,...W.metadata?{metadata:W.metadata}:{}},X=$.messages.some((G)=>G.id===J.messageId)?$.messages.filter((G,V)=>V!==Z).map((G)=>G.id===J.messageId?{...G,...K}:G):$.messages.map((G,V)=>V===Z?{...G,...K,id:J.messageId}:G);return{...$,messages:X}}case"awaiting-input":return{...$,runId:J.runId,pending:[...J.pending]};case"message-end":return d($,J.messageId,Q,(Z)=>({...Z,finishReason:J.finishReason,...J.outputTruncated?{outputTruncated:!0}:{},...J.usage?{usage:J.usage}:{},content:J.outputTruncated||J.finishReason==="length"?Z.content.filter((W)=>!(W.type==="output"&&W.partial)):Z.content.map((W)=>W.type==="output"&&W.partial?{...W,partial:!1}:W)}));case"usage":return{...$,usage:J.usage};case"error":return{...$,error:J.error,pending:[]};case"run-end":return{...$,runId:void 0,finishReason:J.finishReason,messages:r9($,J.finishReason)};default:return $}}function H0($,J){if(!$.some((Q)=>Q.runId===J&&Q.finishReason===void 0))return $;return $.map((Q)=>{if(Q.runId!==J||Q.finishReason!==void 0)return Q;let{runId:Z,...W}=Q;return{...W,content:[]}})}function r9($,J){return $.messages.map((Q)=>Q.role==="assistant"&&$.runMessageIds.includes(Q.id)?z0(Q,J):Q)}function z0($,J){let Q=$.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?D0(K,J):K)}:W);if($.finishReason===void 0)return{...$,finishReason:J,content:Q};return Q.some((W,K)=>W!==$.content[K])?{...$,content:Q}:$}function D0($,J){let Q={messages:$.messages,pending:[],error:null,seq:-1,runMessageIds:$.messages.map((Z)=>Z.id),loadedTools:[]};return{...$,finishReason:J,messages:r9(Q,J)}}function i9($,J,Q){for(let Z=$.messages.length-1;Z>=0;Z--){let W=$.messages[Z],K=W.content.findIndex((Y)=>Y.type==="tool-call"&&Y.toolCallId===J);if(K===-1)continue;if(W.finishReason!==void 0&&!B0($,W,J))return $;let X=W.content.slice();X[K]=Q(X[K]);let G=$.messages.slice();G[Z]={...W,content:X};let V=$.runMessageIds.includes(W.id)?$.runMessageIds:[...$.runMessageIds,W.id];return{...$,runMessageIds:V,messages:G}}return $}function F0($,J,Q){let Z={messages:$.messages,pending:[],error:null,seq:-1,runMessageIds:$.messages.map((K)=>K.id),loadedTools:[],finishReason:$.finishReason},W=t9(Z,J.event,Q);return{...$,...J.label!==void 0?{label:J.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function B0($,J,Q){if(J.finishReason!=="awaiting-input")return!1;return!$.messages.some((Z)=>Z.content.some((W)=>W.type==="tool-result"&&W.toolCallId===Q))}function n9($,J){let Q=$.messages.find((Z)=>Z.id===J);return Q!==void 0&&Q.finishReason!==void 0}function d($,J,Q,Z){let W=$.messages.findIndex((G)=>G.id===J),K=$.runMessageIds.includes(J)?$.runMessageIds:[...$.runMessageIds,J];if(W===-1){let G={id:J,role:"assistant",content:[],createdAt:Q};return{...$,runMessageIds:K,messages:[...$.messages,Z(G)]}}let X=$.messages.slice();return X[W]=Z(X[W]),{...$,runMessageIds:K,messages:X}}function P0($,J){let Q=$[$.length-1];if(Q&&Q.type==="text")return[...$.slice(0,-1),{type:"text",text:Q.text+J}];return[...$,{type:"text",text:J}]}function N0($,J,Q){let Z=$[$.length-1];if(Z&&Z.type==="reasoning"&&Z.id===Q)return[...$.slice(0,-1),{...Z,text:(Z.text??"")+J}];return[...$,Q?{type:"reasoning",id:Q,text:J}:{type:"reasoning",text:J}]}function o9($,J,Q){let Z=$.findIndex(Q);if(Z===-1)return[...$,J];let W=$.slice();return W[Z]=J,W}class aJ{store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor($,J,Q,Z){this.store=$;this.threadId=J;this.report=Z;this.state=s9({messages:Q})}finish($){if(this.closed)return;this.done.add($.id),this.write(()=>[sJ($)])}frame($){if(this.closed)return;let J=$.event;if(J.type==="run-start")this.runId=J.runId;switch(this.state=a9(this.state,$),J.type){case"message":this.write(()=>[sJ(J.message)]);return;case"tool-call":if(J.part.partial)return;this.checkpoint(J.messageId);return;case"message-start":case"tool-result":this.checkpoint(J.messageId);return;default:return}}close($=[]){this.closed=!0;for(let J of $)this.done.add(J.id)}settled(){return this.chain}checkpoint($){if(this.done.has($))return;let J=this.state.messages.find((Z)=>Z.id===$);if(!J)return;let Q=this.runId;this.write(()=>{let Z=sJ(J);if(Z.finishReason===void 0&&Q)Z.runId=Q;return[Z]})}write($){let J;try{J=$()}catch(Q){this.report(Q);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,J)).catch((Q)=>this.report(Q))}}function sJ($){return structuredClone($)}async function e9($,J){let Q=[],Z=null,W=$.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 J(X.runId))continue;Z??=new Set($.flatMap((Y)=>Y.content.flatMap((H)=>H.type==="tool-result"?[H.toolCallId]:[])));let G=X.content.map((Y)=>Y.type==="tool-call"?$Q(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 $Q($){let{partial:J,...Q}=$;if(!Q.nested?.some((Z)=>Z.finishReason===void 0))return Q;return{...Q,nested:Q.nested.map(U0)}}function U0($){if($.finishReason!==void 0)return $;return{...$,finishReason:"interrupted",messages:$.messages.map((J)=>J.role==="assistant"&&J.finishReason===void 0?{...J,finishReason:"interrupted",content:J.content.map((Q)=>Q.type==="tool-call"?$Q(Q):Q)}:J)}}var L0=50,C0=["running","ok","error"];async function ZQ($,J){let{store:Q,threadId:Z}=J,W=Math.max(L0,J.scan??0),K=await Q.listForThread(Z,{limit:W}),X,G=async(F)=>{if(F.state!=="running")return F;if(X??=await JQ(Q),F.deadlineAt>X)return F;return await QQ(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=$.slice(),H=[],D=new Set;for(let F=0;F<Y.length;F++){let C=Y[F],N=null;for(let P=0;P<C.content.length;P++){let B=C.content[P];if(B.type==="tool-call")D.add(B.toolCallId);if(B.type!=="tool-result"||B.status!=="running")continue;let U=B.job?.id,L=U?V.get(U):void 0;if(U&&L===void 0){let O=await Q.get(U);if(L=O?await G(O):void 0,L)V.set(U,L)}if(L?.state==="running")continue;N??=C.content.slice(),N[P]=O0(B,L,J.outputSchemaFor,J.modelOutputFor)}if(N){let P={...C,content:N};Y[F]=P,H.push(P)}}let z=[];for(let F of K){if(F.orphaned||D.has(F.toolCallId))continue;if(await J.isRunLive(F.runId))continue;z.push(F)}return{messages:Y,settled:H,orphans:z,jobs:K}}async function WQ($,J,Q){for(let Z of J)try{await $.transition(Z.id,C0,{orphaned:!0})}catch(W){Q(W)}}function O0($,J,Q,Z){let W={type:"tool-result",toolCallId:$.toolCallId,name:$.name},K=(V,Y)=>{let H=Z?.(String($.name),V);return{...W,status:"ok",job:Y,output:V,...H!==void 0?{modelOutput:H}:{}}};if(!J)return{...W,status:"error",job:$.job,error:{code:"tool_error",message:`The background job for "${String($.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:$.toolCallId,retryable:!0}};let X={id:J.id,...J.summary!==void 0?{summary:J.summary}:{},...J.usage?{usage:J.usage}:{}};if(J.state==="error")return{...W,status:"error",job:X,error:J.error??{code:"tool_error",message:`The background job for "${String($.name)}" failed.`,toolCallId:$.toolCallId,retryable:!0}};let G=Q?.(String($.name));if(G){let V=G.safeParse(J.output);if(V.ok===!1)return{...W,status:"error",job:X,error:{code:"invalid_tool_result",message:`The background job for "${String($.name)}" finished with an output that does not match the tool's output schema: ${V.errors.join(", ")}`,toolCallId:$.toolCallId,retryable:!0}};return K(V.value,X)}return K(J.output,X)}class r$ extends Error{status;code;kind;constructor($,J){super($);this.name="AgentTurnError",this.status=J.status,this.code=J.code,this.kind=J.kind}static async from($){let J={};try{let Z=await $.json();if(Z?.error&&typeof Z.error==="object")J=Z.error}catch{}let Q=(Z)=>typeof J[Z]==="string"?J[Z]:void 0;return new r$(Q("message")??`The agent turn was refused with status ${$.status}.`,{status:$.status,code:Q("code"),kind:Q("kind")})}}function _0($){for(let J=$.length-1;J>=0;J--){let Q=$[J];if(Q.role!=="assistant")continue;return Q.content.map((Z)=>Z.type==="text"?Z.text:"").join("")}return""}var M0=PQ,p$=new Map,KQ=new WeakMap,P$=new WeakMap,XQ="http://gemi.internal/__gemi/agent-turn",l$=new Map,S0=4194304,A0=1000,R0=5,d$=65536,i$=()=>{};class qQ{byKey=new Map;take($,J,Q){let Z=this.byKey.get($);if(!Z?.has(J)&&(Z?.size??0)>=Q)return null;if(!Z)Z=new Map,this.byKey.set($,Z);Z.set(J,(Z.get(J)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let K=this.byKey.get($),X=(K?.get(J)??1)-1;if(!K)return;if(X>0)K.set(J,X);else if(K.delete(J),K.size===0)this.byKey.delete($)}}}var YQ=new WeakMap;function E0($){let J=YQ.get($);if(!J)J=new qQ,YQ.set($,J);return J}function T0($){return $}class X8 extends M0{static kind="agent-controller";hooks;store=oJ;liveRuns=mJ;voice;voiceStore=uJ;attachments=t$;attachmentStorage=LQ;fileOwners=pJ;nonces=Z8;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)}runTools($,J){return this.hooks?.runTools?.($,J)}usageLimits($,J){return this.hooks?.usageLimits?.($,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=S0;maxHistoryMessages=A0;contextWindow=void 0;prepareStep($,J){return this.hooks?.prepareStep?.($,J)}maxConcurrentRuns=R0;runLimitKey($,J){let Q=this.hooks?.runLimitKey;if(Q)return Q($,J);return J.owner}authorizeRequest($,J){let Q=this.hooks?.authorizeRequest;if(Q)return Q($,J);return this.resource?.authorize($,J)}resource;runOwner($){let J=this.hooks?.runOwner;if(J)return J($);let Q=$.ctx?.()?.user,Z=Q?.id??Q?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}static async startTurn($){let{threadId:J}=$;if(typeof J!=="string"||J==="")throw TypeError("AgentController.startTurn needs a `threadId`: a server turn is stored on a thread. Create one with the store's `createThread`.");let Q={...$.turn,...$.text!==void 0?{text:$.text}:{}},Z={...$.body,threadId:J,turn:Q},W=new q(new Request(XQ,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Z)}),{},"api",new URL(XQ).pathname),K=new this;P$.set(W,null);let X=await g.run(W,()=>K.stream(W),{user:$.user??null}),G=P$.get(W);if(!G)throw await r$.from(X);P$.delete(W),X.body?.cancel().catch(i$);let{run:V,hooks:Y}=G,H=[],D=(async()=>{for await(let F of V)if(F.type==="awaiting-input")H=F.pending})().catch(i$),z;return{runId:V.runId,threadId:J,run:V,stop:(F)=>V.stop(F),result:()=>z??=(async()=>{let F=await V.result();await Promise.all([Y,D]);let C=F.messages;return{...F,threadId:J,text:_0(C),pending:F.finishReason==="awaiting-input"?H:[]}})()}}async stream($=new q){let J=await N$($,this.maxBodyBytes);if(J.error)return J$(J);let Q=J.body,Z=typeof Q.threadId==="string"?Q.threadId:void 0,W=f0(Q);if(W.error)return J$({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=n$(Q);if(this.requireThread&&!Z)return S(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(X&&!this.store.removeMessages)return S(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 J8(413,"history_too_long",`The conversation has ${Q.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let Y=await this.runOwner($),H=G?{cancelled:!1,owner:Y}:null;if(H)l$.set(G,H);let D=null,z=[],F=async()=>{try{return await C()}finally{if(Z&&z.length>0&&D===null)await this.store.appendMessages(Z,z).catch((N)=>this.reportHookFailure(N))}},C=async()=>{let N,P=null;if(Z){let T=await this.store.loadThread(Z);if(!T)return S(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let n=await this.settleThread(Z,T,{write:!0});if(N=n.messages,P=this.jobsBlock(n.jobs),X){let Q$=g0(N);if(!Q$)return S(409,{code:"nothing_to_regenerate",message:`Thread ${Z} has no user turn to answer again.`});z=N.slice(Q$.index),await this.store.removeMessages(Z,z.map((vQ)=>vQ.id)),N=N.slice(0,Q$.index),K=K?.localId?{...Q$.turn,localId:K.localId}:Q$.turn}}else N=Array.isArray(Q.messages)?Q.messages:[],n0(this.nonces);let B=[await this.instructions($,{body:V})||void 0,P??void 0].filter(Boolean).join(`
|
|
241
241
|
|
|
242
|
-
`)||void 0,L=await this.context($,{body:V}),O=await this.reasoning($,{body:V})||void 0,j=await this.skills($,{body:V})||void 0,R=await this.runTools($,{body:V,context:L})||void 0,q=await this.usageLimits($,{body:V,context:L})||void 0,d=await this.attachmentsFor($,Z,{body:V}),i=this.agent.memory?await this.memoryScopes($,{body:V}):void 0;if(H?.cancelled)return HQ();let C=Z?new aJ(this.store,Z,N,(E)=>this.reportHookFailure(E)):null,k=`run_${crypto.randomUUID()}`,_={req:$,runId:k,threadId:Z},L$={id:null,notified:Promise.resolve()},f=this.agent.stream({runId:k,messages:N,turn:K,threadId:Z,...C?{onMessage:(E)=>C.finish(E)}:{},onTurn:(E)=>{if(L$.id!==null)return;L$.id=E.id;let n=C?C.settled():Promise.resolve();L$.notified=n.then(()=>this.safely(()=>this.onMessage(E,_)))},instructions:P,...O?{reasoning:O}:{},...j&&j.length>0?{skills:j}:{},...R?.tools&&R.tools.length>0?{tools:R.tools}:{},...R?.activeTools?{activeTools:R.activeTools}:{},...q?{usageLimits:q}:{},context:L,attachments:d,body:V,redactError:(E,n)=>this.redactError(E,n,_),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&&EQ(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==X8.prototype.prepareStep||this.hooks?.prepareStep?{prepareStep:(E)=>this.prepareStep(E,_)}:{}}),IQ=this.liveRuns.register(f,{threadId:Z,owner:Y,clientRunId:G,onEvent:(E)=>this.dispatchEvent(E,_),onInternalError:(E)=>this.reportHookFailure(E),maxRunDurationMs:this.agent.maxRunDurationMs});if(D=f,C)this.follow(f,C);let{stored:wQ,hooks:Y8}=this.persistRun(f,_,IQ,C,L$);if(ZQ.set(f,wQ),P$.has($))P$.set($,{run:f,hooks:Y8});return $.ctx?.()?.waitUntil(Y8),f.toResponse()};try{await this.authorizeRequest($,{route:"stream",threadId:Z,body:V});let N=await this.foreignFile([...K?.files??[],...Z?[]:g0(Q.messages)],Y);if(N)return N;if(H?.cancelled)return HQ();let B=await this.runLimitKey($,{owner:Y,threadId:Z}),P=B===null?i$:A0(this.liveRuns).take(B,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!P)return J8(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&&l$.get(G)===H)l$.delete(G)}}async withThread($,J,Q){let Z=p$.get($)??Promise.resolve(),W,K=new Promise((G)=>{W=G}),X=Z.then(()=>K);p$.set($,X),await Z;try{let G=await this.liveRuns.find({threadId:$});if(G&&this.liveRuns.isRunning(G.runId)&&!this.liveRuns.mayAccess(G.runId,J))return U$();let V=G?this.liveRuns.get(G.runId):null;if(V)V.stop({reason:"superseded by a later turn on this thread"}),await ZQ.get(V);return await Q()}finally{if(W(),p$.get($)===X)p$.delete($)}}async attach($=new x){let J=await N$($,d$);if(J.error)return J$(J);let Q=J.body,Z=typeof Q.threadId==="string"?Q.threadId:v0($,"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($,{route:"attach",threadId:Z});let W=await this.liveRuns.find({threadId:Z});if(W&&!this.liveRuns.mayAccess(W.runId,await this.runOwner($)))return U$();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:f0($,Q);try{return UQ(this.liveRuns.replay(W.runId,X))}catch(G){if(G instanceof $$)return M(410,{code:G.code,message:G.message,oldestSeq:G.oldest});if(G instanceof B$)return M(404,{code:G.code,message:G.message});throw G}}async stop($=new x){let J=await N$($,d$);if(J.error)return J$(J);let Q=J.body;await this.authorizeRequest($,{route:"stop",threadId:typeof Q.threadId==="string"?Q.threadId:void 0});let Z=await this.runOwner($),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=l$.get(Q.clientRunId);if(X){if(X.owner!==null&&X.owner!==Z)return U$();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 U$();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=$.ctx()?.user,K=W?.id??W?.publicId;if(K!==void 0&&K!==null&&String(K)!=="")return{key:`user:${String(K)}`};if(J)return{key:`thread:${J}`};return null}attachmentLimits($){let J=this.hooks?.attachmentLimits;if(J)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 a$(this.attachments,this.attachmentStorage,Z)}async voiceStart($=new x){let J=this.voice;if(!J)return tJ();let Q=await N$($,d$);if(Q.error)return J$(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=n$(Q.body,u0),G=typeof W==="string"&&W!==""?W:void 0;await this.authorizeRequest($,{route:"stream",threadId:G,body:X});let V=$.ctx?.()?.user??null,Y=await J.start({req:$,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 J.realtime.hangup(D).catch((O)=>{console.error("[gemi/ai] a voice call that failed to start could not be hung up.",O)});try{await 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($,{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 hJ(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:[...z$(J.delegate),...Y.session?.tools??[],...N.map((L)=>L.tool)],...K===!0?{turnDetection:null}:{}},P;try{P=await J.realtime.createCall({sdp:Z,session:B,safetyIdentifier:Y.safetyIdentifier})}catch(L){await z(L);let O=L instanceof b&&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($),body:X,startedAt:H});let{threadId:L,session:O,safetyIdentifier:j,mcp:R,tools:q,...d}=Y;return{sessionId:p.start({...d,tools:N,controller:this.constructor,threadId:F,user:V,body:X,call:{realtime:J.realtime,callId:P.callId},sessionId:U,store:this.voiceStore,liveRuns:this.liveRuns,delegate:J.delegate,session:B}).sessionId,sdp:P.sdpAnswer,threadId:F,delegate:J.delegate?.name??D$,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($=new x){if(!this.voice)return tJ();let J=await this.voiceSession($);if(J instanceof Response)return J;let Q=await N$($,d$);if(Q.error)return J$(Q);let Z=n$(Q.body,[]);if(await this.authorizeRequest($,{route:"stream",threadId:J.threadId,body:Z}),J.endedAt!==void 0)return M(409,{code:"voice_ended",message:"This voice session has ended."});return await this.voiceStore.update(J.id,{body:Z}),p.get(J.id)?.setBody(Z),{updated:!0}}async voiceEnd($=new x){let J=this.voice;if(!J)return tJ();let Q=await this.voiceSession($);if(Q instanceof Response)return Q;if(await this.authorizeRequest($,{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 J.realtime.hangup(Q.callId),await this.voiceStore.update(Q.id,{endedAt:Date.now(),endReason:"hangup"});return{ended:!0}}async voiceSession($){let J=$.params?.sessionId,Q=typeof J==="string"&&J?await this.voiceStore.get(J):null;if(!Q)return M(404,{code:"voice_not_found",message:"No such voice session."});if(Q.owner!==null&&Q.owner!==await this.runOwner($))return U$();return Q}async upload($=new x){let J=await $.rawRequest.formData(),Q=J.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=T0(J.get("body")),X=J.get("threadId");await this.authorizeRequest($,{route:"upload",threadId:typeof X==="string"&&X.length>0?X:void 0,body:K});let G=k0(await this.attachmentLimits($),Q,Z,W);if(G)throw new $8(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($),H=(R)=>this.fileOwners.record(R,{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},$,D);if(z)throw new $8(z.code||"upload_refused",z.message);let F=await this.attachmentDestination(Q,$,D),U=c0(F,J.get("destination")),N=await this.attachmentScope($,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()`.');m0()}if(U==="provider"||!N){let R=await XQ(this.agent.provider,Q);await H(R);let q={fileId:R,name:Z,mimeType:W,size:Q.size,destination:"provider"};if(B)q.downgraded="no_scope";return q}let P=SQ(),L=await this.attachmentStorage.put({name:AQ(P,Z),body:Q,contentType:W}),O=U==="both"?await XQ(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($.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!==J:this.requireKnownFiles)return h0()}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 W8($,J)}onError($,J){return this.hooks?.onError?.($,J)}onStreamComplete($,J){return this.hooks?.onStreamComplete?.($,J)}reportHookFailure($){let J=this.hooks?.reportHookFailure;if(J)try{return J($)}catch(Q){console.error("[gemi/ai] reportHookFailure hook failed",Q)}console.error("[gemi/ai] agent controller hook failed",$)}async dispatchEvent($,J){switch($.type){case"tool-call":if(!$.part.partial&&!$.resent)await this.onToolCall({toolCallId:$.part.toolCallId,name:String($.part.name),input:$.part.input},J);return;case"tool-result":{let Q=$.part;await this.onToolResult(Q,J,{toolCallId:Q.toolCallId,name:String(Q.name),input:jQ(Q)});return}case"awaiting-input":await this.onAwaitingInput($.pending,J);return;case"error":await this.onError(CQ($.error),J);return;default:return}}async readThread($){let J=await this.store.loadThread($);if(!J)return null;let{messages:Q}=await this.settleThread($,J,{write:!1});return Q}isRunLive($,J){return this.liveRuns.get($)!==null}async settleThread($,J,{write:Q}){let Z=(V)=>this.isRunLive(V,$),W=await t9(J,Z),K=W.messages,X=[],G=new Map(W.settled.map((V)=>[V.id,V]));if(i0(K)||Q)try{let V=await JQ(K,{threadId:$,store:v.store,isRunLive:Z,outputSchemaFor:(Y)=>this.toolNamed(Y)?.outputSchema,modelOutputFor:(Y,H)=>TQ(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 QQ(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($,[...G.values()])}catch(V){this.reportHookFailure(V)}return{messages:K,jobs:X}}jobsBlockMax(){let $=this.agent.jobs?.contextBlock;if($===!1)return 0;return $?.max??M$}jobsBlock($){return N8($,this.jobsBlockMax())}toolNamed($){let J=(Q)=>{for(let Z of Q){let W=Z;if(Array.isArray(W.tools)){let K=J(W.tools);if(K)return K}else if(W.name===$)return W}return};return J(this.agent.tools??[])}follow($,J){(async()=>{try{for await(let Q of $.frames())J.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 $.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},J)));return}let Y=V.messages;if(Z?.close(Y),await Z?.settled(),J.threadId&&Y.length>0)try{await this.store.appendMessages(J.threadId,Y)}catch(H){this.reportHookFailure(H)}K=this.notifyRun(V,Y,J,W)})(),G=X.then(()=>l0(Promise.all([K,Q]).then(()=>{}),this.hookHoldMs));return{stored:X,hooks:G}}async notifyRun($,J,Q,Z){await Z.notified;for(let W of J){if(W.id===Z.id)continue;await this.safely(()=>this.onMessage(W,Q))}await this.safely(()=>this.onStreamComplete($,Q))}async safely($){try{await $()}catch(J){this.reportHookFailure(J)}}}var rJ=["turn","clientRunId","threadId","messages","regenerate"],E0=["text","files","toolResults"];function n$($,J=qQ($)?rJ:[...rJ,...E0]){let Q={};for(let[Z,W]of Object.entries($)){if(J.includes(Z))continue;Object.defineProperty(Q,Z,{value:W,writable:!0,enumerable:!0,configurable:!0})}return Q}function T0($){if($===null)return{};let J;if(typeof $==="string")try{J=JSON.parse($)}catch{throw new eJ("The upload's `body` field is not valid JSON.")}if(J===null||typeof J!=="object"||Array.isArray(J))throw new eJ("The upload's `body` field must be a JSON object.");return n$(J,rJ)}class eJ extends o${constructor($){super($);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:$}}},view:{}}}}async function XQ($,J){try{return await $.upload(J)}catch(Q){if(Q instanceof I&&j0.has(Q.status))throw new xQ(T(Q).message);throw Q}}var j0=new Set([400,413,415,422]);class $8 extends o${constructor($,J){super(J);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:$,message:J}}},view:{}}}}function k0($,J,Q,Z){if(!$)return null;let{maxBytes:W,accept:K}=$;if(typeof W==="number"&&J.size>W)return{code:"file_too_large",message:`${JSON.stringify(Q)} is ${YQ(J.size)}; the limit is ${YQ(W)}.`};if(K&&K.length>0&&!K.some((X)=>x0(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 x0($,J,Q){let Z=$.trim().toLowerCase();if(!Z)return!1;if(Z.startsWith("."))return J.toLowerCase().endsWith(Z);let W=Q.toLowerCase().split(";")[0].trim();if(Z.endsWith("/*"))return W.startsWith(Z.slice(0,-1));return W===Z}function YQ($){if($<1024)return`${$} B`;let J=["KB","MB","GB"],Q=$/1024,Z=0;while(Q>=1024&&Z<J.length-1)Q/=1024,Z++;return`${Math.round(Q*10)/10} ${J[Z]}`}class xQ extends o${constructor($){super($);this.name="RejectedUploadError";let J=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test($)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:J,message:$}}},view:{}}}}async function N$($,J){let Q=$?.rawRequest;if(!Q||Q.method==="GET"||Q.method==="HEAD"||!Q.body)return{body:{}};if(!q0(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>J)return GQ(J);let W;try{let X=await I0(Q,J);if(X===null)return GQ(J);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 q0($){return PQ($)==="application/json"}async function I0($,J){if(!Number.isFinite(J)||!$.body)return await $.text();let Q=$.body.getReader(),Z=[],W=0;for(;;){let{done:G,value:V}=await Q.read();if(G)break;if(W+=V.byteLength,W>J)return await Q.cancel().catch(i$),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 GQ($){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${$} bytes).`}}function J8($,J,Q){return M($,{...s$(BQ($),Q,$),code:J})}function J$($){if($.status===413)return J8(413,$.code??"body_too_large",$.error??"");return M($.status??400,{code:$.code??"invalid_request",message:$.error})}function qQ($){return Boolean($.turn)&&typeof $.turn==="object"}function w0($){let J=qQ($)?$.turn:$,Q={};if(typeof J.text==="string")Q.text=J.text;if(Array.isArray(J.files)){let Z=b0(J.files);if(typeof Z==="string")return{error:Z};Q.files=Z}if(Array.isArray(J.toolResults))Q.toolResults=J.toolResults;if(Object.keys(Q).length===0)return{};if(J===$.turn&&J.localId!==void 0&&J.localId!==null&&J.localId!==""){let{localId:Z}=J;if(typeof Z!=="string")return{error:"turn.localId must be a string."};if(Z.length>VQ)return{error:`turn.localId is longer than ${VQ} characters.`};Q.localId=Z}return{turn:Q}}var VQ=200;function b0($){let J=[];for(let[Q,Z]of $.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.`;J.push({...X?{fileId:X}:{},...G?{attachmentId:G}:{},...V!==void 0?{name:V}:{},...Y!==void 0?{mimeType:Y}:{}})}return J}function f0($,J){if(typeof J.from==="number"&&Number.isFinite(J.from))return Math.max(0,Math.floor(J.from));if(typeof J.cursor==="number"&&Number.isFinite(J.cursor)){let Z=Math.floor(J.cursor);if(Z>=0)return Z+1;return}let Q=$?.rawRequest?.headers?.get("Last-Event-ID");if(Q){let Z=Number.parseInt(Q,10);if(Number.isFinite(Z))return Math.max(0,Z+1)}return}function v0($,J){let Q=$?.search?.get(J);return typeof Q==="string"?Q:void 0}function y0($){let J=K8($);for(let Q=$.length-1;Q>=0;Q--){let Z=$[Q];if(Z.role!=="user"||J.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 HQ(){return M(409,{code:"stopped",message:"The turn was stopped before it started."})}function U$(){return M(403,s$("permission","This run belongs to someone else.",403))}function h0(){return M(403,s$("permission","A file in this turn was uploaded by someone else.",403))}function g0($){if(!Array.isArray($))return[];let J=[];for(let Q of $){let Z=Q?.content;if(!Array.isArray(Z))continue;for(let W of Z)if(W&&typeof W==="object"&&typeof W.fileId==="string")J.push({fileId:W.fileId})}return J}var u0=["sdp","threadId","pushToTalk"];function tJ(){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:J}),{status:$,headers:{"Content-Type":"application/json"}})}function c0($,J){if(typeof J!=="string"||J.length===0)return $;if(J!=="both"&&J!=="provider"&&J!=="storage")throw Error(`Unknown attachment destination "${J}". Expected "both", "provider" or "storage".`);if(J===$||$==="both"&&J==="storage")return J;if($==="both"&&J==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${J}" destination, but the server's policy for it is "${$}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var zQ=!1;function m0(){if(zQ)return;zQ=!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 p0=2147483647;function l0($,J){let Q=$.then(()=>{},()=>{});if(!(J<=p0))return Q;let Z,W=new Promise((K)=>{Z=setTimeout(K,J)});return Promise.race([Q,W]).finally(()=>clearTimeout(Z))}var DQ=!1;function d0($){if(DQ||Bun.env.NODE_ENV!=="production")return;if(!($ instanceof Q8))return;DQ=!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 i0($){return $.some((J)=>J.content.some((Q)=>Q.type==="tool-result"&&Q.status==="running"))}export{Q6 as windowMessages,z$ as voiceTools,t0 as turnStarts,w$ as toRealtimeUsage,JZ as toAgentTools,s0 as supportsStrict,r0 as splitTurns,V6 as settleSummaries,o0 as s,W8 as redactError,L6 as parsePartialJson,e0 as messageSize,X$ as measureUsage,hJ as mcpVoiceTools,mJ as liveRuns,F$ as keepSummary,E9 as isCallNotFound,K8 as injectedMessageIds,FJ as generate,sZ as evalChain,R0 as defineAgentHooks,uJ as defaultVoiceStore,z6 as defaultUsageLimitStore,G6 as defaultSummaryStore,Z8 as defaultNonceStore,pJ as defaultFileOwners,t$ as defaultAttachmentStore,oJ as defaultAgentStore,g$ as VoiceHangup,p as VoiceBridge,a0 as Usage,PJ as ToolNamespace,g as ToolError,F6 as Skill,a$ as ScopedAttachments,B6 as SKILLS_NAMESPACE,nJ as RedisReceiptStore,LQ as RedisNonceStore,b$ as RealtimeSideband,b as RealtimeRequestError,V$ as RealtimeClient,F8 as Prompt,OQ as PrismaNonceStore,D6 as PendingEscalation,bJ as OpenAIProvider,CJ as OpenAIImageProvider,gJ as MemoryVoiceSessionStore,H6 as MemoryUsageLimitStore,Y6 as MemorySummaryStore,iJ as MemoryReceiptStore,Q8 as MemoryNonceStore,u$ as MemoryLiveRuns,c$ as MemoryFileOwners,y$ as MemoryCircuitStore,RQ as MemoryAttachmentStore,m$ as MemoryAgentStore,O8 as MemoryAgentJobStore,v8 as MEMORY_NAMESPACE,B$ as LiveRunNotFoundError,_8 as JobsRequireThreadError,C8 as JobHandle,n0 as JSONSchemaError,MQ as InvalidAttachmentScopeError,x8 as InMemoryAgentMemoryStore,x$ as ImageRequestError,q$ as ImageProvider,NJ as ImageModel,$$ as FrameCursorEvictedError,H$ as FallbackProvider,b8 as FakeAgentMemoryStore,T$ as Eval,u9 as DatabaseAgentStore,YJ as DatabaseAgentMemoryStore,KJ as DatabaseAgentJobStore,A9 as DEFAULT_TRANSCRIPTION_MODEL,k8 as DEFAULT_MEMORY_MAX_TOKENS,f8 as DEFAULT_MEMORY_LIMITS,Z6 as DEFAULT_MAX_SUMMARY_TOKENS,P6 as DEFAULT_MAX_RUN_DURATION_MS,M8 as DEFAULT_JOB_DEADLINE_MS,M$ as DEFAULT_JOBS_CONTEXT_MAX,D$ as DEFAULT_DELEGATE_NAME,$6 as DEFAULT_CONTEXT_WINDOW_STEP,J6 as DEFAULT_CONTEXT_WINDOW_NOTE,W6 as DEFAULT_COMPACT_TRIGGER_TOKENS,K6 as DEFAULT_COMPACT_INSTRUCTIONS,X6 as COMPACT_SUMMARY_HEADER,fJ as AzureOpenAIProvider,_J as AzureOpenAIImageProvider,_Q as AttachmentNotFoundError,r$ as AgentTurnError,j$ as AgentTool,N6 as AgentRunError,e as AgentProvider,q8 as AgentMemoryRefusedError,I8 as AgentMemoryConflictError,w8 as AgentMemories,v as AgentJobs,QJ as AgentJobDeadlineSweep,S8 as AgentJob,X8 as AgentController,U6 as Agent};
|
|
242
|
+
`)||void 0,U=await this.context($,{body:V}),L=await this.reasoning($,{body:V})||void 0,O=await this.skills($,{body:V})||void 0,A=await this.runTools($,{body:V,context:U})||void 0,x=await this.usageLimits($,{body:V,context:U})||void 0,I=await this.attachmentsFor($,Z,{body:V}),i=this.agent.memory?await this.memoryScopes($,{body:V}):void 0;if(H?.cancelled)return DQ();let _=Z?new aJ(this.store,Z,N,(T)=>this.reportHookFailure(T)):null,k=`run_${crypto.randomUUID()}`,M={req:$,runId:k,threadId:Z},L$={id:null,notified:Promise.resolve()},v=this.agent.stream({runId:k,messages:N,turn:K,threadId:Z,..._?{onMessage:(T)=>_.finish(T)}:{},onTurn:(T)=>{if(L$.id!==null)return;L$.id=T.id;let n=_?_.settled():Promise.resolve();L$.notified=n.then(()=>this.safely(()=>this.onMessage(T,M)))},instructions:B,...L?{reasoning:L}:{},...O&&O.length>0?{skills:O}:{},...A?.tools&&A.tools.length>0?{tools:A.tools}:{},...A?.activeTools?{activeTools:A.activeTools}:{},...x?{usageLimits:x}:{},context:U,attachments:I,body:V,redactError:(T,n)=>this.redactError(T,n,M),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&&jQ(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==X8.prototype.prepareStep||this.hooks?.prepareStep?{prepareStep:(T)=>this.prepareStep(T,M)}:{}}),bQ=this.liveRuns.register(v,{threadId:Z,owner:Y,clientRunId:G,onEvent:(T)=>this.dispatchEvent(T,M),onInternalError:(T)=>this.reportHookFailure(T),maxRunDurationMs:this.agent.maxRunDurationMs});if(D=v,_)this.follow(v,_);let{stored:fQ,hooks:Y8}=this.persistRun(v,M,bQ,_,L$);if(KQ.set(v,fQ),P$.has($))P$.set($,{run:v,hooks:Y8});return $.ctx?.()?.waitUntil(Y8),v.toResponse()};try{await this.authorizeRequest($,{route:"stream",threadId:Z,body:V});let N=await this.foreignFile([...K?.files??[],...Z?[]:c0(Q.messages)],Y);if(N)return N;if(H?.cancelled)return DQ();let P=await this.runLimitKey($,{owner:Y,threadId:Z}),B=P===null?i$:E0(this.liveRuns).take(P,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!B)return J8(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 U=D;if(U)U.result().then(B,B);else B()}}finally{if(H&&l$.get(G)===H)l$.delete(G)}}async withThread($,J,Q){let Z=p$.get($)??Promise.resolve(),W,K=new Promise((G)=>{W=G}),X=Z.then(()=>K);p$.set($,X),await Z;try{let G=await this.liveRuns.find({threadId:$});if(G&&this.liveRuns.isRunning(G.runId)&&!this.liveRuns.mayAccess(G.runId,J))return U$();let V=G?this.liveRuns.get(G.runId):null;if(V)V.stop({reason:"superseded by a later turn on this thread"}),await KQ.get(V);return await Q()}finally{if(W(),p$.get($)===X)p$.delete($)}}async attach($=new q){let J=await N$($,d$);if(J.error)return J$(J);let Q=J.body,Z=typeof Q.threadId==="string"?Q.threadId:h0($,"threadId");if(!Z)return S(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest($,{route:"attach",threadId:Z});let W=await this.liveRuns.find({threadId:Z});if(W&&!this.liveRuns.mayAccess(W.runId,await this.runOwner($)))return U$();if(!W)return S(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:y0($,Q);try{return CQ(this.liveRuns.replay(W.runId,X))}catch(G){if(G instanceof $$)return S(410,{code:G.code,message:G.message,oldestSeq:G.oldest});if(G instanceof B$)return S(404,{code:G.code,message:G.message});throw G}}async stop($=new q){let J=await N$($,d$);if(J.error)return J$(J);let Q=J.body;await this.authorizeRequest($,{route:"stop",threadId:typeof Q.threadId==="string"?Q.threadId:void 0});let Z=await this.runOwner($),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=l$.get(Q.clientRunId);if(X){if(X.owner!==null&&X.owner!==Z)return U$();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 U$();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=$.ctx()?.user,K=W?.id??W?.publicId;if(K!==void 0&&K!==null&&String(K)!=="")return{key:`user:${String(K)}`};if(J)return{key:`thread:${J}`};return null}attachmentLimits($){let J=this.hooks?.attachmentLimits;if(J)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 a$(this.attachments,this.attachmentStorage,Z)}async voiceStart($=new q){let J=this.voice;if(!J)return tJ();let Q=await N$($,d$);if(Q.error)return J$(Q);let{sdp:Z,threadId:W,pushToTalk:K}=Q.body;if(typeof Z!=="string"||!Z.trimStart().startsWith("v="))return S(400,{code:"invalid_request",message:"`sdp` must be the browser's SDP offer."});let X=n$(Q.body,m0),G=typeof W==="string"&&W!==""?W:void 0;await this.authorizeRequest($,{route:"stream",threadId:G,body:X});let V=$.ctx?.()?.user??null,Y=await J.start({req:$,body:X,threadId:G,user:V,pushToTalk:K===!0}),H=Date.now(),D,z=async(U)=>{if(U!==void 0)console.error("[gemi/ai] a voice session could not start.",U);if(D)await J.realtime.hangup(D).catch((L)=>{console.error("[gemi/ai] a voice call that failed to start could not be hung up.",L)});try{await Y.onEnd?.({sessionId:"",...D?{callId:D}:{},threadId:Y.threadId??G??"",reason:"start_failed",startedAt:H,endedAt:Date.now(),durationMs:0,seconds:0,usage:R(),transcription:{usage:R(),seconds:0},transcript:[],requests:[],toolCalls:[],errors:[]})}catch(L){console.error("[gemi/ai] a voice session's onEnd threw.",L)}},F=Y.threadId??G;if(!F)return await z(void 0),S(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($,{route:"stream",threadId:F,body:X})}catch(U){throw await z(void 0),U}let C=crypto.randomUUID(),N=Y.tools??[];try{if(Y.mcp)N=[...N,...await hJ(Y.mcp,{user:V,sessionId:C})]}catch(U){return await z(U),S(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}let P={...Y.session,tools:[...z$(J.delegate),...Y.session?.tools??[],...N.map((U)=>U.tool)],...K===!0?{turnDetection:null}:{}},B;try{B=await J.realtime.createCall({sdp:Z,session:P,safetyIdentifier:Y.safetyIdentifier})}catch(U){await z(U);let L=U instanceof f&&U.code==="rate_limited";return S(L?429:502,{code:"voice_unavailable",message:"Voice isn't available right now."})}D=B.callId;try{await this.voiceStore.create({id:C,callId:B.callId,threadId:F,owner:await this.runOwner($),body:X,startedAt:H});let{threadId:U,session:L,safetyIdentifier:O,mcp:A,tools:x,...I}=Y;return{sessionId:l.start({...I,tools:N,controller:this.constructor,threadId:F,user:V,body:X,call:{realtime:J.realtime,callId:B.callId},sessionId:C,store:this.voiceStore,liveRuns:this.liveRuns,delegate:J.delegate,session:P}).sessionId,sdp:B.sdpAnswer,threadId:F,delegate:J.delegate?.name??D$,endsAt:H+(Y.limits?.maxDurationMs??900000)}}catch(U){return await z(U),S(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}}async voiceUpdate($=new q){if(!this.voice)return tJ();let J=await this.voiceSession($);if(J instanceof Response)return J;let Q=await N$($,d$);if(Q.error)return J$(Q);let Z=n$(Q.body,[]);if(await this.authorizeRequest($,{route:"stream",threadId:J.threadId,body:Z}),J.endedAt!==void 0)return S(409,{code:"voice_ended",message:"This voice session has ended."});return await this.voiceStore.update(J.id,{body:Z}),l.get(J.id)?.setBody(Z),{updated:!0}}async voiceEnd($=new q){let J=this.voice;if(!J)return tJ();let Q=await this.voiceSession($);if(Q instanceof Response)return Q;if(await this.authorizeRequest($,{route:"stream",threadId:Q.threadId,body:Q.body}),Q.endedAt!==void 0)return{ended:!1};let Z=l.get(Q.id);if(Z)await Z.end("hangup");else await J.realtime.hangup(Q.callId),await this.voiceStore.update(Q.id,{endedAt:Date.now(),endReason:"hangup"});return{ended:!0}}async voiceSession($){let J=$.params?.sessionId,Q=typeof J==="string"&&J?await this.voiceStore.get(J):null;if(!Q)return S(404,{code:"voice_not_found",message:"No such voice session."});if(Q.owner!==null&&Q.owner!==await this.runOwner($))return U$();return Q}async upload($=new q){let J=await $.rawRequest.formData(),Q=J.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=k0(J.get("body")),X=J.get("threadId");await this.authorizeRequest($,{route:"upload",threadId:typeof X==="string"&&X.length>0?X:void 0,body:K});let G=q0(await this.attachmentLimits($),Q,Z,W);if(G)throw new $8(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($),H=(A)=>this.fileOwners.record(A,{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},$,D);if(z)throw new $8(z.code||"upload_refused",z.message);let F=await this.attachmentDestination(Q,$,D),C=p0(F,J.get("destination")),N=await this.attachmentScope($,V,{body:K}),P=C!=="provider"&&!N;if(P){if(C==="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()`.');l0()}if(C==="provider"||!N){let A=await GQ(this.agent.provider,Q);await H(A);let x={fileId:A,name:Z,mimeType:W,size:Q.size,destination:"provider"};if(P)x.downgraded="no_scope";return x}let B=RQ(),U=await this.attachmentStorage.put({name:EQ(B,Z),body:Q,contentType:W}),L=C==="both"?await GQ(this.agent.provider,Q):void 0;if(L)await H(L);let O={id:B,scopeKey:N.key,fileId:L,objectName:U,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString(),destination:C};return await this.attachments.put(N,O),{fileId:L,attachmentId:B,name:Z,mimeType:W,size:Q.size,destination:C}}async foreignFile($,J){let Q=new Set($.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!==J:this.requireKnownFiles)return u0()}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 W8($,J)}onError($,J){return this.hooks?.onError?.($,J)}onStreamComplete($,J){return this.hooks?.onStreamComplete?.($,J)}reportHookFailure($){let J=this.hooks?.reportHookFailure;if(J)try{return J($)}catch(Q){console.error("[gemi/ai] reportHookFailure hook failed",Q)}console.error("[gemi/ai] agent controller hook failed",$)}async dispatchEvent($,J){switch($.type){case"tool-call":if(!$.part.partial&&!$.resent)await this.onToolCall({toolCallId:$.part.toolCallId,name:String($.part.name),input:$.part.input},J);return;case"tool-result":{let Q=$.part;await this.onToolResult(Q,J,{toolCallId:Q.toolCallId,name:String(Q.name),input:xQ(Q)});return}case"awaiting-input":await this.onAwaitingInput($.pending,J);return;case"error":await this.onError(MQ($.error),J);return;default:return}}async readThread($){let J=await this.store.loadThread($);if(!J)return null;let{messages:Q}=await this.settleThread($,J,{write:!1});return Q}isRunLive($,J){return this.liveRuns.get($)!==null}async settleThread($,J,{write:Q}){let Z=(V)=>this.isRunLive(V,$),W=await e9(J,Z),K=W.messages,X=[],G=new Map(W.settled.map((V)=>[V.id,V]));if(o0(K)||Q)try{let V=await ZQ(K,{threadId:$,store:y.store,isRunLive:Z,outputSchemaFor:(Y)=>this.toolNamed(Y)?.outputSchema,modelOutputFor:(Y,H)=>kQ(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 WQ(y.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($,[...G.values()])}catch(V){this.reportHookFailure(V)}return{messages:K,jobs:X}}jobsBlockMax(){let $=this.agent.jobs?.contextBlock;if($===!1)return 0;return $?.max??M$}jobsBlock($){return N8($,this.jobsBlockMax())}toolNamed($){let J=(Q)=>{for(let Z of Q){let W=Z;if(Array.isArray(W.tools)){let K=J(W.tools);if(K)return K}else if(W.name===$)return W}return};return J(this.agent.tools??[])}follow($,J){(async()=>{try{for await(let Q of $.frames())J.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 $.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},J)));return}let Y=V.messages;if(Z?.close(Y),await Z?.settled(),J.threadId&&Y.length>0)try{await this.store.appendMessages(J.threadId,Y)}catch(H){this.reportHookFailure(H)}K=this.notifyRun(V,Y,J,W)})(),G=X.then(()=>i0(Promise.all([K,Q]).then(()=>{}),this.hookHoldMs));return{stored:X,hooks:G}}async notifyRun($,J,Q,Z){await Z.notified;for(let W of J){if(W.id===Z.id)continue;await this.safely(()=>this.onMessage(W,Q))}await this.safely(()=>this.onStreamComplete($,Q))}async safely($){try{await $()}catch(J){this.reportHookFailure(J)}}}var rJ=["turn","clientRunId","threadId","messages","regenerate"],j0=["text","files","toolResults"];function n$($,J=wQ($)?rJ:[...rJ,...j0]){let Q={};for(let[Z,W]of Object.entries($)){if(J.includes(Z))continue;Object.defineProperty(Q,Z,{value:W,writable:!0,enumerable:!0,configurable:!0})}return Q}function k0($){if($===null)return{};let J;if(typeof $==="string")try{J=JSON.parse($)}catch{throw new eJ("The upload's `body` field is not valid JSON.")}if(J===null||typeof J!=="object"||Array.isArray(J))throw new eJ("The upload's `body` field must be a JSON object.");return n$(J,rJ)}class eJ extends o${constructor($){super($);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:$}}},view:{}}}}async function GQ($,J){try{return await $.upload(J)}catch(Q){if(Q instanceof w&&x0.has(Q.status))throw new IQ(j(Q).message);throw Q}}var x0=new Set([400,413,415,422]);class $8 extends o${constructor($,J){super(J);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:$,message:J}}},view:{}}}}function q0($,J,Q,Z){if(!$)return null;let{maxBytes:W,accept:K}=$;if(typeof W==="number"&&J.size>W)return{code:"file_too_large",message:`${JSON.stringify(Q)} is ${VQ(J.size)}; the limit is ${VQ(W)}.`};if(K&&K.length>0&&!K.some((X)=>I0(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 I0($,J,Q){let Z=$.trim().toLowerCase();if(!Z)return!1;if(Z.startsWith("."))return J.toLowerCase().endsWith(Z);let W=Q.toLowerCase().split(";")[0].trim();if(Z.endsWith("/*"))return W.startsWith(Z.slice(0,-1));return W===Z}function VQ($){if($<1024)return`${$} B`;let J=["KB","MB","GB"],Q=$/1024,Z=0;while(Q>=1024&&Z<J.length-1)Q/=1024,Z++;return`${Math.round(Q*10)/10} ${J[Z]}`}class IQ extends o${constructor($){super($);this.name="RejectedUploadError";let J=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test($)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:J,message:$}}},view:{}}}}async function N$($,J){let Q=$?.rawRequest;if(!Q||Q.method==="GET"||Q.method==="HEAD"||!Q.body)return{body:{}};if(!w0(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>J)return HQ(J);let W;try{let X=await b0(Q,J);if(X===null)return HQ(J);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 w0($){return UQ($)==="application/json"}async function b0($,J){if(!Number.isFinite(J)||!$.body)return await $.text();let Q=$.body.getReader(),Z=[],W=0;for(;;){let{done:G,value:V}=await Q.read();if(G)break;if(W+=V.byteLength,W>J)return await Q.cancel().catch(i$),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 HQ($){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${$} bytes).`}}function J8($,J,Q){return S($,{...s$(NQ($),Q,$),code:J})}function J$($){if($.status===413)return J8(413,$.code??"body_too_large",$.error??"");return S($.status??400,{code:$.code??"invalid_request",message:$.error})}function wQ($){return Boolean($.turn)&&typeof $.turn==="object"}function f0($){let J=wQ($)?$.turn:$,Q={};if(typeof J.text==="string")Q.text=J.text;if(Array.isArray(J.files)){let Z=v0(J.files);if(typeof Z==="string")return{error:Z};Q.files=Z}if(Array.isArray(J.toolResults))Q.toolResults=J.toolResults;if(Object.keys(Q).length===0)return{};if(J===$.turn&&J.localId!==void 0&&J.localId!==null&&J.localId!==""){let{localId:Z}=J;if(typeof Z!=="string")return{error:"turn.localId must be a string."};if(Z.length>zQ)return{error:`turn.localId is longer than ${zQ} characters.`};Q.localId=Z}return{turn:Q}}var zQ=200;function v0($){let J=[];for(let[Q,Z]of $.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(p))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(p))return`${W}.attachmentId is not a gemi attachment id: it must start with "${p}".`;if(!X&&!G)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;J.push({...X?{fileId:X}:{},...G?{attachmentId:G}:{},...V!==void 0?{name:V}:{},...Y!==void 0?{mimeType:Y}:{}})}return J}function y0($,J){if(typeof J.from==="number"&&Number.isFinite(J.from))return Math.max(0,Math.floor(J.from));if(typeof J.cursor==="number"&&Number.isFinite(J.cursor)){let Z=Math.floor(J.cursor);if(Z>=0)return Z+1;return}let Q=$?.rawRequest?.headers?.get("Last-Event-ID");if(Q){let Z=Number.parseInt(Q,10);if(Number.isFinite(Z))return Math.max(0,Z+1)}return}function h0($,J){let Q=$?.search?.get(J);return typeof Q==="string"?Q:void 0}function g0($){let J=K8($);for(let Q=$.length-1;Q>=0;Q--){let Z=$[Q];if(Z.role!=="user"||J.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 DQ(){return S(409,{code:"stopped",message:"The turn was stopped before it started."})}function U$(){return S(403,s$("permission","This run belongs to someone else.",403))}function u0(){return S(403,s$("permission","A file in this turn was uploaded by someone else.",403))}function c0($){if(!Array.isArray($))return[];let J=[];for(let Q of $){let Z=Q?.content;if(!Array.isArray(Z))continue;for(let W of Z)if(W&&typeof W==="object"&&typeof W.fileId==="string")J.push({fileId:W.fileId})}return J}var m0=["sdp","threadId","pushToTalk"];function tJ(){return S(404,{code:"voice_not_enabled",message:"This agent has no voice: set `voice` on its controller."})}function S($,J){return new Response(JSON.stringify({error:J}),{status:$,headers:{"Content-Type":"application/json"}})}function p0($,J){if(typeof J!=="string"||J.length===0)return $;if(J!=="both"&&J!=="provider"&&J!=="storage")throw Error(`Unknown attachment destination "${J}". Expected "both", "provider" or "storage".`);if(J===$||$==="both"&&J==="storage")return J;if($==="both"&&J==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${J}" destination, but the server's policy for it is "${$}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var FQ=!1;function l0(){if(FQ)return;FQ=!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 d0=2147483647;function i0($,J){let Q=$.then(()=>{},()=>{});if(!(J<=d0))return Q;let Z,W=new Promise((K)=>{Z=setTimeout(K,J)});return Promise.race([Q,W]).finally(()=>clearTimeout(Z))}var BQ=!1;function n0($){if(BQ||Bun.env.NODE_ENV!=="production")return;if(!($ instanceof Q8))return;BQ=!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 o0($){return $.some((J)=>J.content.some((Q)=>Q.type==="tool-result"&&Q.status==="running"))}export{W6 as windowMessages,z$ as voiceTools,e0 as turnStarts,w$ as toRealtimeUsage,ZZ as toAgentTools,t0 as supportsStrict,$6 as splitTurns,z6 as settleSummaries,a0 as s,W8 as redactError,O6 as parsePartialJson,J6 as messageSize,X$ as measureUsage,hJ as mcpVoiceTools,mJ as liveRuns,F$ as keepSummary,j9 as isCallNotFound,K8 as injectedMessageIds,FJ as generate,tZ as evalChain,T0 as defineAgentHooks,uJ as defaultVoiceStore,F6 as defaultUsageLimitStore,H6 as defaultSummaryStore,Z8 as defaultNonceStore,pJ as defaultFileOwners,t$ as defaultAttachmentStore,oJ as defaultAgentStore,g$ as VoiceHangup,l as VoiceBridge,r0 as Usage,PJ as ToolNamespace,u as ToolError,P6 as Skill,a$ as ScopedAttachments,N6 as SKILLS_NAMESPACE,nJ as RedisReceiptStore,OQ as RedisNonceStore,b$ as RealtimeSideband,f as RealtimeRequestError,V$ as RealtimeClient,F8 as Prompt,_Q as PrismaNonceStore,B6 as PendingEscalation,bJ as OpenAIProvider,OJ as OpenAIImageProvider,gJ as MemoryVoiceSessionStore,D6 as MemoryUsageLimitStore,V6 as MemorySummaryStore,iJ as MemoryReceiptStore,Q8 as MemoryNonceStore,u$ as MemoryLiveRuns,c$ as MemoryFileOwners,y$ as MemoryCircuitStore,TQ as MemoryAttachmentStore,m$ as MemoryAgentStore,C8 as MemoryAgentJobStore,v8 as MEMORY_NAMESPACE,B$ as LiveRunNotFoundError,_8 as JobsRequireThreadError,O8 as JobHandle,s0 as JSONSchemaError,AQ as InvalidAttachmentScopeError,x8 as InMemoryAgentMemoryStore,x$ as ImageRequestError,q$ as ImageProvider,NJ as ImageModel,$$ as FrameCursorEvictedError,H$ as FallbackProvider,b8 as FakeAgentMemoryStore,T$ as Eval,m9 as DatabaseAgentStore,YJ as DatabaseAgentMemoryStore,KJ as DatabaseAgentJobStore,E9 as DEFAULT_TRANSCRIPTION_MODEL,k8 as DEFAULT_MEMORY_MAX_TOKENS,f8 as DEFAULT_MEMORY_LIMITS,K6 as DEFAULT_MAX_SUMMARY_TOKENS,U6 as DEFAULT_MAX_RUN_DURATION_MS,M8 as DEFAULT_JOB_DEADLINE_MS,M$ as DEFAULT_JOBS_CONTEXT_MAX,D$ as DEFAULT_DELEGATE_NAME,Q6 as DEFAULT_CONTEXT_WINDOW_STEP,Z6 as DEFAULT_CONTEXT_WINDOW_NOTE,X6 as DEFAULT_COMPACT_TRIGGER_TOKENS,Y6 as DEFAULT_COMPACT_INSTRUCTIONS,G6 as COMPACT_SUMMARY_HEADER,fJ as AzureOpenAIProvider,_J as AzureOpenAIImageProvider,SQ as AttachmentNotFoundError,r$ as AgentTurnError,j$ as AgentTool,L6 as AgentRunError,e as AgentProvider,q8 as AgentMemoryRefusedError,I8 as AgentMemoryConflictError,w8 as AgentMemories,y as AgentJobs,QJ as AgentJobDeadlineSweep,S8 as AgentJob,X8 as AgentController,C6 as Agent};
|
|
243
243
|
|
|
244
|
-
//# debugId=
|
|
244
|
+
//# debugId=9F79A5267F27EAFB64756E2164756E21
|