gemi 0.225.1 → 0.226.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/Agent.d.ts +48 -1
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/AgentController.d.ts +160 -17
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/client/index.d.ts +1 -1
- package/dist/ai/client/index.d.ts.map +1 -1
- package/dist/ai/client/index.js +235 -58
- package/dist/ai/client/index.js.map +1 -1
- package/dist/ai/client/reducer.d.ts +46 -0
- package/dist/ai/client/reducer.d.ts.map +1 -1
- package/dist/ai/contextWindow.d.ts +9 -2
- package/dist/ai/contextWindow.d.ts.map +1 -1
- package/dist/ai/index.d.ts +3 -2
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +80 -70
- package/dist/ai/index.js.map +7 -6
- package/dist/ai/store/LiveRuns.d.ts +21 -0
- package/dist/ai/store/LiveRuns.d.ts.map +1 -1
- package/dist/ai/store/index.d.ts +1 -1
- package/dist/ai/store/index.d.ts.map +1 -1
- package/dist/ai/testing/index.js +2 -2
- package/dist/ai/testing/index.js.map +1 -1
- package/dist/ai/types.d.ts +14 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/useChat.d.ts +30 -0
- package/dist/ai/useChat.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-enqrjcdk.js → chunk-07rrezpq.js} +2 -2
- package/dist/{chunk-enqrjcdk.js.map → chunk-07rrezpq.js.map} +1 -1
- package/dist/{chunk-zy56kaws.js → chunk-0anqpm98.js} +2 -2
- package/dist/{chunk-zy56kaws.js.map → chunk-0anqpm98.js.map} +1 -1
- package/dist/{chunk-v5sg62xm.js → chunk-1p82h0y2.js} +2 -2
- package/dist/{chunk-v5sg62xm.js.map → chunk-1p82h0y2.js.map} +1 -1
- package/dist/{chunk-5kgqfczk.js → chunk-26ngc9ed.js} +3 -3
- package/dist/{chunk-5kgqfczk.js.map → chunk-26ngc9ed.js.map} +1 -1
- package/dist/{chunk-me70vszk.js → chunk-2jx1r4m7.js} +2 -2
- package/dist/{chunk-me70vszk.js.map → chunk-2jx1r4m7.js.map} +1 -1
- package/dist/{chunk-t5aft2ra.js → chunk-2xzf4nqq.js} +4 -4
- package/dist/{chunk-t5aft2ra.js.map → chunk-2xzf4nqq.js.map} +1 -1
- package/dist/{chunk-j0rhz378.js → chunk-42mm1g89.js} +2 -2
- package/dist/{chunk-j0rhz378.js.map → chunk-42mm1g89.js.map} +1 -1
- package/dist/{chunk-k657v3ed.js → chunk-4m7srgh5.js} +3 -3
- package/dist/{chunk-k657v3ed.js.map → chunk-4m7srgh5.js.map} +1 -1
- package/dist/{chunk-ng6pbd7f.js → chunk-53hg89g5.js} +4 -4
- package/dist/{chunk-ng6pbd7f.js.map → chunk-53hg89g5.js.map} +1 -1
- package/dist/{chunk-tp1gxcke.js → chunk-58gyj15y.js} +3 -3
- package/dist/{chunk-tp1gxcke.js.map → chunk-58gyj15y.js.map} +1 -1
- package/dist/{chunk-zvg2qsa5.js → chunk-5tf6nm65.js} +2 -2
- package/dist/{chunk-zvg2qsa5.js.map → chunk-5tf6nm65.js.map} +1 -1
- package/dist/{chunk-m7v4erdg.js → chunk-5yxyd1vb.js} +2 -2
- package/dist/{chunk-m7v4erdg.js.map → chunk-5yxyd1vb.js.map} +1 -1
- package/dist/{chunk-6h1hjzj7.js → chunk-5zbqh32n.js} +2 -2
- package/dist/{chunk-6h1hjzj7.js.map → chunk-5zbqh32n.js.map} +1 -1
- package/dist/{chunk-444g812v.js → chunk-603twf6k.js} +2 -2
- package/dist/{chunk-444g812v.js.map → chunk-603twf6k.js.map} +1 -1
- package/dist/{chunk-qtz4g4kv.js → chunk-6e12tbqc.js} +3 -3
- package/dist/{chunk-qtz4g4kv.js.map → chunk-6e12tbqc.js.map} +1 -1
- package/dist/{chunk-81y96dax.js → chunk-6n3wadx7.js} +1 -1
- package/dist/{chunk-ryh6rfts.js → chunk-72k87qz8.js} +2 -2
- package/dist/{chunk-ryh6rfts.js.map → chunk-72k87qz8.js.map} +1 -1
- package/dist/{chunk-7mvfk0q9.js → chunk-77pms0y3.js} +2 -2
- package/dist/{chunk-7mvfk0q9.js.map → chunk-77pms0y3.js.map} +1 -1
- package/dist/{chunk-mvb8m247.js → chunk-7g3r55sj.js} +2 -2
- package/dist/{chunk-mvb8m247.js.map → chunk-7g3r55sj.js.map} +1 -1
- package/dist/{chunk-we65r9fh.js → chunk-8s8bjrjp.js} +3 -3
- package/dist/{chunk-we65r9fh.js.map → chunk-8s8bjrjp.js.map} +1 -1
- package/dist/{chunk-1jyzg1ex.js → chunk-8xta8133.js} +3 -3
- package/dist/{chunk-1jyzg1ex.js.map → chunk-8xta8133.js.map} +1 -1
- package/dist/{chunk-v0fqq5z7.js → chunk-9kcjxtqg.js} +2 -2
- package/dist/{chunk-v0fqq5z7.js.map → chunk-9kcjxtqg.js.map} +1 -1
- package/dist/chunk-9rkjhnx2.js +5 -0
- package/dist/{chunk-qjn6a2ed.js.map → chunk-9rkjhnx2.js.map} +1 -1
- package/dist/{chunk-pdymdjpq.js → chunk-a2y481gh.js} +2 -2
- package/dist/{chunk-pdymdjpq.js.map → chunk-a2y481gh.js.map} +1 -1
- package/dist/{chunk-21hhvphe.js → chunk-a95pp5kn.js} +2 -2
- package/dist/{chunk-21hhvphe.js.map → chunk-a95pp5kn.js.map} +1 -1
- package/dist/{chunk-mca5s0bf.js → chunk-acsyr6wq.js} +3 -3
- package/dist/{chunk-mca5s0bf.js.map → chunk-acsyr6wq.js.map} +1 -1
- package/dist/{chunk-eydww2nn.js → chunk-atn9z9hx.js} +2 -2
- package/dist/{chunk-eydww2nn.js.map → chunk-atn9z9hx.js.map} +1 -1
- package/dist/{chunk-3e55yw7v.js → chunk-axjw9g4s.js} +3 -3
- package/dist/{chunk-3e55yw7v.js.map → chunk-axjw9g4s.js.map} +1 -1
- package/dist/{chunk-v979k0be.js → chunk-ay5raj98.js} +3 -3
- package/dist/{chunk-v979k0be.js.map → chunk-ay5raj98.js.map} +1 -1
- package/dist/{chunk-pn3egz75.js → chunk-bpfc31b9.js} +1 -1
- package/dist/{chunk-z6x78wb3.js → chunk-bv9kqnj1.js} +2 -2
- package/dist/{chunk-z6x78wb3.js.map → chunk-bv9kqnj1.js.map} +1 -1
- package/dist/{chunk-hvyzp9p6.js → chunk-dp2xrc54.js} +2 -2
- package/dist/{chunk-hvyzp9p6.js.map → chunk-dp2xrc54.js.map} +1 -1
- package/dist/{chunk-7d1f5gyv.js → chunk-dvsafvww.js} +2 -2
- package/dist/{chunk-7d1f5gyv.js.map → chunk-dvsafvww.js.map} +1 -1
- package/dist/{chunk-n2c748aw.js → chunk-e1qssbfa.js} +2 -2
- package/dist/{chunk-n2c748aw.js.map → chunk-e1qssbfa.js.map} +1 -1
- package/dist/{chunk-7901z26g.js → chunk-eb03m143.js} +2 -2
- package/dist/{chunk-7901z26g.js.map → chunk-eb03m143.js.map} +1 -1
- package/dist/{chunk-ads3c8m0.js → chunk-f1pyzfw0.js} +2 -2
- package/dist/{chunk-ads3c8m0.js.map → chunk-f1pyzfw0.js.map} +1 -1
- package/dist/{chunk-bwjaq694.js → chunk-f3jf9bk8.js} +3 -3
- package/dist/{chunk-bwjaq694.js.map → chunk-f3jf9bk8.js.map} +1 -1
- package/dist/{chunk-j7pzdvxr.js → chunk-fhe8c8zy.js} +2 -2
- package/dist/{chunk-j7pzdvxr.js.map → chunk-fhe8c8zy.js.map} +1 -1
- package/dist/{chunk-dxesf8bt.js → chunk-gae8a3jk.js} +2 -2
- package/dist/{chunk-dxesf8bt.js.map → chunk-gae8a3jk.js.map} +1 -1
- package/dist/{chunk-6et7jwp8.js → chunk-grxz4ecb.js} +2 -2
- package/dist/{chunk-6et7jwp8.js.map → chunk-grxz4ecb.js.map} +1 -1
- package/dist/{chunk-crk4ddqa.js → chunk-h4179pzx.js} +3 -3
- package/dist/{chunk-crk4ddqa.js.map → chunk-h4179pzx.js.map} +1 -1
- package/dist/{chunk-bch7xbsr.js → chunk-hqxbxk1f.js} +2 -2
- package/dist/{chunk-bch7xbsr.js.map → chunk-hqxbxk1f.js.map} +1 -1
- package/dist/{chunk-2450kxym.js → chunk-jc5nbacx.js} +2 -2
- package/dist/{chunk-2450kxym.js.map → chunk-jc5nbacx.js.map} +1 -1
- package/dist/{chunk-3vgjrn2r.js → chunk-jg94sqmx.js} +2 -2
- package/dist/{chunk-3vgjrn2r.js.map → chunk-jg94sqmx.js.map} +1 -1
- package/dist/{chunk-ftc9292d.js → chunk-jkftpj8g.js} +2 -2
- package/dist/{chunk-ftc9292d.js.map → chunk-jkftpj8g.js.map} +1 -1
- package/dist/{chunk-8yxjq6cm.js → chunk-jm4908xm.js} +2 -2
- package/dist/{chunk-8yxjq6cm.js.map → chunk-jm4908xm.js.map} +1 -1
- package/dist/{chunk-kxc2mzzr.js → chunk-jy26hy7z.js} +2 -2
- package/dist/{chunk-kxc2mzzr.js.map → chunk-jy26hy7z.js.map} +1 -1
- package/dist/{chunk-tgy75n24.js → chunk-k4v5e6ww.js} +2 -2
- package/dist/{chunk-tgy75n24.js.map → chunk-k4v5e6ww.js.map} +1 -1
- package/dist/{chunk-4qyp7w89.js → chunk-kn2hk1n3.js} +1 -1
- package/dist/{chunk-9xxgj5zk.js → chunk-mcntwhp7.js} +3 -3
- package/dist/{chunk-9xxgj5zk.js.map → chunk-mcntwhp7.js.map} +1 -1
- package/dist/{chunk-wnmpwb4s.js → chunk-mdby3yea.js} +3 -3
- package/dist/{chunk-wnmpwb4s.js.map → chunk-mdby3yea.js.map} +1 -1
- package/dist/{chunk-qx9p15em.js → chunk-mmns1ske.js} +2 -2
- package/dist/{chunk-qx9p15em.js.map → chunk-mmns1ske.js.map} +1 -1
- package/dist/{chunk-ja3n968b.js → chunk-mzmv1zmn.js} +2 -2
- package/dist/{chunk-ja3n968b.js.map → chunk-mzmv1zmn.js.map} +1 -1
- package/dist/{chunk-v4ecxbgd.js → chunk-n1dcwz8z.js} +2 -2
- package/dist/{chunk-v4ecxbgd.js.map → chunk-n1dcwz8z.js.map} +1 -1
- package/dist/{chunk-mvp6fkg2.js → chunk-n6rf9tnb.js} +3 -3
- package/dist/{chunk-mvp6fkg2.js.map → chunk-n6rf9tnb.js.map} +1 -1
- package/dist/{chunk-kzz2nfzf.js → chunk-nfmsyjf4.js} +2 -2
- package/dist/{chunk-kzz2nfzf.js.map → chunk-nfmsyjf4.js.map} +1 -1
- package/dist/{chunk-z4fhhtjh.js → chunk-ngk1tka6.js} +2 -2
- package/dist/{chunk-z4fhhtjh.js.map → chunk-ngk1tka6.js.map} +1 -1
- package/dist/{chunk-j13jmjkr.js → chunk-p7s80mhn.js} +2 -2
- package/dist/{chunk-j13jmjkr.js.map → chunk-p7s80mhn.js.map} +1 -1
- package/dist/{chunk-awryyak8.js → chunk-pdxmd8bd.js} +2 -2
- package/dist/{chunk-awryyak8.js.map → chunk-pdxmd8bd.js.map} +1 -1
- package/dist/{chunk-421hq1rw.js → chunk-ppx8p2g0.js} +1 -1
- package/dist/{chunk-64yf0shq.js → chunk-q26d0qa3.js} +2 -2
- package/dist/{chunk-64yf0shq.js.map → chunk-q26d0qa3.js.map} +1 -1
- package/dist/{chunk-40yd1n60.js → chunk-q67c5zyw.js} +2 -2
- package/dist/{chunk-40yd1n60.js.map → chunk-q67c5zyw.js.map} +1 -1
- package/dist/{chunk-gj0bwm41.js → chunk-q902m8c6.js} +2 -2
- package/dist/{chunk-gj0bwm41.js.map → chunk-q902m8c6.js.map} +1 -1
- package/dist/{chunk-t9fh0ptd.js → chunk-qmezsfxd.js} +2 -2
- package/dist/{chunk-t9fh0ptd.js.map → chunk-qmezsfxd.js.map} +1 -1
- package/dist/{chunk-8szsd6vy.js → chunk-r8zp4khs.js} +2 -2
- package/dist/{chunk-8szsd6vy.js.map → chunk-r8zp4khs.js.map} +1 -1
- package/dist/{chunk-70jhw0ft.js → chunk-rk3xgyd0.js} +1 -1
- package/dist/{chunk-xpzdwhjg.js → chunk-se6ktpm5.js} +3 -3
- package/dist/{chunk-xpzdwhjg.js.map → chunk-se6ktpm5.js.map} +1 -1
- package/dist/{chunk-x93dpv6e.js → chunk-szx9z0zm.js} +2 -2
- package/dist/{chunk-x93dpv6e.js.map → chunk-szx9z0zm.js.map} +1 -1
- package/dist/{chunk-3dkaz47e.js → chunk-t956xcy4.js} +2 -2
- package/dist/{chunk-3dkaz47e.js.map → chunk-t956xcy4.js.map} +1 -1
- package/dist/{chunk-fjnhqbtx.js → chunk-v1d1xc2r.js} +1 -1
- package/dist/{chunk-qrc2r0ce.js → chunk-vd8a3g3n.js} +3 -3
- package/dist/{chunk-qrc2r0ce.js.map → chunk-vd8a3g3n.js.map} +1 -1
- package/dist/{chunk-x47kwv2x.js → chunk-vf4tn1yd.js} +2 -2
- package/dist/{chunk-x47kwv2x.js.map → chunk-vf4tn1yd.js.map} +1 -1
- package/dist/{chunk-8pdke84p.js → chunk-vre98hts.js} +2 -2
- package/dist/{chunk-8pdke84p.js.map → chunk-vre98hts.js.map} +1 -1
- package/dist/{chunk-svrvb47q.js → chunk-w6j7q0dc.js} +2 -2
- package/dist/{chunk-svrvb47q.js.map → chunk-w6j7q0dc.js.map} +1 -1
- package/dist/{chunk-bzrta2sw.js → chunk-w7511nk3.js} +3 -3
- package/dist/{chunk-bzrta2sw.js.map → chunk-w7511nk3.js.map} +1 -1
- package/dist/{chunk-wzr8tzv0.js → chunk-xg2ctnwf.js} +2 -2
- package/dist/{chunk-wzr8tzv0.js.map → chunk-xg2ctnwf.js.map} +1 -1
- package/dist/{chunk-9znec0we.js → chunk-ydgtkgf9.js} +24 -24
- package/dist/chunk-ydgtkgf9.js.map +27 -0
- package/dist/{chunk-d3a29hyg.js → chunk-yg7sra7w.js} +3 -3
- package/dist/{chunk-d3a29hyg.js.map → chunk-yg7sra7w.js.map} +1 -1
- package/dist/{chunk-tbvrv4h2.js → chunk-zq4jbwvn.js} +2 -2
- package/dist/{chunk-tbvrv4h2.js.map → chunk-zq4jbwvn.js.map} +1 -1
- package/dist/{chunk-rq0dpv7r.js → chunk-ztpenack.js} +2 -2
- package/dist/{chunk-rq0dpv7r.js.map → chunk-ztpenack.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/Email.d.ts.map +1 -1
- package/dist/email/index.js +3 -4
- package/dist/email/index.js.map +4 -15
- 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/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/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-9znec0we.js.map +0 -27
- package/dist/chunk-qjn6a2ed.js +0 -5
- /package/dist/{chunk-81y96dax.js.map → chunk-6n3wadx7.js.map} +0 -0
- /package/dist/{chunk-pn3egz75.js.map → chunk-bpfc31b9.js.map} +0 -0
- /package/dist/{chunk-4qyp7w89.js.map → chunk-kn2hk1n3.js.map} +0 -0
- /package/dist/{chunk-421hq1rw.js.map → chunk-ppx8p2g0.js.map} +0 -0
- /package/dist/{chunk-70jhw0ft.js.map → chunk-rk3xgyd0.js.map} +0 -0
- /package/dist/{chunk-fjnhqbtx.js.map → chunk-v1d1xc2r.js.map} +0 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ca as
|
|
3
|
-
`)}function
|
|
2
|
+
import{ca as aQ,da as JZ,ea as $Z,fa as d6,ga as n6,ha as o6,ia as r$,ja as s6,ka as a6,la as _$,ma as t6,na as r6,oa as e6,pa as J0}from"../chunk-jg94sqmx.js";import{$c as I6,Ac as xZ,Bc as OQ,Dc as _Q,Ec as RQ,Fc as MQ,Gc as SQ,Hc as AQ,Ic as EQ,Jc as kQ,Kc as TQ,Lc as jQ,Mc as xQ,Nc as wQ,Oc as IQ,Qc as t$,Rc as M6,Sc as S6,Tc as A6,Uc as R6,Vc as E6,Wc as k6,Xc as T6,Yc as j6,Zc as x6,_c as w6,ad as NJ,bd as f6,cd as O8,dd as q6,ed as _8,fd as b6,gd as v6,hd as y6,ic as o$,id as fJ,jc as z8,jd as D$,kc as Y8,kd as h6,lc as s$,ld as g6,md as L8,nd as c6,od as u6,pc as sQ,pd as m6,qc as pQ,qd as p6,rc as YJ,rd as l6,sc as B6,sd as B8,tc as h,td as i6,uc as FQ,ud as z$,vc as UQ,xc as CQ,yc as m,zc as jZ}from"../chunk-ydgtkgf9.js";import{Ad as j,Hd as i,Id as a$,Ld as D8,Md as H8,Nd as P8,Od as mJ,Pd as N8,Qd as oJ,Rd as pJ,Sd as u$,Td as F8,Ud as U8,Vd as sJ,Wd as C8,ae as QJ,ce as $J,yd as ZZ,zd as R}from"../chunk-vd8a3g3n.js";import{te as zQ}from"../chunk-a2y481gh.js";import"../chunk-8xta8133.js";import{Pi as f,ni as Q8,qi as W8,vj as X8,wj as T$}from"../chunk-ay5raj98.js";import{Aj as nJ,xj as Z8,zj as dJ}from"../chunk-mzmv1zmn.js";import{Dj as O6,Ej as _6,Fj as L6}from"../chunk-w7511nk3.js";import{Sj as l}from"../chunk-jy26hy7z.js";import"../chunk-fhe8c8zy.js";import{$k as V8,Zk as K8,_k as G8,al as c$}from"../chunk-se6ktpm5.js";import"../chunk-5zbqh32n.js";import{gl as e,hl as JJ,wl as xJ}from"../chunk-n6rf9tnb.js";import"../chunk-jc5nbacx.js";import"../chunk-07rrezpq.js";import{nm as CZ}from"../chunk-yg7sra7w.js";import"../chunk-pdxmd8bd.js";import"../chunk-k4v5e6ww.js";import{Km as eJ}from"../chunk-dp2xrc54.js";import"../chunk-f1pyzfw0.js";import{existsSync as w8,readdirSync as Q0,readFileSync as KQ}from"fs";import{isAbsolute as I8,join as AJ,relative as f8,sep as q8}from"path";var GQ="prompts.json",b8=/\{\{>\s*([\w./-]+)\s*\}\}/g,ZQ=/\{\{(\w+)\}\}/g,v8=/^[\w-]+(\/[\w-]+)*$/,WQ={dir:"app/agents",shared:"prompts"},EJ={},tJ=new Map,RJ;function y8(){if(RJ===void 0){let J=AJ(eJ(),"dist","server",GQ);RJ=w8(J)?JSON.parse(KQ(J,"utf8")):null}return RJ??null}function h8(J){return J.replace(/\r?\n$/,"")}function XQ(){return EJ.cache??Bun.env.NODE_ENV==="production"}function g8(J,$){if(!v8.test(J))throw Error(`"${J}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let Q=$.dir??EJ.dir??WQ.dir,Z=I8(Q)?Q:AJ(process.cwd(),Q),W=J.includes("/")?`${J}.md`:AJ($.shared??EJ.shared??WQ.shared,`${J}.md`);return AJ(Z,W)}function c8(J,$){let Q=g8(J,$),Z=XQ()?tJ.get(Q):void 0;if(Z!==void 0)return Z;let W=Bun.env.NODE_ENV==="production";if(W){let K=y8()?.[f8(eJ(),Q).split(q8).join("/")];if(K!==void 0)return K}let X;try{X=h8(KQ(Q,"utf8"))}catch(K){if(K.code==="ENOENT"){let G=W?` or in dist/server/${GQ}`:"";throw Error(`The prompt "${J}" does not exist (looked for ${Q}${G}).`)}throw K}if(XQ())tJ.set(Q,X);return X}function rJ(J,$,Q){if($.includes(J))throw Error(`The prompt "${J}" includes itself: ${[...$,J].join(" > ")}.`);return c8(J,Q).replace(b8,(Z,W)=>rJ(W,[...$,J],Q))}class VQ{static configure(J){EJ={...J},tJ.clear(),RJ=void 0}static render(J,$={},Q={}){return rJ(J,[],Q).replace(ZQ,(Z,W)=>{if(!Object.hasOwn($,W))throw Error(`The prompt "${J}" has no value for {{${W}}}.`);return String($[W])})}static placeholders(J,$={}){let Q=[...rJ(J,[],$).matchAll(ZQ)].map((Z)=>Z[1]);return[...new Set(Q)]}}class J$ extends zQ{name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await m.sweep({limit:100})===100);}}var TJ=20,u8=300,m8=200;function DQ(J,$){if($<=0||J.length===0)return null;let Q=(X,K)=>K.createdAt-X.createdAt||(X.id<K.id?1:-1);return["<jobs>","Background jobs that tools started in this conversation, running ones first. A running job's result replaces its tool result when it finishes. Do not start the same work again while a job for it is running.",...[...J.filter((X)=>!h(X.state)).sort(Q),...J.filter((X)=>h(X.state)).sort(Q)].slice(0,$).map((X)=>{let K=[`- ${X.id} (${X.toolName})`];if(X.state==="waiting")K.push(`waiting for ${(X.after??[]).join(", ")} since ${kJ(X.createdAt)}`);else if(X.state==="running")K.push(`running since ${kJ(X.createdAt)}`);else if(X.state==="ok")K.push(`finished at ${kJ(X.settledAt??X.updatedAt)}`);else{let G=X.error?`${X.error.code}: ${YQ(X.error.message,m8)}`:"failed";K.push(`failed at ${kJ(X.settledAt??X.updatedAt)} (${G})`)}if(X.summary!==void 0)K.push(`summary: ${YQ(JSON.stringify(X.summary),u8)}`);if(X.orphaned)K.push("its tool call was lost when the turn that started it was cut short");return K.join("; ")}),"</jobs>"].join(`
|
|
3
|
+
`)}function kJ(J){return new Date(J).toISOString().replace(/\.\d{3}Z$/,"Z")}function YQ(J,$){return J.length<=$?J:`${J.slice(0,$-1)}\u2026`}var HQ=["after_jobs","batch_key","queued","inbox","job_checkpoint"],PQ=20;class $${table;sql;dialect;connection;later;constructor(J,$={}){let Q=$.table??"gemi_agent_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The agent jobs table name "${Q}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Q,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of p8(this.dialect,this.table))await this.sql.unsafe(J)}async transaction(J){if(this.connection===void 0||this.joinable())return J();return xJ(this.sql,()=>J(),{connection:this.connection})}async create(J){let $=J.after!==void 0||J.batch!==void 0||J.queued!==void 0;if($)await this.requireLaterColumns("A job with `after` or `batch`");let Q=this.q(),Z=this.clock(Q),W=J.state??"running";if($)await Q`
|
|
4
4
|
INSERT INTO ${this.name(Q)}
|
|
5
5
|
(id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,
|
|
6
6
|
orphaned, attachment_scope, created_at, updated_at, deadline_at,
|
|
7
7
|
after_jobs, batch_key, queued)
|
|
8
8
|
VALUES
|
|
9
9
|
(${J.id}, ${J.threadId}, ${J.runId}, ${J.toolCallId}, ${J.toolName},
|
|
10
|
-
${J.owner}, ${J.job}, ${
|
|
10
|
+
${J.owner}, ${J.job}, ${g(J.summary)}, ${W}, 0, ${J.attachmentScope},
|
|
11
11
|
${Z}, ${Z}, ${Z} + ${this.ms(Q,J.deadlineMs)},
|
|
12
|
-
${
|
|
12
|
+
${g(J.after)}, ${J.batch??null}, ${g(J.queued)})
|
|
13
13
|
`;else await Q`
|
|
14
14
|
INSERT INTO ${this.name(Q)}
|
|
15
15
|
(id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,
|
|
16
16
|
orphaned, attachment_scope, created_at, updated_at, deadline_at)
|
|
17
17
|
VALUES
|
|
18
18
|
(${J.id}, ${J.threadId}, ${J.runId}, ${J.toolCallId}, ${J.toolName},
|
|
19
|
-
${J.owner}, ${J.job}, ${
|
|
19
|
+
${J.owner}, ${J.job}, ${g(J.summary)}, ${W}, 0, ${J.attachmentScope},
|
|
20
20
|
${Z}, ${Z}, ${Z} + ${this.ms(Q,J.deadlineMs)})
|
|
21
|
-
`;let
|
|
21
|
+
`;let X=await this.get(J.id);if(!X)throw Error(`The background job ${J.id} was not found after it was written.`);return X}async get(J){let $=this.q(),Q=await $`SELECT * FROM ${this.name($)} WHERE id = ${J}`;return Q[0]?r(Q[0]):null}async listForThread(J,$={}){let Q=this.q(),Z=$.states===void 0?Q`1 = 1`:$.states.length===0?Q`1 = 0`:Q`state IN (${NQ(Q,$.states)})`;return($.limit===void 0?await Q`
|
|
22
22
|
SELECT * FROM ${this.name(Q)}
|
|
23
23
|
WHERE thread_id = ${J} AND ${Z}
|
|
24
24
|
ORDER BY created_at DESC, id DESC
|
|
@@ -27,36 +27,36 @@ import{ca as uQ,da as lQ,ea as iQ,fa as _6,ga as B6,ha as S6,ia as m$,ja as M6,k
|
|
|
27
27
|
WHERE thread_id = ${J} AND ${Z}
|
|
28
28
|
ORDER BY created_at DESC, id DESC
|
|
29
29
|
LIMIT ${Math.max(0,Math.floor($.limit))}
|
|
30
|
-
`).map(
|
|
31
|
-
UPDATE ${this.name(Z)} SET ${
|
|
32
|
-
WHERE id = ${J} AND state IN (${
|
|
33
|
-
`;return
|
|
30
|
+
`).map(r)}async transition(J,$,Q){if($.length===0)return!1;if("checkpoint"in Q)await this.requireLaterColumns("`job.checkpoint`");let Z=this.q(),W=this.clock(Z),X=[Z`updated_at = ${W}`];if(Q.deadlineMs!==void 0)X.push(Z`deadline_at = ${W} + ${this.ms(Z,Q.deadlineMs)}`);if("checkpoint"in Q)X.push(Z`job_checkpoint = ${g(Q.checkpoint)}`);if(Q.state!==void 0)X.push(Z`state = ${Q.state}`);if("output"in Q)X.push(Z`output = ${g(Q.output)}`);if("error"in Q)X.push(Z`error = ${g(Q.error)}`);if("usage"in Q)X.push(Z`${this.column(Z,"usage")} = ${g(Q.usage)}`);if("orphaned"in Q)X.push(Z`orphaned = ${Q.orphaned?1:0}`);if(Q.state!==void 0&&h(Q.state))X.push(Q.settledAt!==void 0?Z`settled_at = COALESCE(settled_at, ${this.ms(Z,Q.settledAt)})`:Z`settled_at = COALESCE(settled_at, ${W})`);let K=X.reduce((z,V)=>Z`${z}, ${V}`),G=await Z`
|
|
31
|
+
UPDATE ${this.name(Z)} SET ${K}
|
|
32
|
+
WHERE id = ${J} AND state IN (${NQ(Z,$)})
|
|
33
|
+
`;return jJ(G)>0}async overdue(J,$){let Q=this.q();return(await Q`
|
|
34
34
|
SELECT * FROM ${this.name(Q)}
|
|
35
35
|
WHERE state = 'running' AND deadline_at <= ${this.ms(Q,J)}
|
|
36
36
|
ORDER BY deadline_at, id
|
|
37
37
|
LIMIT ${Math.max(0,Math.floor($))}
|
|
38
|
-
`).map(
|
|
38
|
+
`).map(r)}async waitingOn(J){if(!await this.columns())return[];let $=this.q();return(await $`
|
|
39
39
|
SELECT * FROM ${this.name($)}
|
|
40
40
|
WHERE state = 'waiting' AND after_jobs LIKE ${`%${JSON.stringify(J)}%`}
|
|
41
41
|
ORDER BY created_at, id
|
|
42
|
-
`).map(
|
|
42
|
+
`).map(r).filter((Z)=>Z.after?.includes(J))}async waiting(J){let $=this.q();return(await $`
|
|
43
43
|
SELECT * FROM ${this.name($)}
|
|
44
44
|
WHERE state = 'waiting'
|
|
45
45
|
ORDER BY created_at, id
|
|
46
46
|
LIMIT ${Math.max(0,Math.floor(J))}
|
|
47
|
-
`).map(
|
|
47
|
+
`).map(r)}async listBatch(J){if(!await this.columns())return[];let $=this.q();return(await $`
|
|
48
48
|
SELECT * FROM ${this.name($)} WHERE batch_key = ${J} ORDER BY created_at, id
|
|
49
|
-
`).map(
|
|
49
|
+
`).map(r)}async appendInbox(J,$){await this.requireLaterColumns("`AgentJobs.message`");for(let Q=0;Q<PQ;Q++){let Z=this.q(),[W]=await Z`
|
|
50
50
|
SELECT state, inbox FROM ${this.name(Z)} WHERE id = ${J}
|
|
51
|
-
`;if(!W||
|
|
52
|
-
UPDATE ${this.name(Z)} SET inbox = ${
|
|
53
|
-
WHERE id = ${J} AND state IN ('waiting', 'running') AND ${this.sameInbox(Z,
|
|
54
|
-
`;if(
|
|
51
|
+
`;if(!W||h(String(W.state)))return!1;let X=W.inbox===null||W.inbox===void 0?null:String(W.inbox),K=JSON.stringify([...b(X)??[],$]),G=await Z`
|
|
52
|
+
UPDATE ${this.name(Z)} SET inbox = ${K}, updated_at = ${this.clock(Z)}
|
|
53
|
+
WHERE id = ${J} AND state IN ('waiting', 'running') AND ${this.sameInbox(Z,X)}
|
|
54
|
+
`;if(jJ(G)>0)return!0}throw Error(`Could not add a message to background job ${J}: too many writers at once.`)}async takeInbox(J){if(!await this.columns())return[];for(let $=0;$<PQ;$++){let Q=this.q(),[Z]=await Q`SELECT inbox FROM ${this.name(Q)} WHERE id = ${J}`;if(!Z||Z.inbox===null||Z.inbox===void 0)return[];let W=String(Z.inbox),X=await Q`
|
|
55
55
|
UPDATE ${this.name(Q)} SET inbox = NULL WHERE id = ${J} AND ${this.sameInbox(Q,W)}
|
|
56
|
-
`;if(
|
|
56
|
+
`;if(jJ(X)>0)return b(W)??[]}throw Error(`Could not take the messages of background job ${J}: too many writers.`)}async now(){let J=this.q(),[$]=await J`SELECT ${this.clock(J)} AS now`;return Number($.now)}async prune(J){let $=this.q(),Q=await $`
|
|
57
57
|
DELETE FROM ${this.name($)}
|
|
58
58
|
WHERE state IN ('ok', 'error') AND settled_at <= ${this.clock($)} - ${this.ms($,J)}
|
|
59
|
-
`;return
|
|
59
|
+
`;return jJ(Q)}columns(){return this.later??=(async()=>{try{return await this.sql.unsafe(`SELECT ${HQ.join(", ")} FROM ${this.quoted(this.table)} WHERE 1 = 0`),!0}catch{return!1}})(),this.later}async requireLaterColumns(J){if(await this.columns())return;throw this.later=void 0,Error(`${J} needs the columns ${HQ.join(", ")} on the ${this.table} table, which it does not have. Add them (see docs/ai-background-jobs.md and UPGRADE.md), or call createTable() on a new table.`)}sameInbox(J,$){return $===null?J`inbox IS NULL`:J`inbox = ${$}`}quoted(J){return this.dialect==="mysql"||this.dialect==="mariadb"?`\`${J}\``:`"${J}"`}joinable(){if(this.connection===void 0)return;let J=e();if(J===void 0||JJ()!==this.connection)return;return J}q(){return this.joinable()??this.sql}column(J,$){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe(Q?`\`${$}\``:`"${$}"`)}name(J){let $=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe($?`\`${this.table}\``:`"${this.table}"`)}clock(J){switch(this.dialect){case"postgres":return J`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return J`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return J`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(J,$){let Q=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${Q} AS SIGNED)`:J`CAST(${Q} AS BIGINT)`}}function NQ(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function g(J){return J===void 0?null:JSON.stringify(J)}function b(J){if(J===null||J===void 0)return;return JSON.parse(String(J))}function r(J){let $=b(J.summary),Q=b(J.output),Z=b(J.error),W=b(J.usage),X=b(J.after_jobs),K=b(J.queued),G=b(J.inbox),z=b(J.job_checkpoint);return{id:String(J.id),threadId:String(J.thread_id),runId:String(J.run_id),toolCallId:String(J.tool_call_id),toolName:String(J.tool_name),owner:J.owner===null||J.owner===void 0?null:String(J.owner),job:J.job===null||J.job===void 0?null:String(J.job),...$!==void 0?{summary:$}:{},state:String(J.state),...Q!==void 0?{output:Q}:{},...Z!==void 0?{error:Z}:{},...W!==void 0?{usage:W}:{},...Number(J.orphaned)===1?{orphaned:!0}:{},attachmentScope:J.attachment_scope===null||J.attachment_scope===void 0?null:String(J.attachment_scope),...X!==void 0?{after:X}:{},...J.batch_key===null||J.batch_key===void 0?{}:{batch:String(J.batch_key)},...K!==void 0?{queued:K}:{},...G!==void 0&&G.length>0?{inbox:G}:{},...z!==void 0?{checkpoint:z}:{},createdAt:Number(J.created_at),updatedAt:Number(J.updated_at),deadlineAt:Number(J.deadline_at),...J.settled_at===null||J.settled_at===void 0?{}:{settledAt:Number(J.settled_at)}}}function jJ(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function p8(J,$){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
60
60
|
\`id\` VARCHAR(191) NOT NULL,
|
|
61
61
|
\`thread_id\` VARCHAR(191) NOT NULL,
|
|
62
62
|
\`run_id\` VARCHAR(191) NOT NULL,
|
|
@@ -110,26 +110,26 @@ import{ca as uQ,da as lQ,ea as iQ,fa as _6,ga as B6,ha as S6,ia as m$,ja as M6,k
|
|
|
110
110
|
"queued" TEXT,
|
|
111
111
|
"inbox" TEXT,
|
|
112
112
|
"job_checkpoint" TEXT${Z}
|
|
113
|
-
)`,`CREATE INDEX IF NOT EXISTS "${$}_thread_id_created_at_idx" ON "${$}"("thread_id", "created_at")`,`CREATE INDEX IF NOT EXISTS "${$}_state_deadline_at_idx" ON "${$}"("state", "deadline_at")`]}var
|
|
113
|
+
)`,`CREATE INDEX IF NOT EXISTS "${$}_thread_id_created_at_idx" ON "${$}"("thread_id", "created_at")`,`CREATE INDEX IF NOT EXISTS "${$}_state_deadline_at_idx" ON "${$}"("state", "deadline_at")`]}var LQ=4;class Z${table;sql;dialect;connection;constructor(J,$={}){let Q=$.table??"gemi_agent_memories";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The agent memories table name "${Q}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Q,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of l8(this.dialect,this.table))await this.sql.unsafe(J)}async list(J,$={}){if(J.length===0)return[];if($.kinds!==void 0&&$.kinds.length===0)return[];let Q=this.q(),Z=[Q`scope IN (${GJ(Q,J)})`];if($.kinds!==void 0)Z.push(Q`kind IN (${GJ(Q,$.kinds)})`);if(!$.includeExpired)Z.push(Q`(expires_at IS NULL OR expires_at > ${this.clock(Q)})`);if($.after!==void 0){let[z]=await Q`
|
|
114
114
|
SELECT created_at, id FROM ${this.name(Q)}
|
|
115
|
-
WHERE id = ${$.after} AND scope IN (${
|
|
116
|
-
`;if(
|
|
115
|
+
WHERE id = ${$.after} AND scope IN (${GJ(Q,J)})
|
|
116
|
+
`;if(z){let V=this.ms(Q,Number(z.created_at));Z.push(Q`(created_at > ${V} OR (created_at = ${V} AND id > ${String(z.id)}))`)}}let W=Z.reduce((z,V)=>Q`${z} AND ${V}`),X=$.limit===void 0||$.tags!==void 0?void 0:Math.max(0,Math.floor($.limit)),G=(X===void 0?await Q`
|
|
117
117
|
SELECT * FROM ${this.name(Q)} WHERE ${W}
|
|
118
118
|
ORDER BY created_at, id
|
|
119
119
|
`:await Q`
|
|
120
120
|
SELECT * FROM ${this.name(Q)} WHERE ${W}
|
|
121
121
|
ORDER BY created_at, id
|
|
122
|
-
LIMIT ${
|
|
123
|
-
`).map(
|
|
124
|
-
UPDATE ${this.name(Z)} SET ${
|
|
122
|
+
LIMIT ${X}
|
|
123
|
+
`).map(Q$);if($.tags!==void 0){if(G=G.filter((z)=>SQ(z,$.tags)),$.limit!==void 0)G=G.slice(0,Math.max(0,Math.floor($.limit)))}return G}async get(J){let $=this.q(),Q=await $`SELECT * FROM ${this.name($)} WHERE id = ${J}`;return Q[0]?Q$(Q[0]):null}async upsert(J){let $=J.key??null;if($===null)return await this.insert(J,null),{record:await this.mustGet(J.id),action:"added"};for(let Q=1;;Q++){let Z=await this.atKey(J.scope,$);if(Z){if(AQ(Z,J))return{record:Z,action:"unchanged"};let W=await this.update(Z.id,{kind:J.kind,content:J.content,tags:J.tags??[],pinned:J.pinned??!1,expiresAt:J.expiresAt??null},Z.version);if(W)return{record:W,action:"updated"}}else try{return await this.insert(J,$),{record:await this.mustGet(J.id),action:"added"}}catch(W){if(Q>=LQ||!await this.atKey(J.scope,$))throw W}if(Q>=LQ)throw Error(`The memory at "${$}" in ${J.scope} kept changing while it was being written.`)}}async update(J,$,Q){let Z=this.q(),W=[Z`version = version + 1`,Z`updated_at = ${this.clock(Z)}`];if($.kind!==void 0)W.push(Z`kind = ${$.kind}`);if($.content!==void 0)W.push(Z`content = ${$.content}`);if($.key!==void 0)W.push(Z`${this.column(Z,"key")} = ${$.key}`);if($.tags!==void 0)W.push(Z`tags = ${JSON.stringify($.tags)}`);if($.pinned!==void 0)W.push(Z`pinned = ${$.pinned?1:0}`);if($.expiresAt!==void 0)W.push($.expiresAt===null?Z`expires_at = NULL`:Z`expires_at = ${this.ms(Z,$.expiresAt)}`);let X=W.reduce((G,z)=>Z`${G}, ${z}`),K=Q===void 0?await Z`UPDATE ${this.name(Z)} SET ${X} WHERE id = ${J}`:await Z`
|
|
124
|
+
UPDATE ${this.name(Z)} SET ${X}
|
|
125
125
|
WHERE id = ${J} AND version = ${Math.floor(Q)}
|
|
126
|
-
`;if(
|
|
126
|
+
`;if(wJ(K)===0)return null;return this.get(J)}async delete(J){if(J.length===0)return 0;let $=this.q(),Q=await $`DELETE FROM ${this.name($)} WHERE id IN (${GJ($,[...new Set(J)])})`;return wJ(Q)}async deleteScope(J){let $=this.q();return wJ(await $`DELETE FROM ${this.name($)} WHERE scope = ${J}`)}async search(J,$,Q={}){let Z=await this.list(J,{kinds:Q.kinds,tags:Q.tags});return MQ(Z,$,Q.limit)}async count(J){let $=this.q(),[Q]=await $`
|
|
127
127
|
SELECT COUNT(*) AS total FROM ${this.name($)}
|
|
128
128
|
WHERE scope = ${J} AND (expires_at IS NULL OR expires_at > ${this.clock($)})
|
|
129
129
|
`;return Number(Q?.total??0)}async touch(J,$){if(J.length===0)return;let Q=this.q();await Q`
|
|
130
130
|
UPDATE ${this.name(Q)} SET last_used_at = ${this.ms(Q,$)}
|
|
131
|
-
WHERE id IN (${
|
|
132
|
-
`}async prune(J){let $=this.q();return
|
|
131
|
+
WHERE id IN (${GJ(Q,[...new Set(J)])})
|
|
132
|
+
`}async prune(J){let $=this.q();return wJ(await $`DELETE FROM ${this.name($)} WHERE expires_at IS NOT NULL AND expires_at <= ${this.ms($,J)}`)}async now(){let J=this.q(),[$]=await J`SELECT ${this.clock(J)} AS now`;return Number($.now)}async insert(J,$){let Q=this.q(),Z=this.clock(Q),W=J.expiresAt===void 0||J.expiresAt===null?null:Math.max(0,Math.round(J.expiresAt));await Q`
|
|
133
133
|
INSERT INTO ${this.name(Q)}
|
|
134
134
|
(id, scope, kind, ${this.column(Q,"key")}, content, tags, pinned, source, version,
|
|
135
135
|
created_at, updated_at, expires_at)
|
|
@@ -140,7 +140,7 @@ import{ca as uQ,da as lQ,ea as iQ,fa as _6,ga as B6,ha as S6,ia as m$,ja as M6,k
|
|
|
140
140
|
${W===null?null:this.ms(Q,W)})
|
|
141
141
|
`}async atKey(J,$){let Q=this.q(),Z=await Q`
|
|
142
142
|
SELECT * FROM ${this.name(Q)} WHERE scope = ${J} AND ${this.column(Q,"key")} = ${$}
|
|
143
|
-
`;return Z[0]?
|
|
143
|
+
`;return Z[0]?Q$(Z[0]):null}async mustGet(J){let $=await this.get(J);if(!$)throw Error(`The memory ${J} was not found after it was written.`);return $}joinable(){if(this.connection===void 0)return;let J=e();if(J===void 0||JJ()!==this.connection)return;return J}q(){return this.joinable()??this.sql}column(J,$){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe(Q?`\`${$}\``:`"${$}"`)}name(J){let $=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe($?`\`${this.table}\``:`"${this.table}"`)}clock(J){switch(this.dialect){case"postgres":return J`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return J`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return J`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(J,$){let Q=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${Q} AS SIGNED)`:J`CAST(${Q} AS BIGINT)`}}function GJ(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function BQ(J,$){if(J===null||J===void 0||J==="")return $;try{return JSON.parse(String(J))}catch{return $}}function Q$(J){let $=BQ(J.tags,[]);return{id:String(J.id),scope:String(J.scope),kind:String(J.kind),content:String(J.content),key:J.key===null||J.key===void 0?null:String(J.key),tags:Array.isArray($)?$.map(String):[],pinned:Number(J.pinned)===1,source:BQ(J.source,{by:"app"}),version:Number(J.version),createdAt:Number(J.created_at),updatedAt:Number(J.updated_at),lastUsedAt:J.last_used_at===null||J.last_used_at===void 0?null:Number(J.last_used_at),expiresAt:J.expires_at===null||J.expires_at===void 0?null:Number(J.expires_at)}}function wJ(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function l8(J,$){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
144
144
|
\`id\` VARCHAR(191) NOT NULL,
|
|
145
145
|
\`scope\` VARCHAR(191) NOT NULL,
|
|
146
146
|
\`kind\` VARCHAR(191) NOT NULL,
|
|
@@ -177,19 +177,19 @@ import{ca as uQ,da as lQ,ea as iQ,fa as _6,ga as B6,ha as S6,ia as m$,ja as M6,k
|
|
|
177
177
|
"updated_at" BIGINT NOT NULL,
|
|
178
178
|
"last_used_at" BIGINT,
|
|
179
179
|
"expires_at" BIGINT${Z}
|
|
180
|
-
)`,`CREATE INDEX IF NOT EXISTS "${$}_scope_kind_created_at_idx" ON "${$}"("scope", "kind", "created_at")`,`CREATE INDEX IF NOT EXISTS "${$}_expires_at_idx" ON "${$}"("expires_at")`,`CREATE UNIQUE INDEX IF NOT EXISTS "${$}_scope_key_key" ON "${$}"("scope", "key")`]}var AQ={n:0,mean:0,stddev:0,low:null,high:null};function u(J){let $=[0.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-0.13857109526572012,0.000009984369578019572,0.00000015056327351493116];if(J<0.5)return Math.log(Math.PI/Math.sin(Math.PI*J))-u(1-J);J-=1;let Q=$[0],Z=J+7.5;for(let W=1;W<9;W++)Q+=$[W]/(J+W);return 0.5*Math.log(2*Math.PI)+(J+0.5)*Math.log(Z)-Z+Math.log(Q)}function MQ(J,$,Q){let W=1,K=1-(J+$)*Q/(J+1);if(Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;K=1/K;let X=K;for(let G=1;G<=300;G++){let V=2*G,Y=G*($-G)*Q/((J+V-1)*(J+V));if(K=1+Y*K,Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+Y/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(K=1/K,X*=K*W,Y=-(J+G)*(J+$+G)*Q/((J+V)*(J+V+1)),K=1+Y*K,Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+Y/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;K=1/K;let z=K*W;if(X*=z,Math.abs(z-1)<0.00000000000001)break}return X}function A8(J,$,Q){if(J<=0)return 0;if(J>=1)return 1;let Z=Math.exp(u($+Q)-u($)-u(Q)+$*Math.log(J)+Q*Math.log(1-J));return J<($+1)/($+Q+2)?Z*MQ($,Q,J)/$:1-Z*MQ(Q,$,1-J)/Q}function rJ(J,$){return A8($/($+J*J),$/2,0.5)}function R8(J){if(!(J>0))return Number.POSITIVE_INFINITY;let $=1.959964,Q=2;while(rJ(Q,J)>0.05)Q*=2;for(let Z=0;Z<100;Z++){let W=($+Q)/2;if(rJ(W,J)>0.05)$=W;else Q=W}return($+Q)/2}function E8(J,$,Q,Z){let W=J+Q,K=$+Z,X=(z,D)=>u(z+1)-u(D+1)-u(z-D+1),G=(z)=>Math.exp(X($,z)+X(Z,W-z)-X(K,W)),V=G(J),Y=0;for(let z=Math.max(0,W-Z);z<=Math.min($,W);z++){let D=G(z);if(D<=V*1.0000001)Y+=D}return Math.min(1,Y)}function RQ(J,$){if(J.length<2)return 0;let Q=J.reduce((W,K)=>W+(K-$)**2,0),Z=Math.sqrt(Q/(J.length-1));return Z<0.000000000001*Math.max(1,Math.abs($))?0:Z}function eJ(J){let $=J.length;if($===0)return AQ;let Q=J.map((G)=>G?1:0),Z=Q.reduce((G,V)=>G+V,0)/$,W=3.841458881296,K=(Z+W/(2*$))/(1+W/$),X=1.959964*Math.sqrt(Z*(1-Z)/$+W/(4*$*$))/(1+W/$);return{n:$,mean:Z,stddev:RQ(Q,Z),low:Math.max(0,K-X),high:Math.min(1,K+X)}}function J$(J){let $=J.length;if($===0)return AQ;let Q=J.reduce((K,X)=>K+X,0)/$,Z=RQ(J,Q);if($<2||Z===0)return{n:$,mean:Q,stddev:Z,low:null,high:null};let W=R8($-1)*Z/Math.sqrt($);return{n:$,mean:Q,stddev:Z,low:Q-W,high:Q+W}}function KJ(J,$,Q){return{before:J.mean,after:$.mean,delta:$.mean-J.mean,p:Q,pAdjusted:Q,significant:!1}}function EQ(J,$){if(J.n===0||$.n===0)return KJ(J,$,null);let Q=(Z)=>Math.round(Z.mean*Z.n);return KJ(J,$,E8(Q(J),J.n,Q($),$.n))}function kQ(J,$){if(J.n<2||$.n<2)return KJ(J,$,null);let Q=J.stddev**2/J.n,Z=$.stddev**2/$.n,W=Math.sqrt(Q+Z);if(W===0)return KJ(J,$,null);let K=(Q+Z)**2/(Q**2/(J.n-1)+Z**2/($.n-1));return KJ(J,$,rJ(($.mean-J.mean)/W,K))}function TQ(J,$,Q){if(Q==="holm"){let Z=J.filter((K)=>K.p!==null).sort((K,X)=>K.p-X.p),W=0;Z.forEach((K,X)=>{W=Math.max(W,Math.min(1,K.p*(Z.length-X))),K.pAdjusted=W})}else for(let Z of J)Z.pAdjusted=Z.p;for(let Z of J)Z.significant=Z.pAdjusted!==null&&Z.pAdjusted<$&&Z.delta!==0}class EJ{name;cases;runs;concurrency;graders;pricing;task;constructor(J){this.name=J.name,this.cases=J.cases,this.runs=J.runs??1,this.concurrency=J.concurrency??1,this.task=J.task,this.graders=typeof J.graders==="function"?J.graders({judge:($)=>EJ.judge($)}):J.graders,this.pricing=J.pricing}static create(J){let $=`The eval "${J.name}"`;XJ(J.runs,$,"runs"),XJ(J.concurrency,$,"concurrency");let Q=new Set;for(let W of J.cases){if(Q.has(W.id))throw Error(`${$} has two cases with the id "${W.id}".`);Q.add(W.id)}let Z=new EJ(J);for(let[W,K]of Object.entries(Z.graders))if(typeof K!=="function"&&K.kind==="judge")XJ(K.samples,`${$}'s judge "${W}"`,"samples");return Z}static judge(J){return{...J,kind:"judge"}}static compare(J,$,Q={}){return yQ(J,$,Q)}static format(J,$={}){return x8(J,$)}async run(J={}){let $=`${this.name}.run`;XJ(J.runs,$,"runs"),XJ(J.concurrency,$,"concurrency");let Q=J.only?new Set(J.only):null;if(Q){let P=[...Q].filter((F)=>!this.cases.some((U)=>U.id===F));if(P.length>0)throw Error(`The eval "${this.name}" has no case ${P.map((F)=>`"${F}"`).join(", ")}.`)}let Z=J.runs??this.runs,W=Date.now(),K=new AbortController,X=J.signal?AbortSignal.any([J.signal,K.signal]):K.signal,G=this.cases.filter((P)=>!Q||Q.has(P.id)),V={};for(let[P,F]of Object.entries(this.graders)){if(X.aborted)break;if(typeof F==="function"||F.kind!=="judge"||!F.calibration)continue;V[P]=await this.calibrate(F,X)}let Y=G.flatMap((P)=>Array.from({length:Z},(F,U)=>({test:P,run:U+1}))),z=Array.from({length:Y.length}),D=0,N,H=async()=>{while(D<Y.length&&!X.aborted){let P=D++,F=Y[P],U=await this.sample(F.test,F.run,X,J.keepOutputs??!1);z[P]=U;try{J.onSample?.(U)}catch(L){N??={error:L},K.abort(L)}}},C=Math.min(J.concurrency??this.concurrency,Y.length);if(await Promise.all(Array.from({length:C},H)),N)throw N.error;let O=z.filter((P)=>P!==void 0);return this.report(O,V,Z,new Date(W).toISOString(),Date.now()-W,{aborted:X.aborted||O.length<Y.length,planned:G.map((P)=>P.id)})}async sample(J,$,Q,Z){let W=Date.now(),K,X,G=await GJ(async()=>{try{K=await this.task(J.input,{case:J,run:$,signal:Q})}catch(C){X=qQ(C)}}),V={},Y=!1,z=await GJ(async()=>{if(X!==void 0)return;let C={case:J,input:J.input,run:$};for(let[O,P]of Object.entries(this.graders)){if(J.skip?.includes(O))continue;let F=await jQ(P,K,C,Q);if(!F)continue;if(V[O]=F,!F.pass&&typeof P!=="function"&&P.gate)Y=!0}}),D=Object.values(V).map((C)=>C.score),N=X===void 0&&D.length===0,H=this.pricing?$$(this.pricing,G.byModel).cost+$$(this.pricing,z.byModel).cost:void 0;return{case:J.id,run:$,pass:X===void 0&&!N&&Object.values(V).every((C)=>C.pass),excluded:Y||N,...N?{ungraded:!0}:{},score:X!==void 0||N?0:bQ(D),grades:V,...X!==void 0?{error:X}:{},...Z&&X===void 0?{output:K}:{},usage:G.usage,byModel:T8(G.byModel,z.byModel),judgeUsage:z.usage,...H!==void 0?{cost:H}:{},durationMs:Date.now()-W}}async calibrate(J,$){let Q=J.calibration,Z=[],W=0,K=await GJ(async()=>{for(let[V,Y]of Q.examples.entries()){if($.aborted)break;let z=Y.id??`example-${V+1}`,D={case:{id:z,input:Y.input},input:Y.input,run:0},N=await jQ(J,Y.output,D,$),H=N?.pass??!1;if(H===Y.expected)W++;else Z.push({id:z,expected:Y.expected,got:H,...N?.note?{note:N.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(([,N])=>typeof N!=="function"&&N.gate).map(([N])=>N)),G={};for(let N of this.cases){let H=J.filter((C)=>C.case===N.id);if(H.length===0)continue;G[N.id]={...xQ(H),graders:IQ(H,X)}}let V=A(),Y=A(),z={};for(let N of J){V=T(V,N.usage),Y=T(Y,N.judgeUsage);for(let[H,C]of Object.entries(N.byModel))z[H]=T(z[H]??A(),C)}let D=this.pricing?$$(this.pricing,z):void 0;return{name:this.name,startedAt:Z,durationMs:W,runs:Q,aborted:K.aborted,planned:K.planned,samples:J,cases:G,graders:IQ(J,X),calibration:$,totals:{...xQ(J),usage:V,judgeUsage:Y,byModel:z,...D?{cost:D.cost}:{},unpriced:D?D.unpriced:Object.keys(z)}}}}async function jQ(J,$,Q,Z){let W=typeof J==="function"?0.5:J.threshold??0.5;try{if(typeof J==="function")return Q$(await J($,Q),W);if(J.kind!=="judge")return Q$(await J.check($,Q),W);return await k8(J,$,Q,W,Z)}catch(K){return{pass:!1,score:0,error:qQ(K)}}}async function k8(J,$,Q,Z,W){let K=await J.prompt($,Q),X=typeof K==="string"?{prompt:K}:K,G=[];for(let D=0;D<(J.samples??1)&&!W.aborted;D++){let N=await Z$({signal:W,provider:J.provider,...J.instructions!==void 0?{instructions:J.instructions}:{},...X,output:J.output,...J.reasoning!==void 0?{reasoning:J.reasoning}:{},...J.maxOutputTokens!==void 0?{maxOutputTokens:J.maxOutputTokens}:{},...J.temperature!==void 0?{temperature:J.temperature}:{},logErrors:!1});if(!N.ok){G.push({pass:!1,score:0,error:`The judge failed: ${N.error.message}`});continue}let H=Q$(J.verdict(N.output,Q),Z);if(H)G.push(H)}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),z=G.map((D)=>D.error).filter(Boolean);return{pass:V*2>G.length,score:bQ(G.map((D)=>D.score)),...Y.length>0?{note:Y.join(" | ")}:{},...z.length===G.length?{error:z.join(" | ")}:{}}}function Q$(J,$){if(J===null||J===void 0)return null;if(typeof J==="boolean")return{pass:J,score:J?1:0};if(typeof J==="number"){if(!Number.isFinite(J))throw Error(`A grader answered the score ${J}.`);let Q=wQ(J);return{pass:Q>=$,score:Q}}return{pass:J.pass,score:J.score===void 0?J.pass?1:0:wQ(J.score),...J.note!==void 0?{note:J.note}:{}}}function xQ(J){let $=J.filter((Q)=>!Q.excluded);return{samples:J.length,kept:$.length,passed:$.filter((Q)=>Q.pass).length,errors:J.filter((Q)=>Q.error!==void 0).length,passRate:eJ($.map((Q)=>Q.pass)),score:J$($.map((Q)=>Q.score))}}function IQ(J,$){let Q=J.filter((W)=>!W.excluded),Z=[...new Set(J.flatMap((W)=>Object.keys(W.grades)))];return Object.fromEntries(Z.map((W)=>{let X=($.has(W)?J:Q).flatMap((G)=>G.grades[W]?[G.grades[W]]:[]);return[W,{passRate:eJ(X.map((G)=>G.pass)),score:J$(X.map((G)=>G.score))}]}))}function $$(J,$){let Q=0,Z=[];for(let[W,K]of Object.entries($)){let X=fQ(J,W,K);if(X===void 0){Z.push(W);continue}Q+=X}return{cost:Q,unpriced:Z}}function T8(...J){let $={};for(let Q of J)for(let[Z,W]of Object.entries(Q))$[Z]=T($[Z]??A(),W);return $}function yQ(J,$,Q){for(let[P,F]of[["baseline",J],["current report",$]])if(F.aborted)throw Error(`Eval.compare: the ${P} for "${F.name}" was aborted (${F.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,F,U)=>{let L={label:P,passRate:EQ(F.passRate,U.passRate),score:kQ(F.score,U.score)};return K.push(L),{passRate:L.passRate,score:L.score}},G=(P,F,U)=>Object.fromEntries(Object.keys(U).filter((L)=>(L in F)).map((L)=>[L,X(`${P} ${L}`,F[L],U[L])])),V=(P,F)=>({fromCurrent:P.filter((U)=>!F.includes(U)),fromBaseline:F.filter((U)=>!P.includes(U))}),Y=X("total",J.totals,$.totals),z=G("case",J.cases,$.cases),D=G("grader",J.graders,$.graders),N=K.flatMap((P)=>[P.passRate,P.score]);TQ(N,Z,W);let H={cases:V([...new Set([...J.planned??[],...Object.keys(J.cases)])],[...new Set([...$.planned??[],...Object.keys($.cases)])]),graders:V(Object.keys(J.graders),Object.keys($.graders))},C=[...H.cases.fromCurrent.map((P)=>`case ${P}: in the baseline, missing from this report`),...H.graders.fromCurrent.map((P)=>`grader ${P}: in the baseline, missing from this report`)],O=[];for(let P of K)for(let[F,U]of[["pass rate",P.passRate],["score",P.score]]){if(!U.significant)continue;let L=`${P.label}: ${F} ${U.before.toFixed(2)} \u2192 ${U.after.toFixed(2)} (p = ${j8(U.pAdjusted)})`;(U.delta<0?C:O).push(L)}return{totals:Y,cases:z,graders:D,missing:H,comparisons:N.filter((P)=>P.p!==null).length,alpha:Z,adjust:W,regressions:C,improvements:O}}function j8(J){return J<0.001?"<0.001":J.toFixed(3)}function x8(J,$){let Q=$.baseline&&!$.baseline.aborted&&!J.aborted?yQ($.baseline,J,$):void 0,{totals:Z}=J,W=[];if(W.push(`eval ${J.name}: ${Z.samples} samples, ${Z.kept} kept, ${Z.passed} passed, ${Z.errors} errors (${(J.durationMs/1000).toFixed(1)}s)`),J.aborted)W.push(`ABORTED: only ${Z.samples} of the planned samples ran; not comparable.`);let K=(Y)=>{if(Y.n===0)return"-";let z=Y.mean.toFixed(2);if(Y.low===null||Y.high===null)return`${z} (${Y.n===1?"n=1":"no spread"})`;return`${z} [${Y.low.toFixed(2)}, ${Y.high.toFixed(2)}]`},X=(Y)=>Y?` ${Y.delta>=0?"+":""}${Y.delta.toFixed(2)}${Y.significant?"*":""}`:"",G=(Y,z)=>{let D=[0,1,2,3].map((H)=>Math.max(...[[Y,"n","pass rate","score"],...z].map((C)=>C[H].length))),N=(H)=>H.map((C,O)=>C.padEnd(D[O])).join(" ").trimEnd();W.push("",N([Y,"n","pass rate","score"]),...z.map(N))};G("case",Object.entries(J.cases).map(([Y,z])=>[Y,`${z.kept}/${z.samples}`,K(z.passRate)+X(Q?.cases[Y]?.passRate),K(z.score)+X(Q?.cases[Y]?.score)])),G("grader",Object.entries(J.graders).map(([Y,z])=>[Y,String(z.passRate.n),K(z.passRate)+X(Q?.graders[Y]?.passRate),K(z.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,z]of Object.entries(J.calibration))W.push(`judge ${Y}: agreement ${z.agreement.toFixed(2)} on ${z.n} examples${z.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(`
|
|
181
|
-
`)}function bQ(J){return J.reduce(($,Q)=>$+Q,0)/J.length}function wQ(J){return Math.min(1,Math.max(0,J))}function qQ(J){return J instanceof Error?J.message:String(J)}function XJ(J,$,Q){if(J===void 0||Number.isInteger(J)&&J>=1)return;throw Error(`${$} sets \`${Q}\` to ${String(J)}, but it has to be a whole number of at least 1.`)}var I8=/^[A-Za-z0-9_-]{1,64}$/;function w8(J,$){let Q=f8($)?$:{filter:$},Z=Q.deferred===!0,W=J.descriptors(Q.filter);if(!Q.namespaces)return W.map((z)=>W$(J,z,Z));let K=Object.entries(Q.namespaces),X=new Set(J.descriptors().flatMap((z)=>z.tags));for(let[z,D]of K){if(!I8.test(z))throw Error(`toAgentTools: "${z}" is not a valid namespace name. A namespace is named by its tag and sent to the provider as a tool name is \u2014 letters, digits, "_" and "-", at most 64.`);if(typeof D?.description!=="string"||D.description.trim()==="")throw Error(`toAgentTools: the namespace "${z}" needs a description. It is what the model reads to decide whether to look inside.`);if(!X.has(z))throw Error(`toAgentTools: no tool is tagged "${z}", so its namespace would be empty.`)}let G=new Map(K.map(([z])=>[z,[]])),V=[];for(let z of W){let D=K.find(([N])=>z.tags.includes(N))?.[0];if(D===void 0)V.push(W$(J,z,Z));else G.get(D).push(W$(J,z,!1))}let Y=[];for(let[z,D]of K){let N=G.get(z);if(N.length===0)continue;Y.push(K$.create({name:z,description:D.description,tools:N,deferred:D.deferred??Z}))}return[...Y,...V]}function f8(J){return typeof J==="object"&&J!==null&&(("filter"in J)||("namespaces"in J)||("deferred"in J))}function W$(J,$,Q){if($.kind==="tool")return y8(J,$,Q);return kJ.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:$.requiresApproval,deferred:Q,execute:(Z,W)=>{let K=c.getStore()?.req;if(!K)throw new m(`"${$.name}" calls an api route as the user who started this run, and this run was not started inside a request. Run it from an AgentController, or give this agent tools that do not go through the MCP registry.`);return J.execute({kind:"local",req:K},$.name,Z,W)}})}function y8(J,$,Q){let Z=J.nativeTool($.name);return kJ.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:J.nativeApproval($.name),deferred:Q,...Z.timeoutMs!==void 0?{timeoutMs:Z.timeoutMs}:{},...Z.async?{async:Z.async}:{},execute:(W,K)=>{let X=c.getStore()?.req;return J.startNative(X?{kind:"local",req:X}:void 0,$.name,W,K)}})}function b8(J){if(J==="auto")return;let $=/^(\d+)x(\d+)$/.exec(J);if(!$)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(J)}.`);let Q=Number($[1]),Z=Number($[2]);if(Q%16!==0||Z%16!==0)throw Error(`Image size ${J} is not supported: width and height must both be divisible by 16.`);if(Math.max(Q/Z,Z/Q)>3)throw Error(`Image size ${J} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function vQ(J,$){if(J.size!==void 0)try{b8(J.size)}catch(Q){throw Error(`${$}: ${Q.message}`)}if(J.background==="transparent"&&J.format==="jpeg")throw Error(`${$}: a transparent background needs "png"; JPEG has no alpha channel.`);if(J.compression!==void 0){let Q=J.compression;if(!Number.isInteger(Q)||Q<0||Q>100)throw Error(`${$}: compression is an integer from 0 to 100; got ${Q}.`)}}function hQ(J,$){if(J instanceof File)return J;let Q=J.type||"image/png",Z=Q==="image/jpeg"?"jpg":Q.split("/")[1]??"png";return new File([J],`${$}.${Z}`,{type:Q})}class X${name;provider;settings;constructor(J){let{name:$,provider:Q,...Z}=J;vQ(Z,`ImageModel "${$}"`),this.name=$,this.provider=Q,this.settings=Z}static create(J){return new X$(J)}async generate(J){let $=this.merge(J);return this.present(await this.provider.generate({prompt:J.prompt,...$,signal:J.signal}))}async edit(J){let $=this.merge(J);return this.present(await this.provider.edit({prompt:J.prompt,...$,images:J.images.map((Q,Z)=>hQ(Q,`image-${Z}`)),...J.mask?{mask:hQ(J.mask,"mask")}:{},signal:J.signal}))}present(J){return gQ(this.provider.model,J.usage),q8(J)}merge(J){let $={...this.settings,...J.size!==void 0?{size:J.size}:{},...J.quality!==void 0?{quality:J.quality}:{},...J.background!==void 0?{background:J.background}:{},...J.format!==void 0?{format:J.format}:{},...J.compression!==void 0?{compression:J.compression}:{}};return vQ($,`ImageModel "${this.name}"`),$}}function q8(J){return{image:new Blob([J.bytes],{type:J.mimeType}),mimeType:J.mimeType,size:J.size,usage:J.usage}}var G$=300000;function Y$(J){return{generationsUrl:`${J.base}/images/generations${J.query}`,editsUrl:`${J.base}/images/edits${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,maxRetries:J.maxRetries}}class TJ extends Error{code;retryable;retryAfter;constructor(J,$={}){super(J.message,$);if(this.name="ImageRequestError",this.code=J.code,this.retryable=J.retryable,J.retryAfter!==void 0)this.retryAfter=J.retryAfter}}var v8={png:"image/png",jpeg:"image/jpeg"};function h8(J){let $=Number(J?.input_tokens??0),Q=Number(J?.output_tokens??0),Z={inputTokens:$,outputTokens:Q,totalTokens:Number(J?.total_tokens??$+Q)},W=J?.input_tokens_details?.image_tokens;if(typeof W==="number")Z.imageInputTokens=W;let K=J?.output_tokens_details?.image_tokens;if(typeof K==="number")Z.imageOutputTokens=K;return Z}function g8(J){let $=atob(J),Q=new Uint8Array($.length);for(let Z=0;Z<$.length;Z++)Q[Z]=$.charCodeAt(Z);return Q}function u8(J){let Q=J?.data?.[0]?.b64_json;if(typeof Q!=="string"||Q.length===0)throw new TJ({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let Z=typeof J.output_format==="string"?J.output_format:"png";return{bytes:g8(Q),mimeType:v8[Z]??`image/${Z}`,size:typeof J.size==="string"?J.size:"",...typeof J.background==="string"?{background:J.background}:{},usage:h8(J.usage)}}async function cQ(J,$,Q,Z){let W;try{W=await uQ(J,$,{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,retryTimeouts:!1,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(K){if(Z.signal?.aborted)throw K;throw new TJ(a(K),{cause:K})}return u8(await W.json())}async function mQ(J,$,Q={}){return await cQ(J.generationsUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify($)},J,Q)}async function pQ(J,$,Q={}){return await cQ(J.editsUrl,{method:"POST",headers:await J.headers(),body:$},J,Q)}class jJ{static models(){return[]}modelName(){return this.model}async generate(J){return await mQ(this.endpoint(),this.body(J),{signal:J.signal})}async edit(J){let $=new FormData;for(let[Q,Z]of Object.entries(this.body(J)))if(Z!==void 0)$.set(Q,String(Z));for(let Q of J.images)$.append("image[]",Q,Q.name);if(J.mask)$.set("mask",J.mask,J.mask.name);return await pQ(this.endpoint(),$,{signal:J.signal})}body(J){return{model:this.modelName(),prompt:J.prompt,...J.size?{size:J.size}:{},...J.quality?{quality:J.quality}:{},...J.background?{background:J.background}:{},...J.format?{output_format:J.format}:{},...J.compression!==void 0?{output_compression:J.compression}:{}}}normalizeError(J){return a(J)}}var dQ=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class V$ extends jJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new V$(J,$)}static models(){return dQ}endpoint(){return Y$(lQ(this.config,{timeoutMs:G$}))}}class z$ extends jJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new z$(J,$)}static models(){return dQ}modelName(){return this.config.deployment??this.model}endpoint(){return Y$(iQ(this.config,{timeoutMs:G$}))}}class xJ{now;entries=new Map;constructor(J=Date.now){this.now=J}allow(J,$){let Q=this.entries.get(J);if(Q?.openUntil===void 0)return!0;let Z=this.now();if(Z<Q.openUntil)return!1;if(Q.probeUntil!==void 0&&Z<Q.probeUntil)return!1;return Q.probeUntil=Z+$.cooldownMs,!0}record(J,$,Q){let Z=this.entries.get(J)??{failures:0},W=Z.openUntil!==void 0;if($==="success")return this.entries.delete(J),W?"closed":void 0;if($==="none"){delete Z.probeUntil;return}if(Z.failures+=1,this.entries.set(J,Z),W||Z.failures>=Q.failures)return Z.openUntil=this.now()+Q.cooldownMs,delete Z.probeUntil,W?void 0:"open";return}state(J){let $=this.entries.get(J);if($?.openUntil===void 0)return"closed";return this.now()<$.openUntil?"open":"half-open"}}var oQ=Symbol("timed-out");class YJ extends P${model;capabilities;entries;options;circuit;constructor(J,$={}){super();if(J.length===0)throw Error("FallbackProvider needs at least one provider.");for(let Z of J)if(Z.timeoutMs!==void 0&&!(Z.timeoutMs>0))throw Error(`FallbackProvider: timeoutMs for ${Z.provider.model} must be a positive number, got ${Z.timeoutMs}.`);this.entries=[...J];let Q=$.circuit;if(Q){let Z=Q.failures??3,W=Q.cooldownMs??30000;if(!Number.isInteger(Z)||Z<1)throw Error(`FallbackProvider: circuit.failures must be a positive integer, got ${Z}.`);if(!(W>0))throw Error(`FallbackProvider: circuit.cooldownMs must be a positive number, got ${W}.`);let K=new Set;for(let G of J){let V=D$(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 xJ;this.options={...$,circuit:{...Q,store:X}},this.circuit={policy:{failures:Z,cooldownMs:W},store:X,...Q.onStateChange?{onStateChange:Q.onStateChange}:{}}}else this.options=$,this.circuit=void 0;this.model=J[0].provider.model,this.capabilities=c8(J.map((Z)=>Z.provider.capabilities))}static chain(J,$){return new YJ(J,$)}from(J){if(!Number.isInteger(J)||J<0||J>=this.entries.length)throw RangeError(`FallbackProvider.from(${J}): the chain has ${this.entries.length} entries.`);return new YJ(this.entries.slice(J),this.options)}leg(J){let $=this.from(J).entries[0];return new YJ([$],this.options)}upload(J){return this.entries[0].provider.upload(J)}deleteFile(J){let $=this.entries[0].provider;if(!$.deleteFile)return Promise.reject(Error(`${$.constructor.name} cannot delete provider files: it does not implement deleteFile().`));return $.deleteFile(J)}normalizeError(J){return this.entries[0].provider.normalizeError(J)}stream(J){return this.run(J)}async*run(J){let $,Q=J.signal,Z=0;for(let W=0;W<this.entries.length;W++){let K=this.entries[W],X=W===this.entries.length-1,G=K.provider.model;if(this.circuit&&!X&&!await this.allow(K))continue;Z+=1;let V=!1,Y=async(_)=>{if(V)return;V=!0,await this.record(W,K,_)},z=new AbortController,D=()=>z.abort(Q?.reason);if(Q?.aborted)z.abort(Q.reason);else Q?.addEventListener("abort",D,{once:!0});let N=[],H=!1,C=!1,O,P,F,U=!1,L,R=!1,E=(_)=>{let k=$?T(T(A(),$),_.usage):_.usage;return $=void 0,{..._,usage:k}};try{L=K.provider.stream({...J,...K.reasoning!==void 0?{reasoning:K.reasoning}:{},signal:z.signal})[Symbol.asyncIterator]();let _=K.timeoutMs!==void 0?Date.now()+K.timeoutMs:void 0;for(;;){let k=!H&&_!==void 0?await m8(L.next(),Math.max(0,_-Date.now())):await L.next();if(k===oQ){U=!0,F={error:{code:"provider_error",message:`${G} did not start answering within ${K.timeoutMs}ms.`,retryable:!0}};break}if(k.done){R=!0;break}let S=k.value;if(S.type==="finish"&&S.model)P=S.model;if(S.type==="retry"){yield S;continue}if(H){if(S.type==="finish")O=T(O??A(),S.usage),C=!0,yield E(S);else{if(S.type==="error")F={error:S.error};yield S}continue}if(nQ(S)){H=!0,await Y("success"),yield*N.splice(0),yield S;continue}if(S.type==="error")F={error:S.error,...t(S)};else if(S.type==="finish"){if(O=T(O??A(),S.usage),S.reason==="error"&&!F)F={error:{code:"provider_error",message:`${G} ended the call with an error and did not say which.`,retryable:!1}}}N.push(S)}}catch(_){let k=K.provider.normalizeError(_);if(H){if(k.code!=="aborted")yield{type:"error",error:k,...t(_)};this.report({index:W,model:G,responseModel:P,attempt:Z,usage:O,outcome:H$(k),error:k}),yield E({type:"finish",reason:k.code==="aborted"?"aborted":"error",usage:A(),...P?{model:P}:{}});return}F={error:k,...t(_)}}finally{if(Q?.removeEventListener("abort",D),!R)z.abort(),L?.return?.()?.catch(()=>{})}if(H){if(!C&&$)yield{type:"finish",reason:F?"error":"stop",usage:$},$=void 0;this.report({index:W,model:G,responseModel:P,attempt:Z,usage:O,outcome:F?H$(F.error):"ok",...F?{error:F.error}:{}});return}if(Q?.aborted){await Y("none"),this.report({index:W,model:G,responseModel:P,attempt:Z,usage:O,outcome:"aborted"}),yield E({type:"finish",reason:"aborted",usage:O??A(),...P?{model:P}:{}});return}if(!F){await Y("success"),this.report({index:W,model:G,responseModel:P,attempt:Z,usage:O,outcome:"ok"});for(let _ of N)yield _.type==="finish"?E(_):_;return}let j=!X&&F.error.code!=="aborted"&&this.shouldFallBack(F.error,{index:W,model:G,timedOut:U,...t(F)});if(await Y(j?"failure":"none"),this.report({index:W,model:G,responseModel:P,attempt:Z,usage:O,outcome:j?"fallback":H$(F.error),error:F.error}),j){if(O)$=T($??A(),O);continue}let x=!1,y;for(let _ of N){if(_.type==="finish"){y=_;continue}if(_.type==="error")x=!0;yield _}if(!x&&F.error.code!=="aborted")yield{type:"error",error:F.error,...t(F)};yield E({type:"finish",reason:F.error.code==="aborted"?"aborted":y?.reason??"error",usage:O??A(),...P?{model:P}:{}});return}}async allow(J){if(!this.circuit)return!0;try{return await this.circuit.store.allow(D$(J),this.circuit.policy)}catch{return!0}}async record(J,$,Q){if(!this.circuit)return;let Z=D$($),W;try{W=await this.circuit.store.record(Z,Q,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:J,model:$.provider.model,key:Z,state:W})}catch{}}shouldFallBack(J,$){let Q=this.options.fallbackOn??((Z)=>Z.retryable);try{return Q(J,$)}catch{return!1}}report(J){if(J.usage===void 0)delete J.usage;if(J.responseModel===void 0)delete J.responseModel;try{this.options.onUsage?.(J)}catch{}}}function D$(J){return J.circuitKey??J.provider.model}function H$(J){return J.code==="aborted"?"aborted":"failed"}function c8(J){return{reasoning:J.every(($)=>$.reasoning),structuredOutput:J.every(($)=>$.structuredOutput),fileInput:J.every(($)=>$.fileInput),parallelToolCalls:J.every(($)=>$.parallelToolCalls),toolSearch:J.every(($)=>$.toolSearch),supportsForcedToolChoice:J.every(($)=>$.supportsForcedToolChoice!==!1)}}function m8(J,$){let Q,Z=new Promise((W)=>{Q=setTimeout(()=>W(oQ),$)});return Promise.race([J,Z]).finally(()=>clearTimeout(Q))}async function p8(J,$,Q={}){let Z=Q.samples??1;if(!Number.isInteger(Z)||Z<1)throw RangeError(`evalChain: samples must be a positive integer, got ${Z}.`);let W=[];for(let K=0;K<J.entries.length;K++){let X=J.leg(K),G={index:K,model:X.model,results:[],errors:[]};for(let V=0;V<Z;V++)try{G.results.push(await $(X,{index:K,sample:V}))}catch(Y){G.errors.push({sample:V,error:Y})}W.push(G)}return W}class wJ extends Error{line;constructor(J){super(J??"Voice session ended by the app.");this.name="VoiceHangup",this.line=J}}var zJ="ask_agent",l8={maxDurationMs:900000,idleTimeoutMs:120000,maxQueued:3,progressIntervalMs:4000,closingLineMs:1e4,tickMs:60000,hangupGraceMs:30000,toolTimeoutMs:60000,maxToolCallsPerMinute:20,toolOutputChars:8000},i8={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 VJ(J={}){return[{name:J.name??zJ,description:J.description??"Hand one self-contained request to the agent that does the work, in the user's own words with references resolved. It can take minutes; the result comes back when it is done, so tell the user you are on it.",parameters:{type:"object",properties:{request:{type:"string",description:"What the user wants done."}},required:["request"],additionalProperties:!1}},{name:"stop_work",description:"Stop the work that is running, and drop any requests waiting behind it.",parameters:{type:"object",properties:{},additionalProperties:!1}},{name:"work_status",description:"What the agent is doing right now, and what is waiting.",parameters:{type:"object",properties:{},additionalProperties:!1}},{name:"answer_question",description:"Answer the question the agent asked (it came back from a request with status needs_input). For an approval, set approve.",parameters:{type:"object",properties:{answer:{type:"string",description:"The user's answer, in their words."},approve:{type:"boolean",description:"For an approval: whether the user approved."}},required:["answer"],additionalProperties:!1}}]}var IJ=new Map;class p{sessionId;threadId;callId;ended;params;sideband;hangupCall;limits;lines;delegateName;startedAt=Date.now();body;usage=A();transcription={usage:A(),seconds:0};hooks=Promise.resolve();pendingCreate;transcript=[];requests=[];toolCalls=[];toolHandlers=new Map;toolsRunning=0;toolCallTimes=[];errors=[];running;queue=[];pending=[];lastProgress;lastNoteAt=0;noteTimer;responseActive=!1;responseWanted=!1;ending;timers=[];idleTimer;tickTimer;resolveEnded;closingWaiter;static start(J){return new p(J)}static get(J){return IJ.get(J)}static async endAll(J){await Promise.all([...IJ.values()].map(($)=>$.end("hangup",J)))}constructor(J){this.params=J,this.sessionId=J.sessionId??crypto.randomUUID(),this.threadId=J.threadId,this.body=J.body??{},this.limits={...l8,...sQ(J.limits)},this.lines={...i8,...sQ(J.lines)},this.delegateName=J.delegate?.name??zJ;let $=new Set(VJ(J.delegate).map((Q)=>Q.name));for(let Q of J.tools??[]){if($.has(Q.tool.name)||this.toolHandlers.has(Q.tool.name))throw Error(`VoiceBridge: two tools are named "${Q.tool.name}".`);this.toolHandlers.set(Q.tool.name,Q)}if("realtime"in J.call){let{realtime:Q,callId:Z}=J.call;this.callId=Z,this.sideband=Q.sideband(Z),this.hangupCall=()=>this.sideband.hangup()}else this.callId=J.call.callId??J.call.sideband.callId,this.sideband=J.call.sideband,this.hangupCall=()=>this.sideband.hangup();this.ended=new Promise((Q)=>this.resolveEnded=Q),IJ.set(this.sessionId,this),this.timers.push(setTimeout(()=>void this.end("max_duration",this.lines.maxDuration),this.limits.maxDurationMs)),this.tickTimer=setInterval(()=>void this.tick(),this.limits.tickMs),this.touch(),this.listen()}setBody(J){this.body=J;let $=this.params.contextNote?.(J);if($)this.sideband.addNote($)}end(J="hangup",$){return this.ending??=this.finish(J,$??null)}async listen(){for await(let J of this.sideband){try{this.params.onEvent?.(J)}catch{}this.closingWaiter?.(J),await this.handle(J)}}async handle(J){switch(J.type){case"input_audio_buffer.speech_started":this.touch();return;case"response.created":this.responseActive=!0,this.pendingCreate=void 0,this.touch();return;case"response.done":{if(this.responseActive=!1,this.responseWanted&&!this.ending)this.responseWanted=!1,this.createResponse();let $=J.usage;if($){this.usage=T(this.usage,$);let Q=this.info();this.hook(()=>this.params.onUsage?.($,Q))}return}case"conversation.item.input_audio_transcription.completed":{let $=J;if(this.say("user",String($.transcript??"")),$.transcriptionUsage||$.transcriptionSeconds!==void 0){this.transcription={usage:$.transcriptionUsage?T(this.transcription.usage,$.transcriptionUsage):this.transcription.usage,seconds:this.transcription.seconds+($.transcriptionSeconds??0)};let Q=this.info(),Z={...$.transcriptionUsage?{usage:$.transcriptionUsage}:{},...$.transcriptionSeconds!==void 0?{seconds:$.transcriptionSeconds}:{}};this.hook(()=>this.params.onTranscriptionUsage?.(Z,Q))}return}case"response.output_audio_transcript.done":this.say("assistant",String(J.transcript??""));return;case"response.output_text.done":this.say("assistant",String(J.text??""));return;case"response.function_call_arguments.done":{let $=J;if(this.touch(),!this.ending)this.call($.call_id,$.name,$.arguments);return}case"session.updated":if(this.tampered(J.session))this.end("session_tampered",null);return;case"error":{let $=J.error;if(this.errors.push({code:$?.code,message:String($?.message??"")}),this.pendingCreate&&$?.event_id===this.pendingCreate)if(this.pendingCreate=void 0,$.code==="conversation_already_has_active_response")this.responseActive=!0,this.responseWanted=!0;else this.responseActive=!1;return}case"sideband.closed":{let $=J;if(!this.ending&&!$.byClient)this.end($.code===1000?"call_ended":"sideband_lost",null);return}}}say(J,$){if($.trim())this.transcript.push({role:J,text:$,at:Date.now()})}call(J,$,Q){let Z=d8(Q);if($===this.delegateName){let K=typeof Z.request==="string"?Z.request.trim():"";if(!K)return this.answer(J,{status:"error",message:"The request was empty."});return this.enqueue({record:{request:K,status:"queued"},turn:{text:K},callId:J})}let W=this.toolHandlers.get($);if(W)return void this.runTool(J,W,Z);switch($){case"stop_work":{let K=this.running;if(K)K.stopRequested=!0,K.handle?.stop({reason:"Stopped by voice."});let X=this.dropQueue();return this.answer(J,{stopped:Boolean(K),dropped:X})}case"work_status":return this.answer(J,{running:this.running?{request:this.running.record.request,step:this.lastProgress??"starting"}:null,queued:this.queue.map((K)=>K.record.request),...this.pending.length?{needsInput:this.questions()}:{}});case"answer_question":{if(!this.pending.length)return this.answer(J,{status:"error",message:"There is no open question."});let K=typeof Z.answer==="string"?Z.answer:"",X=typeof Z.approve==="boolean"?Z.approve:void 0,G=this.pending.map((V)=>n8(V,K,X));return this.pending=[],this.enqueue({record:{request:`(answer) ${K}`,status:"queued"},turn:{toolResults:G},callId:J})}default:return this.answer(J,{status:"error",message:`There is no tool called ${$}.`})}}enqueue(J){if(!this.running){this.requests.push(J.record),this.run(J);return}if(this.queue.length>=this.limits.maxQueued)return this.answer(J.callId,{status:"busy",message:"Too many requests are waiting. Ask the user to wait for the current one."});this.requests.push(J.record),this.queue.push(J),this.answer(J.callId,{status:"queued",position:this.queue.length,message:"It will start when the current request is done."}),J.callId=void 0}async run(J){this.running=J,J.record.status="running",this.lastProgress=void 0,this.pauseIdle();try{let $=new Set;await this.waitForThread($);let Q=await this.latestBody();while(!J.stopRequested&&await this.waitForThread($));if(J.stopRequested||this.ending){J.record.status="dropped",this.complete(J,{status:"stopped"});return}let Z;try{Z=await this.params.controller.startTurn({threadId:this.threadId,user:this.params.user,body:Q,turn:J.turn})}catch(K){J.record.status="refused",this.complete(J,{status:"refused",message:K instanceof Error?K.message:"The request could not be started."});return}J.handle=Z,J.record.runId=Z.runId,this.follow(Z);let W=await Z.result();if(J.record.status="done",J.record.finishReason=W.finishReason,W.finishReason==="awaiting-input"&&W.pending.length)this.pending=W.pending,this.complete(J,{status:"needs_input",text:W.text,questions:this.questions()});else if(W.finishReason==="error")this.complete(J,{status:"failed",message:W.error?.message??"The work failed."});else if(W.finishReason==="aborted")this.complete(J,{status:"stopped",text:W.text});else this.complete(J,{status:"done",text:W.text})}catch($){J.record.status="done",this.complete(J,{status:"failed",message:$ instanceof Error?$.message:"The work failed."})}finally{this.running=void 0,this.flushNote();let $=this.queue.shift();if($&&!this.ending)this.run($);else this.touch()}}async runTool(J,$,Q){let Z=$.tool.name,W=Date.now();if(this.toolCallTimes=this.toolCallTimes.filter((D)=>W-D<60000),this.toolCallTimes.length>=this.limits.maxToolCallsPerMinute){let D={name:Z,status:"busy"};this.toolCalls.push(D),this.answer(J,{status:"busy",message:"Too many tool calls in the last minute. Tell the user to wait a moment."});return}this.toolCallTimes.push(W);let K={name:Z,status:"running"};this.toolCalls.push(K),this.toolsRunning+=1,this.pauseIdle();let X=new AbortController,G=$.timeoutMs??this.limits.toolTimeoutMs,V,Y;try{let D=await Promise.race([$.run(Q,{sessionId:this.sessionId,signal:X.signal}),new Promise((N,H)=>{V=setTimeout(()=>{H(new m(`"${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 wJ){K.status="refused",K.message=D.message,this.end("usage",D.line??null);return}let N=D instanceof m?D.message:"The tool failed.";if(!(D instanceof m))console.error(`[gemi/ai] the voice tool "${Z}" threw.`,D);K.status="failed",K.message=N,Y={status:"failed",message:N}}finally{clearTimeout(V),K.durationMs=Date.now()-W,this.toolsRunning-=1,this.touch()}let z=this.info();if(this.hook(()=>this.params.onToolCall?.({...K},z)),!this.ending)this.answer(J,Y)}clip(J){let $;try{$=JSON.stringify(J)}catch{return String(J)}if($===void 0||$.length<=this.limits.toolOutputChars)return J;return`${$.slice(0,this.limits.toolOutputChars)}\u2026 (cut: ${$.length} characters in all)`}async waitForThread(J=new Set){let $=this.params.liveRuns;if(!$)return!1;let Q=await $.find({threadId:this.threadId}),Z=Q&&!J.has(Q.runId)?$.get(Q.runId):null;if(!Q||!Z)return!1;return J.add(Q.runId),await Z.result().catch(()=>{return}),!0}async latestBody(){let J=this.params.store;if(!J)return this.body;let $=await J.get(this.sessionId).catch(()=>null);if($)this.body=$.body;return this.body}async follow(J){let $=this.params.progress??o8();try{for await(let Q of J.run){let Z=$(Q);if(Z)this.note(Z)}}catch{}}complete(J,$){if(this.ending)return;if(J.callId)this.sideband.functionOutput(J.callId,$),J.callId=void 0;else this.sideband.addNote(`Update on the earlier request "${J.record.request}": ${JSON.stringify($)}`);this.respond()}answer(J,$){this.sideband.functionOutput(J,$),this.respond()}respond(){if(this.ending)return;if(this.responseActive){this.responseWanted=!0;return}this.responseActive=!0,this.createResponse()}createResponse(){let J=`gemi_voice_${crypto.randomUUID()}`;this.pendingCreate=J,this.sideband.send({type:"response.create",event_id:J})}questions(){return this.pending.map((J)=>({kind:J.kind,tool:String(J.name),input:J.input}))}dropQueue(){let J=this.queue.splice(0);for(let $ of J)$.record.status="dropped";return J.length}note(J){if(J===this.lastProgress)return;this.lastProgress=J;let $=this.lastNoteAt+this.limits.progressIntervalMs-Date.now();if($<=0)return this.flushNote();this.noteTimer??=setTimeout(()=>this.flushNote(),$)}flushNote(){if(this.noteTimer)clearTimeout(this.noteTimer);if(this.noteTimer=void 0,!this.lastProgress||this.ending||!this.running)return;this.lastNoteAt=Date.now(),this.sideband.addNote(`Progress on "${this.running.record.request}": ${this.lastProgress}`)}touch(){if(this.idleTimer)clearTimeout(this.idleTimer);if(this.idleTimer=void 0,this.running||this.toolsRunning>0||this.ending)return;this.idleTimer=setTimeout(()=>void this.end("idle",this.lines.idle),this.limits.idleTimeoutMs)}pauseIdle(){if(this.idleTimer)clearTimeout(this.idleTimer);this.idleTimer=void 0}info(){return{sessionId:this.sessionId,total:this.usage,elapsedMs:Date.now()-this.startedAt,transcription:this.transcription}}tick(){if(this.ending)return;let J=this.info();this.hook(()=>this.params.onTick?.(J))}hook(J){this.hooks=this.hooks.then(async()=>{try{await J()}catch($){if($ instanceof wJ)this.end("usage",$.line??null);else console.error("[gemi/ai] a voice hook threw; ending the call.",$),this.end("error",this.lines.error)}})}tampered(J){let $=this.params.session;if(!$||!J)return!1;if($.instructions!==void 0&&J.instructions!==void 0&&J.instructions!==$.instructions)return!0;if(Array.isArray(J.tools)){let Q=new Set([...VJ(this.params.delegate),...$.tools??[]].map((W)=>W.name)),Z=new Set(J.tools.map((W)=>String(W?.name)));if(Q.size!==Z.size||[...Q].some((W)=>!Z.has(W)))return!0}return!1}async finish(J,$){for(let X of this.timers)clearTimeout(X);if(this.idleTimer)clearTimeout(this.idleTimer);if(this.noteTimer)clearTimeout(this.noteTimer);if(this.tickTimer)clearInterval(this.tickTimer);if(this.dropQueue(),$&&(J!=="call_ended"&&J!=="sideband_lost"))await this.closingLine($);if(J!=="call_ended")await this.hangUp();else this.sideband.close();await this.hooks;let Z=Date.now(),W=Z-this.startedAt,K={sessionId:this.sessionId,...this.callId?{callId:this.callId}:{},threadId:this.threadId,reason:J,startedAt:this.startedAt,endedAt:Z,durationMs:W,seconds:Math.ceil(W/1000),usage:this.usage,transcription:this.transcription,transcript:this.transcript,requests:this.requests,toolCalls:this.toolCalls,errors:this.errors};IJ.delete(this.sessionId),await this.params.store?.update(this.sessionId,{endedAt:Z,endReason:J}).catch(()=>{return});try{await this.params.onEnd?.(K)}catch(X){console.error("[gemi/ai] a voice session's onEnd threw.",X)}return this.resolveEnded(K),K}async hangUp(){try{await this.hangupCall()}catch(J){console.error("[gemi/ai] a voice call could not be hung up; waiting for the vendor.",J),this.errors.push({code:"hangup_failed",message:J instanceof Error?J.message:String(J)});let $;await Promise.race([this.sideband.closed,new Promise((Q)=>$=setTimeout(Q,this.limits.hangupGraceMs))]),clearTimeout($),this.sideband.close()}}async closingLine(J){await new Promise(($)=>{let Q=`gemi_voice_closing_${crypto.randomUUID()}`,Z=`gemi_voice_cancel_${crypto.randomUUID()}`,W=this.responseActive?"cancelling":"asked",K,X=setTimeout(G,this.limits.closingLineMs);function G(){clearTimeout(X),$()}let V=()=>{W="asked",this.sideband.send({type:"response.create",event_id:Q,response:{instructions:`Say exactly this to the user, and nothing else: "${J}"`,tool_choice:"none"}})};if(this.closingWaiter=(Y)=>{let z=Y;if(z.type==="sideband.closed")return G();if(W==="cancelling"){if(z.type==="response.done"||z.type==="error"&&z.error?.event_id===Z)V();return}if(z.type==="error"&&z.error?.event_id===Q)return G();if(z.type==="response.created"&&!K){K=z.response?.id;return}let D=(N)=>!K||!N||N===K;if(z.type==="response.done"&&D(z.response?.id))W="playing";else if(z.type==="output_audio_buffer.stopped"&&W==="playing"&&D(z.response_id))G()},W==="cancelling")this.sideband.send({type:"response.cancel",event_id:Z});else V()}),this.closingWaiter=void 0}}function sQ(J){if(!J)return{};return Object.fromEntries(Object.entries(J).filter(([,$])=>$!==void 0))}function d8(J){try{let $=JSON.parse(J);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function n8(J,$,Q){let Z={toolCallId:J.toolCallId,signature:J.signature,...J.path?{path:J.path}:{}};if(J.kind==="question")return{...Z,output:$};if(J.kind==="approval")return{...Z,approve:Q===!0,...$?{reason:$}:{}};return{...Z,approve:!1,reason:"Not available in a voice call."}}function o8(){let J=new Set;return($)=>{if($.type==="tool-call"){if($.part.partial||$.resent||J.has($.part.toolCallId))return;return J.add($.part.toolCallId),`running ${String($.part.name)}`}if($.type==="tool-progress"){let Q=$.data;if(typeof Q==="string")return Q;if(Q&&typeof Q==="object")for(let Z of["message","label","title"]){let W=Q[Z];if(typeof W==="string"&&W)return W}}return}}var aQ="http://gemi.internal/__gemi__/voice/mcp";async function N$(J,$){if(!$.user)throw Error("Voice MCP tools run as the signed-in user, and this voice session has none. Give `mcp` only to a signed-in user's session.");let{registry:Q}=J,Z=J.scopes??Q.scopes().map((X)=>X.name),W=(X)=>({kind:"remote",req:X,principal:{user:$.user,via:"voice",id:`voice:${$.sessionId}`,scopes:Z}});return(await Q.available(W(tQ()),J.filter)).filter((X)=>!X.requiresApproval).map((X)=>({tool:{name:X.name,description:X.description,parameters:X.inputSchema},...J.timeoutMs!==void 0?{timeoutMs:J.timeoutMs}:{},run:(G,V)=>{let Y=tQ();return c.run(Y,async()=>{return await J.authorize?.({name:X.name,input:G,sessionId:V.sessionId}),Q.execute(W(Y),X.name,G,void 0,{signal:V.signal})},{user:$.user})}}))}function tQ(){return new I(new Request(aQ,{method:"POST"}),{},"api",new URL(aQ).pathname)}class F${records=new Map;retainEndedMs;constructor(J={}){this.retainEndedMs=J.retainEndedMs??600000}async create(J){this.sweep(),this.records.set(J.id,structuredClone(J))}async get(J){let $=this.records.get(J);return $?structuredClone($):null}async update(J,$){let Q=this.records.get(J);if(!Q)return;this.records.set(J,{...Q,...structuredClone($),id:J})}sweep(){let J=Date.now()-this.retainEndedMs;for(let[$,Q]of this.records)if(Q.endedAt!==void 0&&Q.endedAt<J)this.records.delete($)}}var O$=new F$;var rQ=new WeakMap,eQ=100;class U${threadsTable;messagesTable;scope=null;sql;dialect;connection;options;constructor(J,$={}){if(this.threadsTable=JZ($.threadsTable??"gemi_agent_threads","threads"),this.messagesTable=JZ($.messagesTable??"gemi_agent_messages","messages"),this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name,this.options=$,$.ttlMs!==void 0)WZ($.ttlMs,"ttlMs")}get expires(){return this.options.ttlMs!==void 0}forScope(J){if(typeof J!=="string"||J==="")throw TypeError("A DatabaseAgentStore scope is a non-empty string.");let $=new U$({sql:this.sql,dialect:this.dialect,name:this.connection},this.options);return $.scope=J,$}async createTable(){let J=t8(this.dialect,this.threadsTable,this.messagesTable);for(let $ of J)await this.sql.unsafe($);await this.addScopeColumns(),await this.addExpiryColumns()}async addExpiryColumns(){if(await this.hasColumn(this.threadsTable,"expires_at"))return;for(let J of e8(this.dialect,this.threadsTable))await this.sql.unsafe(J)}async addScopeColumns(){let J=r8(this.dialect,this.threadsTable,this.messagesTable);for(let[$,Q]of J){if(await this.hasColumn($,"scope"))continue;for(let Z of Q)await this.sql.unsafe(Z)}}async hasColumn(J,$){try{return await this.sql.unsafe(`SELECT ${$} FROM ${this.quote(J)} WHERE 1 = 0`),!0}catch{return!1}}async createThread(J={}){let $=crypto.randomUUID(),Q=J.userId===void 0||J.userId===null?null:String(J.userId),Z=this.expiryOf(J);return await this.run(async(W)=>{let K=this.clock(W);if(Z){let X=Z.at!==void 0?this.ms(W,Z.at):Z.ttlMs===null?null:W`${K} + ${this.ms(W,Z.ttlMs)}`,G=Z.slides&&Z.ttlMs!==null?this.ms(W,Z.ttlMs):null;if(this.scope===null)await W`
|
|
180
|
+
)`,`CREATE INDEX IF NOT EXISTS "${$}_scope_kind_created_at_idx" ON "${$}"("scope", "kind", "created_at")`,`CREATE INDEX IF NOT EXISTS "${$}_expires_at_idx" ON "${$}"("expires_at")`,`CREATE UNIQUE INDEX IF NOT EXISTS "${$}_scope_key_key" ON "${$}"("scope", "key")`]}var qQ={n:0,mean:0,stddev:0,low:null,high:null};function p(J){let $=[0.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-0.13857109526572012,0.000009984369578019572,0.00000015056327351493116];if(J<0.5)return Math.log(Math.PI/Math.sin(Math.PI*J))-p(1-J);J-=1;let Q=$[0],Z=J+7.5;for(let W=1;W<9;W++)Q+=$[W]/(J+W);return 0.5*Math.log(2*Math.PI)+(J+0.5)*Math.log(Z)-Z+Math.log(Q)}function fQ(J,$,Q){let W=1,X=1-(J+$)*Q/(J+1);if(Math.abs(X)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)X=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;X=1/X;let K=X;for(let G=1;G<=300;G++){let z=2*G,V=G*($-G)*Q/((J+z-1)*(J+z));if(X=1+V*X,Math.abs(X)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)X=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+V/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(X=1/X,K*=X*W,V=-(J+G)*(J+$+G)*Q/((J+z)*(J+z+1)),X=1+V*X,Math.abs(X)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)X=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+V/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;X=1/X;let Y=X*W;if(K*=Y,Math.abs(Y-1)<0.00000000000001)break}return K}function i8(J,$,Q){if(J<=0)return 0;if(J>=1)return 1;let Z=Math.exp(p($+Q)-p($)-p(Q)+$*Math.log(J)+Q*Math.log(1-J));return J<($+1)/($+Q+2)?Z*fQ($,Q,J)/$:1-Z*fQ(Q,$,1-J)/Q}function W$(J,$){return i8($/($+J*J),$/2,0.5)}function d8(J){if(!(J>0))return Number.POSITIVE_INFINITY;let $=1.959964,Q=2;while(W$(Q,J)>0.05)Q*=2;for(let Z=0;Z<100;Z++){let W=($+Q)/2;if(W$(W,J)>0.05)$=W;else Q=W}return($+Q)/2}function n8(J,$,Q,Z){let W=J+Q,X=$+Z,K=(Y,D)=>p(Y+1)-p(D+1)-p(Y-D+1),G=(Y)=>Math.exp(K($,Y)+K(Z,W-Y)-K(X,W)),z=G(J),V=0;for(let Y=Math.max(0,W-Z);Y<=Math.min($,W);Y++){let D=G(Y);if(D<=z*1.0000001)V+=D}return Math.min(1,V)}function bQ(J,$){if(J.length<2)return 0;let Q=J.reduce((W,X)=>W+(X-$)**2,0),Z=Math.sqrt(Q/(J.length-1));return Z<0.000000000001*Math.max(1,Math.abs($))?0:Z}function X$(J){let $=J.length;if($===0)return qQ;let Q=J.map((G)=>G?1:0),Z=Q.reduce((G,z)=>G+z,0)/$,W=3.841458881296,X=(Z+W/(2*$))/(1+W/$),K=1.959964*Math.sqrt(Z*(1-Z)/$+W/(4*$*$))/(1+W/$);return{n:$,mean:Z,stddev:bQ(Q,Z),low:Math.max(0,X-K),high:Math.min(1,X+K)}}function K$(J){let $=J.length;if($===0)return qQ;let Q=J.reduce((X,K)=>X+K,0)/$,Z=bQ(J,Q);if($<2||Z===0)return{n:$,mean:Q,stddev:Z,low:null,high:null};let W=d8($-1)*Z/Math.sqrt($);return{n:$,mean:Q,stddev:Z,low:Q-W,high:Q+W}}function VJ(J,$,Q){return{before:J.mean,after:$.mean,delta:$.mean-J.mean,p:Q,pAdjusted:Q,significant:!1}}function vQ(J,$){if(J.n===0||$.n===0)return VJ(J,$,null);let Q=(Z)=>Math.round(Z.mean*Z.n);return VJ(J,$,n8(Q(J),J.n,Q($),$.n))}function yQ(J,$){if(J.n<2||$.n<2)return VJ(J,$,null);let Q=J.stddev**2/J.n,Z=$.stddev**2/$.n,W=Math.sqrt(Q+Z);if(W===0)return VJ(J,$,null);let X=(Q+Z)**2/(Q**2/(J.n-1)+Z**2/($.n-1));return VJ(J,$,W$(($.mean-J.mean)/W,X))}function hQ(J,$,Q){if(Q==="holm"){let Z=J.filter((X)=>X.p!==null).sort((X,K)=>X.p-K.p),W=0;Z.forEach((X,K)=>{W=Math.max(W,Math.min(1,X.p*(Z.length-K))),X.pAdjusted=W})}else for(let Z of J)Z.pAdjusted=Z.p;for(let Z of J)Z.significant=Z.pAdjusted!==null&&Z.pAdjusted<$&&Z.delta!==0}class IJ{name;cases;runs;concurrency;graders;pricing;task;constructor(J){this.name=J.name,this.cases=J.cases,this.runs=J.runs??1,this.concurrency=J.concurrency??1,this.task=J.task,this.graders=typeof J.graders==="function"?J.graders({judge:($)=>IJ.judge($)}):J.graders,this.pricing=J.pricing}static create(J){let $=`The eval "${J.name}"`;zJ(J.runs,$,"runs"),zJ(J.concurrency,$,"concurrency");let Q=new Set;for(let W of J.cases){if(Q.has(W.id))throw Error(`${$} has two cases with the id "${W.id}".`);Q.add(W.id)}let Z=new IJ(J);for(let[W,X]of Object.entries(Z.graders))if(typeof X!=="function"&&X.kind==="judge")zJ(X.samples,`${$}'s judge "${W}"`,"samples");return Z}static judge(J){return{...J,kind:"judge"}}static compare(J,$,Q={}){return lQ(J,$,Q)}static format(J,$={}){return t8(J,$)}async run(J={}){let $=`${this.name}.run`;zJ(J.runs,$,"runs"),zJ(J.concurrency,$,"concurrency");let Q=J.only?new Set(J.only):null;if(Q){let N=[...Q].filter((F)=>!this.cases.some((U)=>U.id===F));if(N.length>0)throw Error(`The eval "${this.name}" has no case ${N.map((F)=>`"${F}"`).join(", ")}.`)}let Z=J.runs??this.runs,W=Date.now(),X=new AbortController,K=J.signal?AbortSignal.any([J.signal,X.signal]):X.signal,G=this.cases.filter((N)=>!Q||Q.has(N.id)),z={};for(let[N,F]of Object.entries(this.graders)){if(K.aborted)break;if(typeof F==="function"||F.kind!=="judge"||!F.calibration)continue;z[N]=await this.calibrate(F,K)}let V=G.flatMap((N)=>Array.from({length:Z},(F,U)=>({test:N,run:U+1}))),Y=Array.from({length:V.length}),D=0,P,H=async()=>{while(D<V.length&&!K.aborted){let N=D++,F=V[N],U=await this.sample(F.test,F.run,K,J.keepOutputs??!1);Y[N]=U;try{J.onSample?.(U)}catch(_){P??={error:_},X.abort(_)}}},O=Math.min(J.concurrency??this.concurrency,V.length);if(await Promise.all(Array.from({length:O},H)),P)throw P.error;let C=Y.filter((N)=>N!==void 0);return this.report(C,z,Z,new Date(W).toISOString(),Date.now()-W,{aborted:K.aborted||C.length<V.length,planned:G.map((N)=>N.id)})}async sample(J,$,Q,Z){let W=Date.now(),X,K,G=await YJ(async()=>{try{X=await this.task(J.input,{case:J,run:$,signal:Q})}catch(O){K=dQ(O)}}),z={},V=!1,Y=await YJ(async()=>{if(K!==void 0)return;let O={case:J,input:J.input,run:$};for(let[C,N]of Object.entries(this.graders)){if(J.skip?.includes(C))continue;let F=await gQ(N,X,O,Q);if(!F)continue;if(z[C]=F,!F.pass&&typeof N!=="function"&&N.gate)V=!0}}),D=Object.values(z).map((O)=>O.score),P=K===void 0&&D.length===0,H=this.pricing?G$(this.pricing,G.byModel).cost+G$(this.pricing,Y.byModel).cost:void 0;return{case:J.id,run:$,pass:K===void 0&&!P&&Object.values(z).every((O)=>O.pass),excluded:V||P,...P?{ungraded:!0}:{},score:K!==void 0||P?0:iQ(D),grades:z,...K!==void 0?{error:K}:{},...Z&&K===void 0?{output:X}:{},usage:G.usage,byModel:s8(G.byModel,Y.byModel),judgeUsage:Y.usage,...H!==void 0?{cost:H}:{},durationMs:Date.now()-W}}async calibrate(J,$){let Q=J.calibration,Z=[],W=0,X=await YJ(async()=>{for(let[z,V]of Q.examples.entries()){if($.aborted)break;let Y=V.id??`example-${z+1}`,D={case:{id:Y,input:V.input},input:V.input,run:0},P=await gQ(J,V.output,D,$),H=P?.pass??!1;if(H===V.expected)W++;else Z.push({id:Y,expected:V.expected,got:H,...P?.note?{note:P.note}:{}})}}),K=Q.examples.length,G=K===0?1:W/K;return{n:K,agreement:G,ok:G>=(Q.minAgreement??0.8),disagreements:Z,usage:X.usage}}report(J,$,Q,Z,W,X){let K=new Set(Object.entries(this.graders).filter(([,P])=>typeof P!=="function"&&P.gate).map(([P])=>P)),G={};for(let P of this.cases){let H=J.filter((O)=>O.case===P.id);if(H.length===0)continue;G[P.id]={...cQ(H),graders:uQ(H,K)}}let z=R(),V=R(),Y={};for(let P of J){z=j(z,P.usage),V=j(V,P.judgeUsage);for(let[H,O]of Object.entries(P.byModel))Y[H]=j(Y[H]??R(),O)}let D=this.pricing?G$(this.pricing,Y):void 0;return{name:this.name,startedAt:Z,durationMs:W,runs:Q,aborted:X.aborted,planned:X.planned,samples:J,cases:G,graders:uQ(J,K),calibration:$,totals:{...cQ(J),usage:z,judgeUsage:V,byModel:Y,...D?{cost:D.cost}:{},unpriced:D?D.unpriced:Object.keys(Y)}}}}async function gQ(J,$,Q,Z){let W=typeof J==="function"?0.5:J.threshold??0.5;try{if(typeof J==="function")return V$(await J($,Q),W);if(J.kind!=="judge")return V$(await J.check($,Q),W);return await o8(J,$,Q,W,Z)}catch(X){return{pass:!1,score:0,error:dQ(X)}}}async function o8(J,$,Q,Z,W){let X=await J.prompt($,Q),K=typeof X==="string"?{prompt:X}:X,G=[];for(let D=0;D<(J.samples??1)&&!W.aborted;D++){let P=await z$({signal:W,provider:J.provider,...J.instructions!==void 0?{instructions:J.instructions}:{},...K,output:J.output,...J.reasoning!==void 0?{reasoning:J.reasoning}:{},...J.maxOutputTokens!==void 0?{maxOutputTokens:J.maxOutputTokens}:{},...J.temperature!==void 0?{temperature:J.temperature}:{},logErrors:!1});if(!P.ok){G.push({pass:!1,score:0,error:`The judge failed: ${P.error.message}`});continue}let H=V$(J.verdict(P.output,Q),Z);if(H)G.push(H)}if(G.length===0)return null;if(G.length===1)return G[0];let z=G.filter((D)=>D.pass).length,V=G.map((D)=>D.note??D.error).filter(Boolean),Y=G.map((D)=>D.error).filter(Boolean);return{pass:z*2>G.length,score:iQ(G.map((D)=>D.score)),...V.length>0?{note:V.join(" | ")}:{},...Y.length===G.length?{error:Y.join(" | ")}:{}}}function V$(J,$){if(J===null||J===void 0)return null;if(typeof J==="boolean")return{pass:J,score:J?1:0};if(typeof J==="number"){if(!Number.isFinite(J))throw Error(`A grader answered the score ${J}.`);let Q=mQ(J);return{pass:Q>=$,score:Q}}return{pass:J.pass,score:J.score===void 0?J.pass?1:0:mQ(J.score),...J.note!==void 0?{note:J.note}:{}}}function cQ(J){let $=J.filter((Q)=>!Q.excluded);return{samples:J.length,kept:$.length,passed:$.filter((Q)=>Q.pass).length,errors:J.filter((Q)=>Q.error!==void 0).length,passRate:X$($.map((Q)=>Q.pass)),score:K$($.map((Q)=>Q.score))}}function uQ(J,$){let Q=J.filter((W)=>!W.excluded),Z=[...new Set(J.flatMap((W)=>Object.keys(W.grades)))];return Object.fromEntries(Z.map((W)=>{let K=($.has(W)?J:Q).flatMap((G)=>G.grades[W]?[G.grades[W]]:[]);return[W,{passRate:X$(K.map((G)=>G.pass)),score:K$(K.map((G)=>G.score))}]}))}function G$(J,$){let Q=0,Z=[];for(let[W,X]of Object.entries($)){let K=pQ(J,W,X);if(K===void 0){Z.push(W);continue}Q+=K}return{cost:Q,unpriced:Z}}function s8(...J){let $={};for(let Q of J)for(let[Z,W]of Object.entries(Q))$[Z]=j($[Z]??R(),W);return $}function lQ(J,$,Q){for(let[N,F]of[["baseline",J],["current report",$]])if(F.aborted)throw Error(`Eval.compare: the ${N} for "${F.name}" was aborted (${F.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",X=[],K=(N,F,U)=>{let _={label:N,passRate:vQ(F.passRate,U.passRate),score:yQ(F.score,U.score)};return X.push(_),{passRate:_.passRate,score:_.score}},G=(N,F,U)=>Object.fromEntries(Object.keys(U).filter((_)=>(_ in F)).map((_)=>[_,K(`${N} ${_}`,F[_],U[_])])),z=(N,F)=>({fromCurrent:N.filter((U)=>!F.includes(U)),fromBaseline:F.filter((U)=>!N.includes(U))}),V=K("total",J.totals,$.totals),Y=G("case",J.cases,$.cases),D=G("grader",J.graders,$.graders),P=X.flatMap((N)=>[N.passRate,N.score]);hQ(P,Z,W);let H={cases:z([...new Set([...J.planned??[],...Object.keys(J.cases)])],[...new Set([...$.planned??[],...Object.keys($.cases)])]),graders:z(Object.keys(J.graders),Object.keys($.graders))},O=[...H.cases.fromCurrent.map((N)=>`case ${N}: in the baseline, missing from this report`),...H.graders.fromCurrent.map((N)=>`grader ${N}: in the baseline, missing from this report`)],C=[];for(let N of X)for(let[F,U]of[["pass rate",N.passRate],["score",N.score]]){if(!U.significant)continue;let _=`${N.label}: ${F} ${U.before.toFixed(2)} \u2192 ${U.after.toFixed(2)} (p = ${a8(U.pAdjusted)})`;(U.delta<0?O:C).push(_)}return{totals:V,cases:Y,graders:D,missing:H,comparisons:P.filter((N)=>N.p!==null).length,alpha:Z,adjust:W,regressions:O,improvements:C}}function a8(J){return J<0.001?"<0.001":J.toFixed(3)}function t8(J,$){let Q=$.baseline&&!$.baseline.aborted&&!J.aborted?lQ($.baseline,J,$):void 0,{totals:Z}=J,W=[];if(W.push(`eval ${J.name}: ${Z.samples} samples, ${Z.kept} kept, ${Z.passed} passed, ${Z.errors} errors (${(J.durationMs/1000).toFixed(1)}s)`),J.aborted)W.push(`ABORTED: only ${Z.samples} of the planned samples ran; not comparable.`);let X=(V)=>{if(V.n===0)return"-";let Y=V.mean.toFixed(2);if(V.low===null||V.high===null)return`${Y} (${V.n===1?"n=1":"no spread"})`;return`${Y} [${V.low.toFixed(2)}, ${V.high.toFixed(2)}]`},K=(V)=>V?` ${V.delta>=0?"+":""}${V.delta.toFixed(2)}${V.significant?"*":""}`:"",G=(V,Y)=>{let D=[0,1,2,3].map((H)=>Math.max(...[[V,"n","pass rate","score"],...Y].map((O)=>O[H].length))),P=(H)=>H.map((O,C)=>O.padEnd(D[C])).join(" ").trimEnd();W.push("",P([V,"n","pass rate","score"]),...Y.map(P))};G("case",Object.entries(J.cases).map(([V,Y])=>[V,`${Y.kept}/${Y.samples}`,X(Y.passRate)+K(Q?.cases[V]?.passRate),X(Y.score)+K(Q?.cases[V]?.score)])),G("grader",Object.entries(J.graders).map(([V,Y])=>[V,String(Y.passRate.n),X(Y.passRate)+K(Q?.graders[V]?.passRate),X(Y.score)+K(Q?.graders[V]?.score)])),W.push("",`total pass rate ${X(Z.passRate)}${K(Q?.totals.passRate)} score ${X(Z.score)}${K(Q?.totals.score)}`);for(let[V,Y]of Object.entries(J.calibration))W.push(`judge ${V}: agreement ${Y.agreement.toFixed(2)} on ${Y.n} examples${Y.ok?"":" (BELOW minAgreement)"}`);let z=(V)=>`${V.inputTokens} in, ${V.outputTokens} out`;if(W.push(`tokens: task ${z(Z.usage)}; judges ${z(Z.judgeUsage)}${Z.cost!==void 0?`; cost $${Z.cost.toFixed(4)}`:""}${Z.unpriced.length>0&&Z.cost!==void 0?` (unpriced: ${Z.unpriced.join(", ")})`:""}`),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 V of Q.regressions)W.push(`regression: ${V}`);for(let V of Q.improvements)W.push(`improvement: ${V}`)}return W.join(`
|
|
181
|
+
`)}function iQ(J){return J.reduce(($,Q)=>$+Q,0)/J.length}function mQ(J){return Math.min(1,Math.max(0,J))}function dQ(J){return J instanceof Error?J.message:String(J)}function zJ(J,$,Q){if(J===void 0||Number.isInteger(J)&&J>=1)return;throw Error(`${$} sets \`${Q}\` to ${String(J)}, but it has to be a whole number of at least 1.`)}var r8=/^[A-Za-z0-9_-]{1,64}$/;function e8(J,$){let Q=J9($)?$:{filter:$},Z=Q.deferred===!0,W=J.descriptors(Q.filter);if(!Q.namespaces)return W.map((Y)=>Y$(J,Y,Z));let X=Object.entries(Q.namespaces),K=new Set(J.descriptors().flatMap((Y)=>Y.tags));for(let[Y,D]of X){if(!r8.test(Y))throw Error(`toAgentTools: "${Y}" is not a valid namespace name. A namespace is named by its tag and sent to the provider as a tool name is \u2014 letters, digits, "_" and "-", at most 64.`);if(typeof D?.description!=="string"||D.description.trim()==="")throw Error(`toAgentTools: the namespace "${Y}" needs a description. It is what the model reads to decide whether to look inside.`);if(!K.has(Y))throw Error(`toAgentTools: no tool is tagged "${Y}", so its namespace would be empty.`)}let G=new Map(X.map(([Y])=>[Y,[]])),z=[];for(let Y of W){let D=X.find(([P])=>Y.tags.includes(P))?.[0];if(D===void 0)z.push(Y$(J,Y,Z));else G.get(D).push(Y$(J,Y,!1))}let V=[];for(let[Y,D]of X){let P=G.get(Y);if(P.length===0)continue;V.push(D$.create({name:Y,description:D.description,tools:P,deferred:D.deferred??Z}))}return[...V,...z]}function J9(J){return typeof J==="object"&&J!==null&&(("filter"in J)||("namespaces"in J)||("deferred"in J))}function Y$(J,$,Q){if($.kind==="tool")return $9(J,$,Q);return fJ.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:$.requiresApproval,deferred:Q,execute:(Z,W)=>{let X=l.getStore()?.req;if(!X)throw new i(`"${$.name}" calls an api route as the user who started this run, and this run was not started inside a request. Run it from an AgentController, or give this agent tools that do not go through the MCP registry.`);return J.execute({kind:"local",req:X},$.name,Z,W)}})}function $9(J,$,Q){let Z=J.nativeTool($.name);return fJ.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:J.nativeApproval($.name),deferred:Q,...Z.timeoutMs!==void 0?{timeoutMs:Z.timeoutMs}:{},...Z.async?{async:Z.async}:{},execute:(W,X)=>{let K=l.getStore()?.req;return J.startNative(K?{kind:"local",req:K}:void 0,$.name,W,X)}})}function Q9(J){if(J==="auto")return;let $=/^(\d+)x(\d+)$/.exec(J);if(!$)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(J)}.`);let Q=Number($[1]),Z=Number($[2]);if(Q%16!==0||Z%16!==0)throw Error(`Image size ${J} is not supported: width and height must both be divisible by 16.`);if(Math.max(Q/Z,Z/Q)>3)throw Error(`Image size ${J} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function nQ(J,$){if(J.size!==void 0)try{Q9(J.size)}catch(Q){throw Error(`${$}: ${Q.message}`)}if(J.background==="transparent"&&J.format==="jpeg")throw Error(`${$}: a transparent background needs "png"; JPEG has no alpha channel.`);if(J.compression!==void 0){let Q=J.compression;if(!Number.isInteger(Q)||Q<0||Q>100)throw Error(`${$}: compression is an integer from 0 to 100; got ${Q}.`)}}function oQ(J,$){if(J instanceof File)return J;let Q=J.type||"image/png",Z=Q==="image/jpeg"?"jpg":Q.split("/")[1]??"png";return new File([J],`${$}.${Z}`,{type:Q})}class H${name;provider;settings;constructor(J){let{name:$,provider:Q,...Z}=J;nQ(Z,`ImageModel "${$}"`),this.name=$,this.provider=Q,this.settings=Z}static create(J){return new H$(J)}async generate(J){let $=this.merge(J);return this.present(await this.provider.generate({prompt:J.prompt,...$,signal:J.signal}))}async edit(J){let $=this.merge(J);return this.present(await this.provider.edit({prompt:J.prompt,...$,images:J.images.map((Q,Z)=>oQ(Q,`image-${Z}`)),...J.mask?{mask:oQ(J.mask,"mask")}:{},signal:J.signal}))}present(J){return sQ(this.provider.model,J.usage),Z9(J)}merge(J){let $={...this.settings,...J.size!==void 0?{size:J.size}:{},...J.quality!==void 0?{quality:J.quality}:{},...J.background!==void 0?{background:J.background}:{},...J.format!==void 0?{format:J.format}:{},...J.compression!==void 0?{compression:J.compression}:{}};return nQ($,`ImageModel "${this.name}"`),$}}function Z9(J){return{image:new Blob([J.bytes],{type:J.mimeType}),mimeType:J.mimeType,size:J.size,usage:J.usage}}var P$=300000;function N$(J){return{generationsUrl:`${J.base}/images/generations${J.query}`,editsUrl:`${J.base}/images/edits${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,maxRetries:J.maxRetries}}class qJ extends Error{code;retryable;retryAfter;constructor(J,$={}){super(J.message,$);if(this.name="ImageRequestError",this.code=J.code,this.retryable=J.retryable,J.retryAfter!==void 0)this.retryAfter=J.retryAfter}}var W9={png:"image/png",jpeg:"image/jpeg"};function X9(J){let $=Number(J?.input_tokens??0),Q=Number(J?.output_tokens??0),Z={inputTokens:$,outputTokens:Q,totalTokens:Number(J?.total_tokens??$+Q)},W=J?.input_tokens_details?.image_tokens;if(typeof W==="number")Z.imageInputTokens=W;let X=J?.output_tokens_details?.image_tokens;if(typeof X==="number")Z.imageOutputTokens=X;return Z}function K9(J){let $=atob(J),Q=new Uint8Array($.length);for(let Z=0;Z<$.length;Z++)Q[Z]=$.charCodeAt(Z);return Q}function G9(J){let Q=J?.data?.[0]?.b64_json;if(typeof Q!=="string"||Q.length===0)throw new qJ({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let Z=typeof J.output_format==="string"?J.output_format:"png";return{bytes:K9(Q),mimeType:W9[Z]??`image/${Z}`,size:typeof J.size==="string"?J.size:"",...typeof J.background==="string"?{background:J.background}:{},usage:X9(J.usage)}}async function tQ(J,$,Q,Z){let W;try{W=await aQ(J,$,{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,retryTimeouts:!1,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(X){if(Z.signal?.aborted)throw X;throw new qJ($J(X),{cause:X})}return G9(await W.json())}async function rQ(J,$,Q={}){return await tQ(J.generationsUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify($)},J,Q)}async function eQ(J,$,Q={}){return await tQ(J.editsUrl,{method:"POST",headers:await J.headers(),body:$},J,Q)}class bJ{static models(){return[]}modelName(){return this.model}async generate(J){return await rQ(this.endpoint(),this.body(J),{signal:J.signal})}async edit(J){let $=new FormData;for(let[Q,Z]of Object.entries(this.body(J)))if(Z!==void 0)$.set(Q,String(Z));for(let Q of J.images)$.append("image[]",Q,Q.name);if(J.mask)$.set("mask",J.mask,J.mask.name);return await eQ(this.endpoint(),$,{signal:J.signal})}body(J){return{model:this.modelName(),prompt:J.prompt,...J.size?{size:J.size}:{},...J.quality?{quality:J.quality}:{},...J.background?{background:J.background}:{},...J.format?{output_format:J.format}:{},...J.compression!==void 0?{output_compression:J.compression}:{}}}normalizeError(J){return $J(J)}}var QZ=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class F$ extends bJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new F$(J,$)}static models(){return QZ}endpoint(){return N$(JZ(this.config,{timeoutMs:P$}))}}class U$ extends bJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new U$(J,$)}static models(){return QZ}modelName(){return this.config.deployment??this.model}endpoint(){return N$($Z(this.config,{timeoutMs:P$}))}}class vJ{now;entries=new Map;constructor(J=Date.now){this.now=J}allow(J,$){let Q=this.entries.get(J);if(Q?.openUntil===void 0)return!0;let Z=this.now();if(Z<Q.openUntil)return!1;if(Q.probeUntil!==void 0&&Z<Q.probeUntil)return!1;return Q.probeUntil=Z+$.cooldownMs,!0}record(J,$,Q){let Z=this.entries.get(J)??{failures:0},W=Z.openUntil!==void 0;if($==="success")return this.entries.delete(J),W?"closed":void 0;if($==="none"){delete Z.probeUntil;return}if(Z.failures+=1,this.entries.set(J,Z),W||Z.failures>=Q.failures)return Z.openUntil=this.now()+Q.cooldownMs,delete Z.probeUntil,W?void 0:"open";return}state(J){let $=this.entries.get(J);if($?.openUntil===void 0)return"closed";return this.now()<$.openUntil?"open":"half-open"}}var WZ=Symbol("timed-out");class DJ extends _${model;capabilities;entries;options;circuit;constructor(J,$={}){super();if(J.length===0)throw Error("FallbackProvider needs at least one provider.");for(let Z of J)if(Z.timeoutMs!==void 0&&!(Z.timeoutMs>0))throw Error(`FallbackProvider: timeoutMs for ${Z.provider.model} must be a positive number, got ${Z.timeoutMs}.`);this.entries=[...J];let Q=$.circuit;if(Q){let Z=Q.failures??3,W=Q.cooldownMs??30000;if(!Number.isInteger(Z)||Z<1)throw Error(`FallbackProvider: circuit.failures must be a positive integer, got ${Z}.`);if(!(W>0))throw Error(`FallbackProvider: circuit.cooldownMs must be a positive number, got ${W}.`);let X=new Set;for(let G of J){let z=C$(G);if(X.has(z))throw Error(`FallbackProvider: two legs share the circuit key "${z}". Give one of them a \`circuitKey\`.`);X.add(z)}let K=Q.store??new vJ;this.options={...$,circuit:{...Q,store:K}},this.circuit={policy:{failures:Z,cooldownMs:W},store:K,...Q.onStateChange?{onStateChange:Q.onStateChange}:{}}}else this.options=$,this.circuit=void 0;this.model=J[0].provider.model,this.capabilities=V9(J.map((Z)=>Z.provider.capabilities))}static chain(J,$){return new DJ(J,$)}from(J){if(!Number.isInteger(J)||J<0||J>=this.entries.length)throw RangeError(`FallbackProvider.from(${J}): the chain has ${this.entries.length} entries.`);return new DJ(this.entries.slice(J),this.options)}leg(J){let $=this.from(J).entries[0];return new DJ([$],this.options)}upload(J){return this.entries[0].provider.upload(J)}deleteFile(J){let $=this.entries[0].provider;if(!$.deleteFile)return Promise.reject(Error(`${$.constructor.name} cannot delete provider files: it does not implement deleteFile().`));return $.deleteFile(J)}normalizeError(J){return this.entries[0].provider.normalizeError(J)}stream(J){return this.run(J)}async*run(J){let $,Q=J.signal,Z=0;for(let W=0;W<this.entries.length;W++){let X=this.entries[W],K=W===this.entries.length-1,G=X.provider.model;if(this.circuit&&!K&&!await this.allow(X))continue;Z+=1;let z=!1,V=async(L)=>{if(z)return;z=!0,await this.record(W,X,L)},Y=new AbortController,D=()=>Y.abort(Q?.reason);if(Q?.aborted)Y.abort(Q.reason);else Q?.addEventListener("abort",D,{once:!0});let P=[],H=!1,O=!1,C,N,F,U=!1,_,E=!1,T=(L)=>{let k=$?j(j(R(),$),L.usage):L.usage;return $=void 0,{...L,usage:k}};try{_=X.provider.stream({...J,...X.reasoning!==void 0?{reasoning:X.reasoning}:{},signal:Y.signal})[Symbol.asyncIterator]();let L=X.timeoutMs!==void 0?Date.now()+X.timeoutMs:void 0;for(;;){let k=!H&&L!==void 0?await z9(_.next(),Math.max(0,L-Date.now())):await _.next();if(k===WZ){U=!0,F={error:{code:"provider_error",message:`${G} did not start answering within ${X.timeoutMs}ms.`,retryable:!0}};break}if(k.done){E=!0;break}let M=k.value;if(M.type==="finish"&&M.model)N=M.model;if(M.type==="retry"){yield M;continue}if(H){if(M.type==="finish")C=j(C??R(),M.usage),O=!0,yield T(M);else{if(M.type==="error")F={error:M.error};yield M}continue}if(ZZ(M)){H=!0,await V("success"),yield*P.splice(0),yield M;continue}if(M.type==="error")F={error:M.error,...QJ(M)};else if(M.type==="finish"){if(C=j(C??R(),M.usage),M.reason==="error"&&!F)F={error:{code:"provider_error",message:`${G} ended the call with an error and did not say which.`,retryable:!1}}}P.push(M)}}catch(L){let k=X.provider.normalizeError(L);if(H){if(k.code!=="aborted")yield{type:"error",error:k,...QJ(L)};this.report({index:W,model:G,responseModel:N,attempt:Z,usage:C,outcome:O$(k),error:k}),yield T({type:"finish",reason:k.code==="aborted"?"aborted":"error",usage:R(),...N?{model:N}:{}});return}F={error:k,...QJ(L)}}finally{if(Q?.removeEventListener("abort",D),!E)Y.abort(),_?.return?.()?.catch(()=>{})}if(H){if(!O&&$)yield{type:"finish",reason:F?"error":"stop",usage:$},$=void 0;this.report({index:W,model:G,responseModel:N,attempt:Z,usage:C,outcome:F?O$(F.error):"ok",...F?{error:F.error}:{}});return}if(Q?.aborted){await V("none"),this.report({index:W,model:G,responseModel:N,attempt:Z,usage:C,outcome:"aborted"}),yield T({type:"finish",reason:"aborted",usage:C??R(),...N?{model:N}:{}});return}if(!F){await V("success"),this.report({index:W,model:G,responseModel:N,attempt:Z,usage:C,outcome:"ok"});for(let L of P)yield L.type==="finish"?T(L):L;return}let x=!K&&F.error.code!=="aborted"&&this.shouldFallBack(F.error,{index:W,model:G,timedOut:U,...QJ(F)});if(await V(x?"failure":"none"),this.report({index:W,model:G,responseModel:N,attempt:Z,usage:C,outcome:x?"fallback":O$(F.error),error:F.error}),x){if(C)$=j($??R(),C);continue}let w=!1,s;for(let L of P){if(L.type==="finish"){s=L;continue}if(L.type==="error")w=!0;yield L}if(!w&&F.error.code!=="aborted")yield{type:"error",error:F.error,...QJ(F)};yield T({type:"finish",reason:F.error.code==="aborted"?"aborted":s?.reason??"error",usage:C??R(),...N?{model:N}:{}});return}}async allow(J){if(!this.circuit)return!0;try{return await this.circuit.store.allow(C$(J),this.circuit.policy)}catch{return!0}}async record(J,$,Q){if(!this.circuit)return;let Z=C$($),W;try{W=await this.circuit.store.record(Z,Q,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:J,model:$.provider.model,key:Z,state:W})}catch{}}shouldFallBack(J,$){let Q=this.options.fallbackOn??((Z)=>Z.retryable);try{return Q(J,$)}catch{return!1}}report(J){if(J.usage===void 0)delete J.usage;if(J.responseModel===void 0)delete J.responseModel;try{this.options.onUsage?.(J)}catch{}}}function C$(J){return J.circuitKey??J.provider.model}function O$(J){return J.code==="aborted"?"aborted":"failed"}function V9(J){return{reasoning:J.every(($)=>$.reasoning),structuredOutput:J.every(($)=>$.structuredOutput),fileInput:J.every(($)=>$.fileInput),parallelToolCalls:J.every(($)=>$.parallelToolCalls),toolSearch:J.every(($)=>$.toolSearch),supportsForcedToolChoice:J.every(($)=>$.supportsForcedToolChoice!==!1)}}function z9(J,$){let Q,Z=new Promise((W)=>{Q=setTimeout(()=>W(WZ),$)});return Promise.race([J,Z]).finally(()=>clearTimeout(Q))}async function Y9(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 X=0;X<J.entries.length;X++){let K=J.leg(X),G={index:X,model:K.model,results:[],errors:[]};for(let z=0;z<Z;z++)try{G.results.push(await $(K,{index:X,sample:z}))}catch(V){G.errors.push({sample:z,error:V})}W.push(G)}return W}class hJ extends Error{line;constructor(J){super(J??"Voice session ended by the app.");this.name="VoiceHangup",this.line=J}}var PJ="ask_agent",D9={maxDurationMs:900000,idleTimeoutMs:120000,maxQueued:3,progressIntervalMs:4000,closingLineMs:1e4,tickMs:60000,hangupGraceMs:30000,toolTimeoutMs:60000,maxToolCallsPerMinute:20,toolOutputChars:8000},H9={maxDuration:"We've reached the time limit for this voice session. Tap the microphone to start again.",idle:"It's gone quiet, so I'll hang up. Tap the microphone when you want to talk again.",error:null};function HJ(J={}){return[{name:J.name??PJ,description:J.description??"Hand one self-contained request to the agent that does the work, in the user's own words with references resolved. It can take minutes; the result comes back when it is done, so tell the user you are on it.",parameters:{type:"object",properties:{request:{type:"string",description:"What the user wants done."}},required:["request"],additionalProperties:!1}},{name:"stop_work",description:"Stop the work that is running, and drop any requests waiting behind it.",parameters:{type:"object",properties:{},additionalProperties:!1}},{name:"work_status",description:"What the agent is doing right now, and what is waiting.",parameters:{type:"object",properties:{},additionalProperties:!1}},{name:"answer_question",description:"Answer the question the agent asked (it came back from a request with status needs_input). For an approval, set approve.",parameters:{type:"object",properties:{answer:{type:"string",description:"The user's answer, in their words."},approve:{type:"boolean",description:"For an approval: whether the user approved."}},required:["answer"],additionalProperties:!1}}]}var yJ=new Map;class d{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(J){return new d(J)}static get(J){return yJ.get(J)}static async endAll(J){await Promise.all([...yJ.values()].map(($)=>$.end("hangup",J)))}constructor(J){this.params=J,this.sessionId=J.sessionId??crypto.randomUUID(),this.threadId=J.threadId,this.body=J.body??{},this.limits={...D9,...XZ(J.limits)},this.lines={...H9,...XZ(J.lines)},this.delegateName=J.delegate?.name??PJ;let $=new Set(HJ(J.delegate).map((Q)=>Q.name));for(let Q of J.tools??[]){if($.has(Q.tool.name)||this.toolHandlers.has(Q.tool.name))throw Error(`VoiceBridge: two tools are named "${Q.tool.name}".`);this.toolHandlers.set(Q.tool.name,Q)}if("realtime"in J.call){let{realtime:Q,callId:Z}=J.call;this.callId=Z,this.sideband=Q.sideband(Z),this.hangupCall=()=>this.sideband.hangup()}else this.callId=J.call.callId??J.call.sideband.callId,this.sideband=J.call.sideband,this.hangupCall=()=>this.sideband.hangup();this.ended=new Promise((Q)=>this.resolveEnded=Q),yJ.set(this.sessionId,this),this.timers.push(setTimeout(()=>void this.end("max_duration",this.lines.maxDuration),this.limits.maxDurationMs)),this.tickTimer=setInterval(()=>void this.tick(),this.limits.tickMs),this.touch(),this.listen()}setBody(J){this.body=J;let $=this.params.contextNote?.(J);if($)this.sideband.addNote($)}end(J="hangup",$){return this.ending??=this.finish(J,$??null)}async listen(){for await(let J of this.sideband){try{this.params.onEvent?.(J)}catch{}this.closingWaiter?.(J),await this.handle(J)}}async handle(J){switch(J.type){case"input_audio_buffer.speech_started":this.touch();return;case"response.created":this.responseActive=!0,this.pendingCreate=void 0,this.touch();return;case"response.done":{if(this.responseActive=!1,this.responseWanted&&!this.ending)this.responseWanted=!1,this.createResponse();let $=J.usage;if($){this.usage=j(this.usage,$);let Q=this.info();this.hook(()=>this.params.onUsage?.($,Q))}return}case"conversation.item.input_audio_transcription.completed":{let $=J;if(this.say("user",String($.transcript??"")),$.transcriptionUsage||$.transcriptionSeconds!==void 0){this.transcription={usage:$.transcriptionUsage?j(this.transcription.usage,$.transcriptionUsage):this.transcription.usage,seconds:this.transcription.seconds+($.transcriptionSeconds??0)};let Q=this.info(),Z={...$.transcriptionUsage?{usage:$.transcriptionUsage}:{},...$.transcriptionSeconds!==void 0?{seconds:$.transcriptionSeconds}:{}};this.hook(()=>this.params.onTranscriptionUsage?.(Z,Q))}return}case"response.output_audio_transcript.done":this.say("assistant",String(J.transcript??""));return;case"response.output_text.done":this.say("assistant",String(J.text??""));return;case"response.function_call_arguments.done":{let $=J;if(this.touch(),!this.ending)this.call($.call_id,$.name,$.arguments);return}case"session.updated":if(this.tampered(J.session))this.end("session_tampered",null);return;case"error":{let $=J.error;if(this.errors.push({code:$?.code,message:String($?.message??"")}),this.pendingCreate&&$?.event_id===this.pendingCreate)if(this.pendingCreate=void 0,$.code==="conversation_already_has_active_response")this.responseActive=!0,this.responseWanted=!0;else this.responseActive=!1;return}case"sideband.closed":{let $=J;if(!this.ending&&!$.byClient)this.end($.code===1000?"call_ended":"sideband_lost",null);return}}}say(J,$){if($.trim())this.transcript.push({role:J,text:$,at:Date.now()})}call(J,$,Q){let Z=P9(Q);if($===this.delegateName){let X=typeof Z.request==="string"?Z.request.trim():"";if(!X)return this.answer(J,{status:"error",message:"The request was empty."});return this.enqueue({record:{request:X,status:"queued"},turn:{text:X},callId:J})}let W=this.toolHandlers.get($);if(W)return void this.runTool(J,W,Z);switch($){case"stop_work":{let X=this.running;if(X)X.stopRequested=!0,X.handle?.stop({reason:"Stopped by voice."});let K=this.dropQueue();return this.answer(J,{stopped:Boolean(X),dropped:K})}case"work_status":return this.answer(J,{running:this.running?{request:this.running.record.request,step:this.lastProgress??"starting"}:null,queued:this.queue.map((X)=>X.record.request),...this.pending.length?{needsInput:this.questions()}:{}});case"answer_question":{if(!this.pending.length)return this.answer(J,{status:"error",message:"There is no open question."});let X=typeof Z.answer==="string"?Z.answer:"",K=typeof Z.approve==="boolean"?Z.approve:void 0,G=this.pending.map((z)=>N9(z,X,K));return this.pending=[],this.enqueue({record:{request:`(answer) ${X}`,status:"queued"},turn:{toolResults:G},callId:J})}default:return this.answer(J,{status:"error",message:`There is no tool called ${$}.`})}}enqueue(J){if(!this.running){this.requests.push(J.record),this.run(J);return}if(this.queue.length>=this.limits.maxQueued)return this.answer(J.callId,{status:"busy",message:"Too many requests are waiting. Ask the user to wait for the current one."});this.requests.push(J.record),this.queue.push(J),this.answer(J.callId,{status:"queued",position:this.queue.length,message:"It will start when the current request is done."}),J.callId=void 0}async run(J){this.running=J,J.record.status="running",this.lastProgress=void 0,this.pauseIdle();try{let $=new Set;await this.waitForThread($);let Q=await this.latestBody();while(!J.stopRequested&&await this.waitForThread($));if(J.stopRequested||this.ending){J.record.status="dropped",this.complete(J,{status:"stopped"});return}let Z;try{Z=await this.params.controller.startTurn({threadId:this.threadId,user:this.params.user,body:Q,turn:J.turn})}catch(X){J.record.status="refused",this.complete(J,{status:"refused",message:X instanceof Error?X.message:"The request could not be started."});return}J.handle=Z,J.record.runId=Z.runId,this.follow(Z);let W=await Z.result();if(J.record.status="done",J.record.finishReason=W.finishReason,W.finishReason==="awaiting-input"&&W.pending.length)this.pending=W.pending,this.complete(J,{status:"needs_input",text:W.text,questions:this.questions()});else if(W.finishReason==="error")this.complete(J,{status:"failed",message:W.error?.message??"The work failed."});else if(W.finishReason==="aborted")this.complete(J,{status:"stopped",text:W.text});else this.complete(J,{status:"done",text:W.text})}catch($){J.record.status="done",this.complete(J,{status:"failed",message:$ instanceof Error?$.message:"The work failed."})}finally{this.running=void 0,this.flushNote();let $=this.queue.shift();if($&&!this.ending)this.run($);else this.touch()}}async runTool(J,$,Q){let Z=$.tool.name,W=Date.now();if(this.toolCallTimes=this.toolCallTimes.filter((D)=>W-D<60000),this.toolCallTimes.length>=this.limits.maxToolCallsPerMinute){let D={name:Z,status:"busy"};this.toolCalls.push(D),this.answer(J,{status:"busy",message:"Too many tool calls in the last minute. Tell the user to wait a moment."});return}this.toolCallTimes.push(W);let X={name:Z,status:"running"};this.toolCalls.push(X),this.toolsRunning+=1,this.pauseIdle();let K=new AbortController,G=$.timeoutMs??this.limits.toolTimeoutMs,z,V;try{let D=await Promise.race([$.run(Q,{sessionId:this.sessionId,signal:K.signal}),new Promise((P,H)=>{z=setTimeout(()=>{H(new i(`"${Z}" took longer than ${Math.round(G/1000)} s.`)),K.abort()},G)})]);X.status="done",V={status:"done",output:this.clip(D)}}catch(D){if(D instanceof hJ){X.status="refused",X.message=D.message,this.end("usage",D.line??null);return}let P=D instanceof i?D.message:"The tool failed.";if(!(D instanceof i))console.error(`[gemi/ai] the voice tool "${Z}" threw.`,D);X.status="failed",X.message=P,V={status:"failed",message:P}}finally{clearTimeout(z),X.durationMs=Date.now()-W,this.toolsRunning-=1,this.touch()}let Y=this.info();if(this.hook(()=>this.params.onToolCall?.({...X},Y)),!this.ending)this.answer(J,V)}clip(J){let $;try{$=JSON.stringify(J)}catch{return String(J)}if($===void 0||$.length<=this.limits.toolOutputChars)return J;return`${$.slice(0,this.limits.toolOutputChars)}\u2026 (cut: ${$.length} characters in all)`}async waitForThread(J=new Set){let $=this.params.liveRuns;if(!$)return!1;let Q=await $.find({threadId:this.threadId}),Z=Q&&!J.has(Q.runId)?$.get(Q.runId):null;if(!Q||!Z)return!1;return J.add(Q.runId),await Z.result().catch(()=>{return}),!0}async latestBody(){let J=this.params.store;if(!J)return this.body;let $=await J.get(this.sessionId).catch(()=>null);if($)this.body=$.body;return this.body}async follow(J){let $=this.params.progress??F9();try{for await(let Q of J.run){let Z=$(Q);if(Z)this.note(Z)}}catch{}}complete(J,$){if(this.ending)return;if(J.callId)this.sideband.functionOutput(J.callId,$),J.callId=void 0;else this.sideband.addNote(`Update on the earlier request "${J.record.request}": ${JSON.stringify($)}`);this.respond()}answer(J,$){this.sideband.functionOutput(J,$),this.respond()}respond(){if(this.ending)return;if(this.responseActive){this.responseWanted=!0;return}this.responseActive=!0,this.createResponse()}createResponse(){let J=`gemi_voice_${crypto.randomUUID()}`;this.pendingCreate=J,this.sideband.send({type:"response.create",event_id:J})}questions(){return this.pending.map((J)=>({kind:J.kind,tool:String(J.name),input:J.input}))}dropQueue(){let J=this.queue.splice(0);for(let $ of J)$.record.status="dropped";return J.length}note(J){if(J===this.lastProgress)return;this.lastProgress=J;let $=this.lastNoteAt+this.limits.progressIntervalMs-Date.now();if($<=0)return this.flushNote();this.noteTimer??=setTimeout(()=>this.flushNote(),$)}flushNote(){if(this.noteTimer)clearTimeout(this.noteTimer);if(this.noteTimer=void 0,!this.lastProgress||this.ending||!this.running)return;this.lastNoteAt=Date.now(),this.sideband.addNote(`Progress on "${this.running.record.request}": ${this.lastProgress}`)}touch(){if(this.idleTimer)clearTimeout(this.idleTimer);if(this.idleTimer=void 0,this.running||this.toolsRunning>0||this.ending)return;this.idleTimer=setTimeout(()=>void this.end("idle",this.lines.idle),this.limits.idleTimeoutMs)}pauseIdle(){if(this.idleTimer)clearTimeout(this.idleTimer);this.idleTimer=void 0}info(){return{sessionId:this.sessionId,total:this.usage,elapsedMs:Date.now()-this.startedAt,transcription:this.transcription}}tick(){if(this.ending)return;let J=this.info();this.hook(()=>this.params.onTick?.(J))}hook(J){this.hooks=this.hooks.then(async()=>{try{await J()}catch($){if($ instanceof hJ)this.end("usage",$.line??null);else console.error("[gemi/ai] a voice hook threw; ending the call.",$),this.end("error",this.lines.error)}})}tampered(J){let $=this.params.session;if(!$||!J)return!1;if($.instructions!==void 0&&J.instructions!==void 0&&J.instructions!==$.instructions)return!0;if(Array.isArray(J.tools)){let Q=new Set([...HJ(this.params.delegate),...$.tools??[]].map((W)=>W.name)),Z=new Set(J.tools.map((W)=>String(W?.name)));if(Q.size!==Z.size||[...Q].some((W)=>!Z.has(W)))return!0}return!1}async finish(J,$){for(let K of this.timers)clearTimeout(K);if(this.idleTimer)clearTimeout(this.idleTimer);if(this.noteTimer)clearTimeout(this.noteTimer);if(this.tickTimer)clearInterval(this.tickTimer);if(this.dropQueue(),$&&(J!=="call_ended"&&J!=="sideband_lost"))await this.closingLine($);if(J!=="call_ended")await this.hangUp();else this.sideband.close();await this.hooks;let Z=Date.now(),W=Z-this.startedAt,X={sessionId:this.sessionId,...this.callId?{callId:this.callId}:{},threadId:this.threadId,reason:J,startedAt:this.startedAt,endedAt:Z,durationMs:W,seconds:Math.ceil(W/1000),usage:this.usage,transcription:this.transcription,transcript:this.transcript,requests:this.requests,toolCalls:this.toolCalls,errors:this.errors};yJ.delete(this.sessionId),await this.params.store?.update(this.sessionId,{endedAt:Z,endReason:J}).catch(()=>{return});try{await this.params.onEnd?.(X)}catch(K){console.error("[gemi/ai] a voice session's onEnd threw.",K)}return this.resolveEnded(X),X}async hangUp(){try{await this.hangupCall()}catch(J){console.error("[gemi/ai] a voice call could not be hung up; waiting for the vendor.",J),this.errors.push({code:"hangup_failed",message:J instanceof Error?J.message:String(J)});let $;await Promise.race([this.sideband.closed,new Promise((Q)=>$=setTimeout(Q,this.limits.hangupGraceMs))]),clearTimeout($),this.sideband.close()}}async closingLine(J){await new Promise(($)=>{let Q=`gemi_voice_closing_${crypto.randomUUID()}`,Z=`gemi_voice_cancel_${crypto.randomUUID()}`,W=this.responseActive?"cancelling":"asked",X,K=setTimeout(G,this.limits.closingLineMs);function G(){clearTimeout(K),$()}let z=()=>{W="asked",this.sideband.send({type:"response.create",event_id:Q,response:{instructions:`Say exactly this to the user, and nothing else: "${J}"`,tool_choice:"none"}})};if(this.closingWaiter=(V)=>{let Y=V;if(Y.type==="sideband.closed")return G();if(W==="cancelling"){if(Y.type==="response.done"||Y.type==="error"&&Y.error?.event_id===Z)z();return}if(Y.type==="error"&&Y.error?.event_id===Q)return G();if(Y.type==="response.created"&&!X){X=Y.response?.id;return}let D=(P)=>!X||!P||P===X;if(Y.type==="response.done"&&D(Y.response?.id))W="playing";else if(Y.type==="output_audio_buffer.stopped"&&W==="playing"&&D(Y.response_id))G()},W==="cancelling")this.sideband.send({type:"response.cancel",event_id:Z});else z()}),this.closingWaiter=void 0}}function XZ(J){if(!J)return{};return Object.fromEntries(Object.entries(J).filter(([,$])=>$!==void 0))}function P9(J){try{let $=JSON.parse(J);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function N9(J,$,Q){let Z={toolCallId:J.toolCallId,signature:J.signature,...J.path?{path:J.path}:{}};if(J.kind==="question")return{...Z,output:$};if(J.kind==="approval")return{...Z,approve:Q===!0,...$?{reason:$}:{}};return{...Z,approve:!1,reason:"Not available in a voice call."}}function F9(){let J=new Set;return($)=>{if($.type==="tool-call"){if($.part.partial||$.resent||J.has($.part.toolCallId))return;return J.add($.part.toolCallId),`running ${String($.part.name)}`}if($.type==="tool-progress"){let Q=$.data;if(typeof Q==="string")return Q;if(Q&&typeof Q==="object")for(let Z of["message","label","title"]){let W=Q[Z];if(typeof W==="string"&&W)return W}}return}}var KZ="http://gemi.internal/__gemi__/voice/mcp";async function L$(J,$){if(!$.user)throw Error("Voice MCP tools run as the signed-in user, and this voice session has none. Give `mcp` only to a signed-in user's session.");let{registry:Q}=J,Z=J.scopes??Q.scopes().map((K)=>K.name),W=(K)=>({kind:"remote",req:K,principal:{user:$.user,via:"voice",id:`voice:${$.sessionId}`,scopes:Z}});return(await Q.available(W(GZ()),J.filter)).filter((K)=>!K.requiresApproval).map((K)=>({tool:{name:K.name,description:K.description,parameters:K.inputSchema},...J.timeoutMs!==void 0?{timeoutMs:J.timeoutMs}:{},run:(G,z)=>{let V=GZ();return l.run(V,async()=>{return await J.authorize?.({name:K.name,input:G,sessionId:z.sessionId}),Q.execute(W(V),K.name,G,void 0,{signal:z.signal})},{user:$.user})}}))}function GZ(){return new f(new Request(KZ,{method:"POST"}),{},"api",new URL(KZ).pathname)}class B${records=new Map;retainEndedMs;constructor(J={}){this.retainEndedMs=J.retainEndedMs??600000}async create(J){this.sweep(),this.records.set(J.id,structuredClone(J))}async get(J){let $=this.records.get(J);return $?structuredClone($):null}async update(J,$){let Q=this.records.get(J);if(!Q)return;this.records.set(J,{...Q,...structuredClone($),id:J})}sweep(){let J=Date.now()-this.retainEndedMs;for(let[$,Q]of this.records)if(Q.endedAt!==void 0&&Q.endedAt<J)this.records.delete($)}}var M$=new B$;var VZ=new WeakMap,zZ=100;class S${threadsTable;messagesTable;scope=null;sql;dialect;connection;options;constructor(J,$={}){if(this.threadsTable=YZ($.threadsTable??"gemi_agent_threads","threads"),this.messagesTable=YZ($.messagesTable??"gemi_agent_messages","messages"),this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name,this.options=$,$.ttlMs!==void 0)NZ($.ttlMs,"ttlMs")}get expires(){return this.options.ttlMs!==void 0}forScope(J){if(typeof J!=="string"||J==="")throw TypeError("A DatabaseAgentStore scope is a non-empty string.");let $=new S$({sql:this.sql,dialect:this.dialect,name:this.connection},this.options);return $.scope=J,$}async createTable(){let J=O9(this.dialect,this.threadsTable,this.messagesTable);for(let $ of J)await this.sql.unsafe($);await this.addScopeColumns(),await this.addExpiryColumns()}async addExpiryColumns(){if(await this.hasColumn(this.threadsTable,"expires_at"))return;for(let J of L9(this.dialect,this.threadsTable))await this.sql.unsafe(J)}async addScopeColumns(){let J=_9(this.dialect,this.threadsTable,this.messagesTable);for(let[$,Q]of J){if(await this.hasColumn($,"scope"))continue;for(let Z of Q)await this.sql.unsafe(Z)}}async hasColumn(J,$){try{return await this.sql.unsafe(`SELECT ${$} FROM ${this.quote(J)} WHERE 1 = 0`),!0}catch{return!1}}async createThread(J={}){let $=crypto.randomUUID(),Q=J.userId===void 0||J.userId===null?null:String(J.userId),Z=this.expiryOf(J);return await this.run(async(W)=>{let X=this.clock(W);if(Z){let K=Z.at!==void 0?this.ms(W,Z.at):Z.ttlMs===null?null:W`${X} + ${this.ms(W,Z.ttlMs)}`,G=Z.slides&&Z.ttlMs!==null?this.ms(W,Z.ttlMs):null;if(this.scope===null)await W`
|
|
182
182
|
INSERT INTO ${this.threads(W)} (id, user_id, created_at, updated_at, expires_at, ttl_ms)
|
|
183
|
-
VALUES (${$}, ${Q}, ${
|
|
183
|
+
VALUES (${$}, ${Q}, ${X}, ${X}, ${K}, ${G})
|
|
184
184
|
`;else await W`
|
|
185
185
|
INSERT INTO ${this.threads(W)} (id, scope, user_id, created_at, updated_at, expires_at, ttl_ms)
|
|
186
|
-
VALUES (${$}, ${this.scope}, ${Q}, ${
|
|
186
|
+
VALUES (${$}, ${this.scope}, ${Q}, ${X}, ${X}, ${K}, ${G})
|
|
187
187
|
`}else if(this.scope===null)await W`
|
|
188
188
|
INSERT INTO ${this.threads(W)} (id, user_id, created_at, updated_at)
|
|
189
|
-
VALUES (${$}, ${Q}, ${
|
|
189
|
+
VALUES (${$}, ${Q}, ${X}, ${X})
|
|
190
190
|
`;else await W`
|
|
191
191
|
INSERT INTO ${this.threads(W)} (id, scope, user_id, created_at, updated_at)
|
|
192
|
-
VALUES (${$}, ${this.scope}, ${Q}, ${
|
|
192
|
+
VALUES (${$}, ${this.scope}, ${Q}, ${X}, ${X})
|
|
193
193
|
`}),{threadId:$}}async loadThread(J){return this.run(async($)=>{if((await $`
|
|
194
194
|
SELECT id FROM ${this.threads($)}
|
|
195
195
|
WHERE id = ${J} AND ${this.inScope($)} AND ${this.live($)}
|
|
@@ -197,7 +197,7 @@ import{ca as uQ,da as lQ,ea as iQ,fa as _6,ga as B6,ha as S6,ia as m$,ja as M6,k
|
|
|
197
197
|
SELECT message FROM ${this.messages($)}
|
|
198
198
|
WHERE thread_id = ${J} AND ${this.inScope($)}
|
|
199
199
|
ORDER BY position
|
|
200
|
-
`).map((W)=>JSON.parse(String(W.message)))})}async appendMessages(J,$){if($.length===0){if(await this.getThread(J)===null)throw
|
|
200
|
+
`).map((W)=>JSON.parse(String(W.message)))})}async appendMessages(J,$){if($.length===0){if(await this.getThread(J)===null)throw DZ(J);return}await this.atomically(async(Q)=>{if(this.expires)await Q`
|
|
201
201
|
UPDATE ${this.threads(Q)}
|
|
202
202
|
SET updated_at = ${this.clock(Q)},
|
|
203
203
|
expires_at = CASE WHEN ttl_ms IS NULL THEN expires_at ELSE ${this.clock(Q)} + ttl_ms END
|
|
@@ -208,64 +208,64 @@ import{ca as uQ,da as lQ,ea as iQ,fa as _6,ga as B6,ha as S6,ia as m$,ja as M6,k
|
|
|
208
208
|
`;let Z=await Q`
|
|
209
209
|
SELECT title FROM ${this.threads(Q)}
|
|
210
210
|
WHERE id = ${J} AND ${this.inScope(Q)} AND ${this.live(Q)}
|
|
211
|
-
`;if(Z.length===0)throw
|
|
211
|
+
`;if(Z.length===0)throw DZ(J);let W=[...new Set($.map((V)=>V.id))],X=await Q`
|
|
212
212
|
SELECT id FROM ${this.messages(Q)}
|
|
213
|
-
WHERE thread_id = ${J} AND id IN (${
|
|
214
|
-
`,
|
|
213
|
+
WHERE thread_id = ${J} AND id IN (${ZJ(Q,W)})
|
|
214
|
+
`,K=new Set(X.map((V)=>String(V.id))),[G]=await Q`
|
|
215
215
|
SELECT MAX(position) AS position FROM ${this.messages(Q)} WHERE thread_id = ${J}
|
|
216
|
-
`,
|
|
217
|
-
UPDATE ${this.messages(Q)} SET message = ${
|
|
218
|
-
WHERE thread_id = ${J} AND id = ${
|
|
216
|
+
`,z=G?.position===null||G?.position===void 0?0:Number(G.position)+1;for(let V of $){let Y=JSON.stringify(V);if(K.has(V.id))await Q`
|
|
217
|
+
UPDATE ${this.messages(Q)} SET message = ${Y}
|
|
218
|
+
WHERE thread_id = ${J} AND id = ${V.id}
|
|
219
219
|
`;else if(this.scope===null)await Q`
|
|
220
220
|
INSERT INTO ${this.messages(Q)} (thread_id, id, position, message, created_at)
|
|
221
|
-
VALUES (${J}, ${
|
|
222
|
-
`,
|
|
221
|
+
VALUES (${J}, ${V.id}, ${z}, ${Y}, ${this.clock(Q)})
|
|
222
|
+
`,K.add(V.id),z+=1;else await Q`
|
|
223
223
|
INSERT INTO ${this.messages(Q)} (thread_id, scope, id, position, message, created_at)
|
|
224
|
-
VALUES (${J}, ${this.scope}, ${
|
|
225
|
-
`,
|
|
226
|
-
UPDATE ${this.threads(Q)} SET title = ${
|
|
224
|
+
VALUES (${J}, ${this.scope}, ${V.id}, ${z}, ${Y}, ${this.clock(Q)})
|
|
225
|
+
`,K.add(V.id),z+=1}if(Z[0].title===null||Z[0].title===void 0){let V=U9($);if(V!==null)await Q`
|
|
226
|
+
UPDATE ${this.threads(Q)} SET title = ${V}
|
|
227
227
|
WHERE id = ${J} AND title IS NULL
|
|
228
228
|
`}})}async removeMessages(J,$){if($.length===0)return;await this.run(async(Q)=>{await Q`
|
|
229
229
|
DELETE FROM ${this.messages(Q)}
|
|
230
230
|
WHERE thread_id = ${J} AND ${this.inScope(Q)}
|
|
231
|
-
AND id IN (${
|
|
231
|
+
AND id IN (${ZJ(Q,[...new Set($)])})
|
|
232
232
|
`})}async loadSummaries(J){return this.run(async($)=>{let[Q]=await $`
|
|
233
233
|
SELECT summaries FROM ${this.threads($)}
|
|
234
234
|
WHERE id = ${J} AND ${this.inScope($)} AND ${this.live($)}
|
|
235
|
-
`;return Q?
|
|
235
|
+
`;return Q?HZ(Q.summaries):[]})}async saveSummary(J,$){await this.atomically(async(Q)=>{await Q`
|
|
236
236
|
UPDATE ${this.threads(Q)} SET updated_at = updated_at
|
|
237
237
|
WHERE id = ${J} AND ${this.inScope(Q)}
|
|
238
238
|
`;let[Z]=await Q`
|
|
239
239
|
SELECT summaries FROM ${this.threads(Q)}
|
|
240
240
|
WHERE id = ${J} AND ${this.inScope(Q)} AND ${this.live(Q)}
|
|
241
|
-
`;if(!Z)return;let W=
|
|
241
|
+
`;if(!Z)return;let W=NJ(HZ(Z.summaries),$);await Q`
|
|
242
242
|
UPDATE ${this.threads(Q)} SET summaries = ${JSON.stringify(W)}
|
|
243
243
|
WHERE id = ${J}
|
|
244
|
-
`})}async lockSummary(J,$,Q){let Z=`${$}:${crypto.randomUUID()}`;if(!await this.run(async(
|
|
245
|
-
UPDATE ${this.threads(
|
|
246
|
-
SET summary_lock = ${Z}, summary_lock_until = ${
|
|
247
|
-
WHERE id = ${J} AND ${this.inScope(
|
|
248
|
-
AND (summary_lock_until IS NULL OR summary_lock_until <= ${
|
|
249
|
-
`;return
|
|
250
|
-
UPDATE ${this.threads(
|
|
251
|
-
WHERE id = ${J} AND ${this.inScope(
|
|
244
|
+
`})}async lockSummary(J,$,Q){let Z=`${$}:${crypto.randomUUID()}`;if(!await this.run(async(X)=>{let K=this.clock(X),G=await X`
|
|
245
|
+
UPDATE ${this.threads(X)}
|
|
246
|
+
SET summary_lock = ${Z}, summary_lock_until = ${K} + ${this.ms(X,Q)}
|
|
247
|
+
WHERE id = ${J} AND ${this.inScope(X)} AND ${this.live(X)}
|
|
248
|
+
AND (summary_lock_until IS NULL OR summary_lock_until <= ${K})
|
|
249
|
+
`;return C9(G)>0}))return null;return async()=>{await this.run(async(X)=>{await X`
|
|
250
|
+
UPDATE ${this.threads(X)} SET summary_lock = NULL, summary_lock_until = NULL
|
|
251
|
+
WHERE id = ${J} AND ${this.inScope(X)} AND summary_lock = ${Z}
|
|
252
252
|
`})}}async getThread(J){return this.run(async($)=>{let[Q]=await $`
|
|
253
253
|
SELECT ${this.recordColumns($)} FROM ${this.threads($)}
|
|
254
254
|
WHERE id = ${J} AND ${this.inScope($)} AND ${this.live($)}
|
|
255
|
-
`;return Q?
|
|
255
|
+
`;return Q?PZ(Q):null})}async listThreads(J={}){let $=Math.max(0,Math.floor(J.limit??50)),Q=Math.max(0,Math.floor(J.offset??0));return this.run(async(Z)=>{let W=J.userId===void 0?Z`1 = 1`:J.userId===null?Z`user_id IS NULL`:Z`user_id = ${String(J.userId)}`;return(await Z`
|
|
256
256
|
SELECT ${this.recordColumns(Z)} FROM ${this.threads(Z)}
|
|
257
257
|
WHERE ${this.inScope(Z)} AND ${this.live(Z)} AND ${W}
|
|
258
258
|
ORDER BY updated_at DESC, id DESC
|
|
259
259
|
LIMIT ${$} OFFSET ${Q}
|
|
260
|
-
`).map(
|
|
260
|
+
`).map(PZ)})}async deleteThread(J){await this.atomically(async($)=>{if((await $`
|
|
261
261
|
SELECT id FROM ${this.threads($)} WHERE id = ${J} AND ${this.inScope($)}
|
|
262
|
-
`).length===0)return;await $`DELETE FROM ${this.messages($)} WHERE thread_id = ${J}`,await $`DELETE FROM ${this.threads($)} WHERE id = ${J}`})}async sweepExpired(J={}){if(!this.expires)return this.guard(),{deleted:0};let $=Math.max(0,Math.floor(J.limit??500));if($===0)return{deleted:0};return this.atomically(async(Q)=>{let Z=J.now===void 0?this.clock(Q):this.ms(Q,J.now),W=Q`expires_at IS NOT NULL AND expires_at <= ${Z} AND ${this.inScope(Q)}`,
|
|
262
|
+
`).length===0)return;await $`DELETE FROM ${this.messages($)} WHERE thread_id = ${J}`,await $`DELETE FROM ${this.threads($)} WHERE id = ${J}`})}async sweepExpired(J={}){if(!this.expires)return this.guard(),{deleted:0};let $=Math.max(0,Math.floor(J.limit??500));if($===0)return{deleted:0};return this.atomically(async(Q)=>{let Z=J.now===void 0?this.clock(Q):this.ms(Q,J.now),W=Q`expires_at IS NOT NULL AND expires_at <= ${Z} AND ${this.inScope(Q)}`,X=await Q`
|
|
263
263
|
SELECT id FROM ${this.threads(Q)} WHERE ${W}
|
|
264
264
|
ORDER BY expires_at, id
|
|
265
265
|
LIMIT ${$}
|
|
266
|
-
`;if(
|
|
267
|
-
SELECT id FROM ${this.threads(Q)} WHERE id IN (${
|
|
268
|
-
`;if(G.length===0)return{deleted:0};let
|
|
266
|
+
`;if(X.length===0)return{deleted:0};let K=X.map((V)=>String(V.id));await Q`UPDATE ${this.threads(Q)} SET updated_at = updated_at WHERE id IN (${ZJ(Q,K)})`;let G=await Q`
|
|
267
|
+
SELECT id FROM ${this.threads(Q)} WHERE id IN (${ZJ(Q,K)}) AND ${W}
|
|
268
|
+
`;if(G.length===0)return{deleted:0};let z=G.map((V)=>String(V.id));return await Q`DELETE FROM ${this.messages(Q)} WHERE thread_id IN (${ZJ(Q,z)})`,await Q`DELETE FROM ${this.threads(Q)} WHERE id IN (${ZJ(Q,z)})`,{deleted:z.length}})}atomically(J){if(this.guard(),this.joinable())return xJ(this.sql,(K)=>J(K),{connection:this.connection});let $=this.scope,Q=this.options.beginScope,Z=()=>this.sql.begin(async(K)=>{if($!==null&&Q)await Q(K,$);return J(K)});if(this.dialect!=="sqlite")return Z();let X=(VZ.get(this.sql)??Promise.resolve()).then(Z,Z);return VZ.set(this.sql,X.then(()=>{},()=>{})),X}joinable(){if(this.connection===void 0)return;let J=e();if(J===void 0||JJ()!==this.connection)return;return J}run(J){this.guard();let $=this.joinable();if($)return J($);if(this.scope!==null&&this.options.beginScope)return this.atomically(J);return J(this.sql)}guard(){if(this.scope===null&&this.options.requireScope)throw Error("This DatabaseAgentStore requires a scope: call it through store.forScope(scope).")}inScope(J){return this.scope===null?J`1 = 1`:J`scope = ${this.scope}`}live(J){return this.expires?J`(expires_at IS NULL OR expires_at > ${this.clock(J)})`:J`1 = 1`}recordColumns(J){return this.expires?J.unsafe("id, user_id, title, created_at, updated_at, expires_at"):J.unsafe("id, user_id, title, created_at, updated_at")}expiryOf(J){let $=J.ttlMs!==void 0||J.expiresAt!==void 0;if(!this.expires){if($)throw Error("createThread({ ttlMs, expiresAt }) needs a store with `ttlMs`: set `new DatabaseAgentStore(connection, { ttlMs })`, which turns expiry on and reads the expiry columns.");return null}if(J.expiresAt!==void 0){let Z=J.expiresAt instanceof Date?J.expiresAt.getTime():J.expiresAt;if(!Number.isFinite(Z))throw TypeError("createThread: `expiresAt` is not a valid time.");return{at:Z,ttlMs:null,slides:!1}}let Q=J.ttlMs===void 0?this.options.ttlMs:J.ttlMs;if(Q!==null)NZ(Q,"createThread: ttlMs");return{ttlMs:Q,slides:this.options.slidingTtl===!0}}quote(J){return this.dialect==="mysql"||this.dialect==="mariadb"?`\`${J}\``:`"${J}"`}threads(J){return J.unsafe(this.quote(this.threadsTable))}messages(J){return J.unsafe(this.quote(this.messagesTable))}clock(J){switch(this.dialect){case"postgres":return J`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return J`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return J`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(J,$){let Q=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${Q} AS SIGNED)`:J`CAST(${Q} AS BIGINT)`}}function YZ(J,$){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(J))throw Error(`The agent ${$} table name "${J}" is not a plain identifier. Use letters, digits and underscores.`);return J}function DZ(J){return Error(`Thread ${J} does not exist here, or has been deleted.`)}function ZJ(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function U9(J){for(let $ of J){if($.role!=="user"||$.event)continue;let Q=$.content.map((Z)=>Z.type==="text"?Z.text:"").join(" ").replace(/\s+/g," ").trim();if(Q)return Q.length>zZ?`${Q.slice(0,zZ-1)}\u2026`:Q}return null}function HZ(J){if(J===null||J===void 0||J==="")return[];let $=JSON.parse(String(J));return Array.isArray($)?$:[]}function PZ(J){return{id:String(J.id),userId:J.user_id===null||J.user_id===void 0?null:String(J.user_id),title:J.title===null||J.title===void 0?null:String(J.title),createdAt:Number(J.created_at),updatedAt:Number(J.updated_at),..."expires_at"in J?{expiresAt:J.expires_at===null||J.expires_at===void 0?null:Number(J.expires_at)}:{}}}function NZ(J,$){if(typeof J!=="number"||!Number.isFinite(J)||J<=0)throw TypeError(`${$} must be a positive number of milliseconds.`)}function C9(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function O9(J,$,Q){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
269
269
|
\`id\` VARCHAR(191) NOT NULL,
|
|
270
270
|
\`scope\` VARCHAR(191) NULL,
|
|
271
271
|
\`user_id\` VARCHAR(191) NULL,
|
|
@@ -315,14 +315,24 @@ import{ca as uQ,da as lQ,ea as iQ,fa as _6,ga as B6,ha as S6,ia as m$,ja as M6,k
|
|
|
315
315
|
"created_at" BIGINT NOT NULL,
|
|
316
316
|
|
|
317
317
|
CONSTRAINT "${Q}_pkey" PRIMARY KEY ("thread_id", "id")
|
|
318
|
-
)`,`CREATE UNIQUE INDEX IF NOT EXISTS "${Q}_thread_id_position_key" ON "${Q}"("thread_id", "position")`]}function
|
|
318
|
+
)`,`CREATE UNIQUE INDEX IF NOT EXISTS "${Q}_thread_id_position_key" ON "${Q}"("thread_id", "position")`]}function _9(J,$,Q){if(J==="mysql"||J==="mariadb")return[[$,[`ALTER TABLE \`${$}\` ADD COLUMN \`scope\` VARCHAR(191) NULL, ADD INDEX \`${$}_scope_user_id_updated_at_idx\`(\`scope\`, \`user_id\`, \`updated_at\`)`]],[Q,[`ALTER TABLE \`${Q}\` ADD COLUMN \`scope\` VARCHAR(191) NULL`]]];return[[$,[`ALTER TABLE "${$}" ADD COLUMN "scope" TEXT`,`CREATE INDEX IF NOT EXISTS "${$}_scope_user_id_updated_at_idx" ON "${$}"("scope", "user_id", "updated_at")`]],[Q,[`ALTER TABLE "${Q}" ADD COLUMN "scope" TEXT`]]]}function L9(J,$){if(J==="mysql"||J==="mariadb")return[`ALTER TABLE \`${$}\` ADD COLUMN \`expires_at\` BIGINT NULL, ADD COLUMN \`ttl_ms\` BIGINT NULL, ADD INDEX \`${$}_expires_at_idx\`(\`expires_at\`)`];return[`ALTER TABLE "${$}" ADD COLUMN "expires_at" BIGINT`,`ALTER TABLE "${$}" ADD COLUMN "ttl_ms" BIGINT`,`CREATE INDEX IF NOT EXISTS "${$}_expires_at_idx" ON "${$}"("expires_at")`]}class WJ extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(J,$,Q){super(`Frame ${$} of run ${J} has been evicted; the oldest frame still buffered is ${Q}. Reload the thread instead of resuming.`);this.runId=J;this.requested=$;this.oldest=Q}}class FJ extends Error{runId;code="live_run_not_found";constructor(J){super(`No live run ${J} in this process.`);this.runId=J}}class gJ{ttlMs;maxFrames;maxAgeMs;runs=new Map;byThread=new Map;threadRuns=new Map;byClientRun=new Map;constructor(J={}){this.ttlMs=J.ttlMs??60000,this.maxFrames=J.maxFrames??4096,this.maxAgeMs=J.maxAgeMs===void 0?3600000:J.maxAgeMs}register(J,$={}){let Q={run:J,threadId:$.threadId,startedAt:Date.now(),owner:$.owner??null,clientRunId:$.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evicted:!1,evictAt:null,expireAt:null,wake:new Set,version:0};if(this.runs.set(J.runId,Q),$.threadId){this.byThread.set($.threadId,J.runId);let Z=this.threadRuns.get($.threadId);if(!Z)Z=new Set,this.threadRuns.set($.threadId,Z);Z.add(J.runId)}if($.clientRunId)this.byClientRun.set($.clientRunId,J.runId);return this.scheduleExpiry(Q,$.maxRunDurationMs),this.pump(Q,$)}findByClientRunId(J){let $=this.byClientRun.get(J);return $&&this.runs.has($)?$:null}async find(J){let $=this.byThread.get(J.threadId);if(!$)return null;let Q=this.runs.get($);if(!Q)return null;return{runId:$,seq:Q.lastSeq}}running(J){let $=[];for(let Q of this.threadRuns.get(J.threadId)??[]){let Z=this.runs.get(Q);if(!Z||Z.ended||Z.evicted)continue;$.push({runId:Q,seq:Z.lastSeq,startedAt:Z.startedAt})}return $}threadOf(J){return this.runs.get(J)?.threadId}get(J){return this.runs.get(J)?.run??null}ownerOf(J){return this.runs.get(J)?.owner??null}mayAccess(J,$){let Q=this.ownerOf(J);return Q===null||Q===$}isRunning(J){let $=this.runs.get(J);return!!$&&!$.ended&&!$.evicted}replay(J,$){let Q=this.runs.get(J);if(!Q)throw new FJ(J);if($!==void 0&&$<Q.lostBefore)throw new WJ(J,$,Q.lostBefore);let Z=Q.frames[0]?.seq;return this.drain(Q,J,$??Z??Q.lastSeq+1)}clear(){for(let J of this.runs.values()){if(J.evictAt)clearTimeout(J.evictAt);if(J.expireAt)clearTimeout(J.expireAt);J.ended=!0,this.notify(J)}this.runs.clear(),this.byThread.clear(),this.threadRuns.clear(),this.byClientRun.clear()}get size(){return this.runs.size}async pump(J,$){let Q=Promise.resolve();try{for await(let Z of J.run.frames()){if(J.evicted){let X=$.onEvent;if(X)Q=Q.then(()=>X(Z.event)).catch((K)=>A$($,K));continue}if(J.frames.push(Z),J.lastSeq=Z.seq,J.frames.length>this.maxFrames){let X=J.frames.shift();if(X)J.lostBefore=X.seq+1}this.notify(J);let W=$.onEvent;if(W)Q=Q.then(()=>W(Z.event)).catch((X)=>A$($,X))}}catch(Z){A$($,Z)}finally{if(J.ended=!0,J.expireAt)clearTimeout(J.expireAt),J.expireAt=null;this.notify(J),this.scheduleEviction(J),await Q}}async*drain(J,$,Q){let Z=Q;while(!0){let W=J.version;for(;;){if(Z<J.lostBefore)throw new WJ($,Z,J.lostBefore);let X=J.frames,K=X[0]?.seq;if(K===void 0)break;let G=Math.max(0,Z-K);if(G>=X.length)break;let z=X[G];yield z,Z=z.seq+1}if(J.ended&&Z>J.lastSeq||J.evicted)return;await this.wait(J,W)}}wait(J,$){if(J.version!==$)return Promise.resolve();return new Promise((Q)=>J.wake.add(Q))}notify(J){J.version++;let $=Array.from(J.wake);J.wake.clear();for(let Q of $)Q()}scheduleEviction(J){if(J.evictAt)return;let $=setTimeout(()=>{let Q=J.run.runId;if(!J.ended)J.evicted=!0,J.frames=[];if(this.runs.get(Q)===J)this.runs.delete(Q);if(J.threadId&&this.byThread.get(J.threadId)===Q)this.byThread.delete(J.threadId);if(J.threadId){let Z=this.threadRuns.get(J.threadId);if(Z?.delete(Q),Z?.size===0)this.threadRuns.delete(J.threadId)}if(J.clientRunId&&this.byClientRun.get(J.clientRunId)===Q)this.byClientRun.delete(J.clientRunId);this.notify(J)},this.ttlMs);$.unref?.(),J.evictAt=$}scheduleExpiry(J,$){if(this.maxAgeMs===null||$===null)return;let Q=$===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,$+this.ttlMs);if(!Number.isFinite(Q)||Q>2147483647)return;let Z=setTimeout(()=>{if(J.expireAt=null,J.ended)return;try{J.run.stop({reason:`The run was still going ${Math.round(Q/1000)}s after it started, past the live-run registry's age limit.`})}catch{}this.scheduleEviction(J)},Q);Z.unref?.(),J.expireAt=Z}}var R$=new gJ;function A$(J,$){try{J.onInternalError?.($)}catch{}}class cJ{maxEntries;records=new Map;constructor(J=1e5){this.maxEntries=J}async record(J,$){if(this.records.has(J))return;this.records.set(J,{...$});while(this.records.size>this.maxEntries){let Q=this.records.keys().next().value;if(Q===void 0)break;this.records.delete(Q)}}async get(J){let $=this.records.get(J);return $?{...$}:null}async delete(J){this.records.delete(J)}async expired(J,$){let Q=[];for(let[Z,W]of this.records){if(Q.length>=$)break;if(W.expiresAt&&Date.parse(W.expiresAt)<=J.getTime())Q.push(Z)}return Q}}var E$=new cJ;class j${now;receipts=new Map;sweepAt=1024;constructor(J=Date.now){this.now=J}async claim(J,$){let Q=this.now();if(this.receipts.size>=this.sweepAt)this.sweep(Q);let Z=this.receipts.get(J);if(Z&&Z.expiresAt>Q)return Z.result?{status:"replay",result:structuredClone(Z.result)}:{status:"blocked"};return this.receipts.set(J,{expiresAt:$}),{status:"claimed"}}async complete(J,$,Q){this.receipts.set(J,{result:structuredClone($),expiresAt:Q})}async release(J){let $=this.receipts.get(J);if($&&!$.result)this.receipts.delete(J)}get size(){return this.receipts.size}sweep(J){for(let[$,Q]of this.receipts)if(Q.expiresAt<=J)this.receipts.delete($);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var FZ="pending",k$="done:",B9=`
|
|
319
319
|
if redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2], 'NX') then return 'claimed' end
|
|
320
320
|
local held = redis.call('GET', KEYS[1])
|
|
321
321
|
if not held then return ARGV[1] end
|
|
322
|
-
return held
|
|
322
|
+
return held`,M9=`
|
|
323
323
|
if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end
|
|
324
|
-
return 0`;class A${injectedClient;prefix;constructor(J={}){this.injectedClient=J.client,this.prefix=J.prefix??"gemi:ai:receipt"}async claim(J,$){let Q=await this.client.send("EVAL",[J9,"1",this.key(J),KZ,XZ($)]);if(Q==="claimed")return{status:"claimed"};let Z=String(Q??"");if(Z.startsWith(B$))return{status:"replay",result:JSON.parse(Z.slice(B$.length))};return{status:"blocked"}}async complete(J,$,Q){await this.client.send("SET",[this.key(J),B$+JSON.stringify($),"PX",XZ(Q)])}async release(J){await this.client.send("EVAL",[$9,"1",this.key(J),KZ])}key(J){return`${this.prefix}:${J}`}get client(){if(this.injectedClient)return this.injectedClient;let J=GZ(),$=J.bound(S$)?J.make(S$).client:void 0;if(!$)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return $}}function XZ(J){return String(Math.max(1,Math.ceil(J-Date.now())))}var Q9=86400000,Z9=60000;class PJ{ttlMs;slidingTtl;clientOwnedIds;scope=null;threads=new Map;lastSweep=0;constructor(J={}){this.ttlMs=J.ttlMs??Q9,this.slidingTtl=J.slidingTtl??!0,this.clientOwnedIds=J.clientOwnedIds??!1}forScope(J){if(typeof J!=="string"||J==="")throw TypeError("A MemoryAgentStore scope is a non-empty string.");let $=new PJ({ttlMs:this.ttlMs,slidingTtl:this.slidingTtl,clientOwnedIds:this.clientOwnedIds});return $.threads=this.threads,$.scope=J,$}visible(J,$=Date.now()){let Q=this.threads.get(J);if(Q&&R$(Q,$)){this.threads.delete(J);return}if(!Q||this.scope===null||Q.scope===this.scope)return Q;return}fresh(J={}){let $=Date.now(),Q,Z=null;if(J.expiresAt!==void 0){if(Q=J.expiresAt instanceof Date?J.expiresAt.getTime():J.expiresAt,!Number.isFinite(Q))throw TypeError("createThread: `expiresAt` is not a valid time.")}else{let W=J.ttlMs===void 0?this.ttlMs:J.ttlMs;if(W!==null&&!(typeof W==="number"&&W>0))throw TypeError("createThread: ttlMs must be a positive number of milliseconds.");Q=W===null?null:$+W,Z=this.slidingTtl?W:null}return{messages:[],expiresAt:Q,slideMs:Z,...this.scope!==null?{scope:this.scope}:{}}}touch(J){if(J.slideMs!==null)J.expiresAt=Date.now()+J.slideMs}async createThread(J={}){let $=crypto.randomUUID();return this.threads.set($,this.fresh(J)),this.sweep(),{threadId:$}}async loadThread(J){this.sweep();let $=this.visible(J);if(!$){if(this.threads.has(J))return null;return this.clientOwnedIds?[]:null}return this.touch($),$.messages.slice()}async appendMessages(J,$){this.sweep();let Q=this.visible(J);if(!Q){if(!this.clientOwnedIds||this.threads.has(J))throw Error(`Thread ${J} does not exist here, or has expired.`);Q=this.fresh(),this.threads.set(J,Q)}for(let Z of $){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}this.touch(Q)}async removeMessages(J,$){this.sweep();let Q=this.visible(J);if(!Q)return;let Z=new Set($);Q.messages=Q.messages.filter((W)=>!Z.has(W.id)),this.touch(Q)}async loadSummaries(J){return this.visible(J)?.summaries?.slice()??[]}async saveSummary(J,$){let Q=this.visible(J);if(!Q)return;Q.summaries=DJ(Q.summaries??[],$)}delete(J){if(this.visible(J))this.threads.delete(J)}get size(){return this.threads.size}sweep(J=Date.now()){if(J-this.lastSweep<Z9)return;this.lastSweep=J;for(let[$,Q]of this.threads)if(R$(Q,J))this.threads.delete($)}async sweepExpired(J={}){let $=J.now??Date.now(),Q=Math.max(0,Math.floor(J.limit??500)),Z=0;for(let[W,K]of this.threads){if(Q===0)break;if(this.scope!==null&&K.scope!==this.scope)continue;if(R$(K,$))this.threads.delete(W),Z+=1,Q-=1}return{deleted:Z}}}function R$(J,$){return J.expiresAt!==null&&$>=J.expiresAt}var E$=new PJ;function DZ(J={}){return{messages:J.messages?[...J.messages]:[],pending:J.pending?[...J.pending]:[],error:null,threadId:J.threadId,seq:J.seq??-1,cursorRunId:J.cursorRunId,runMessageIds:[],loadedTools:[]}}function HZ(J,$,Q=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==J.cursorRunId)&&$.seq<=J.seq)return J;return{...PZ(J,$.event,Q),seq:$.seq}}function PZ(J,$,Q){switch($.type){case"run-start":return{...J,messages:W9(J.messages,$.runId),runId:$.runId,cursorRunId:$.runId,threadId:$.threadId??J.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return v(J,$.messageId,Q,(Z)=>({...Z,role:$.role}));case"text-delta":if(VZ(J,$.messageId))return J;return v(J,$.messageId,Q,(Z)=>({...Z,content:V9(Z.content,$.delta)}));case"reasoning-delta":if(VZ(J,$.messageId))return J;return v(J,$.messageId,Q,(Z)=>({...Z,content:z9(Z.content,$.delta,$.id,$.providerMetadata)}));case"output-delta":return v(J,$.messageId,Q,(Z)=>({...Z,content:zZ(Z.content,{type:"output",value:$.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return v(J,$.messageId,Q,(Z)=>{let W=Z.content.findIndex((D)=>D.type==="tool-call"&&D.toolCallId===$.part.toolCallId),K=W===-1?void 0:Z.content[W],X=$.part.progress??K?.progress,G=$.part.nested??K?.nested,V=$.part.attachments??K?.attachments,Y={...$.part,...X?{progress:X}:{},...G?{nested:G}:{},...V?{attachments:V}:{}},z=Z.content.slice();if(W===-1)z.push(Y);else z[W]=Y;return{...Z,content:z}});case"tool-call-discard":return v(J,$.messageId,Q,(Z)=>{let W=Z.content.filter((K)=>!(K.type==="tool-call"&&K.partial&&$.toolCallIds.includes(K.toolCallId)));return W.length===Z.content.length?Z:{...Z,content:W}});case"tool-search":{let Z=$.loaded.filter((W)=>!J.loadedTools.includes(W));if(Z.length===0)return J;return{...J,loadedTools:[...J.loadedTools,...Z]}}case"tool-progress":return YZ(J,$.toolCallId,(Z)=>({...Z,progress:[...Z.progress??[],$.data]}));case"nested-event":{let Z=$;return YZ(J,$.toolCallId,(W)=>{let K=W.nested??[],X=K.findIndex((z)=>z.runId===Z.runId),G=K[X]??{runId:Z.runId,agent:Z.agent,messages:[]},V=G9(G,Z,Q),Y=X===-1?[...K,V]:K.map((z,D)=>D===X?V:z);return{...W,nested:Y}})}case"tool-result":{let Z=v(J,$.messageId,Q,(W)=>({...W,content:zZ(W.content,$.part,(K)=>K.type==="tool-result"&&K.toolCallId===$.part.toolCallId)}));return{...Z,pending:Z.pending.filter((W)=>W.toolCallId!==$.part.toolCallId)}}case"message":{let Z=J.messages.findIndex((X)=>X.id===$.message.id),W=J.messages.slice();if(Z===-1)W.push($.message);else W[Z]=$.message;let K=J.runMessageIds.includes($.message.id)?J.runMessageIds:[...J.runMessageIds,$.message.id];return{...J,messages:W,runMessageIds:K}}case"message-id":{let Z=J.messages.findIndex((G)=>G.id===$.localId);if(Z===-1){if(!$.message||J.messages.some((G)=>G.id===$.messageId))return J;return{...J,messages:[...J.messages,$.message]}}let W=J.messages[Z],K={localId:W.localId??W.id,...W.metadata?{metadata:W.metadata}:{}},X=J.messages.some((G)=>G.id===$.messageId)?J.messages.filter((G,V)=>V!==Z).map((G)=>G.id===$.messageId?{...G,...K}:G):J.messages.map((G,V)=>V===Z?{...G,...K,id:$.messageId}:G);return{...J,messages:X}}case"awaiting-input":return{...J,runId:$.runId,pending:[...$.pending]};case"message-end":return v(J,$.messageId,Q,(Z)=>({...Z,finishReason:$.finishReason,...$.outputTruncated?{outputTruncated:!0}:{},...$.usage?{usage:$.usage}:{},content:$.outputTruncated||$.finishReason==="length"?Z.content.filter((W)=>!(W.type==="output"&&W.partial)):Z.content.map((W)=>W.type==="output"&&W.partial?{...W,partial:!1}:W)}));case"usage":return{...J,usage:$.usage};case"retry":return J;case"error":return{...J,error:$.error,pending:[]};case"run-end":return{...J,runId:void 0,finishReason:$.finishReason,messages:NZ(J,$.finishReason)};default:return J}}function W9(J,$){if(!J.some((Q)=>Q.runId===$&&Q.finishReason===void 0))return J;return J.map((Q)=>{if(Q.runId!==$||Q.finishReason!==void 0)return Q;let{runId:Z,...W}=Q;return{...W,content:[]}})}function NZ(J,$){return J.messages.map((Q)=>Q.role==="assistant"&&J.runMessageIds.includes(Q.id)?K9(Q,$):Q)}function K9(J,$){let Q=J.content.map((W)=>W.type==="tool-call"&&W.nested?.some((K)=>K.finishReason===void 0)?{...W,nested:W.nested.map((K)=>K.finishReason===void 0?X9(K,$):K)}:W);if(J.finishReason===void 0)return{...J,finishReason:$,content:Q};return Q.some((W,K)=>W!==J.content[K])?{...J,content:Q}:J}function X9(J,$){let Q={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((Z)=>Z.id),loadedTools:[]};return{...J,finishReason:$,messages:NZ(Q,$)}}function YZ(J,$,Q){for(let Z=J.messages.length-1;Z>=0;Z--){let W=J.messages[Z],K=W.content.findIndex((Y)=>Y.type==="tool-call"&&Y.toolCallId===$);if(K===-1)continue;if(W.finishReason!==void 0&&!Y9(J,W,$))return J;let X=W.content.slice();X[K]=Q(X[K]);let G=J.messages.slice();G[Z]={...W,content:X};let V=J.runMessageIds.includes(W.id)?J.runMessageIds:[...J.runMessageIds,W.id];return{...J,runMessageIds:V,messages:G}}return J}function G9(J,$,Q){let Z={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((K)=>K.id),loadedTools:[],finishReason:J.finishReason},W=PZ(Z,$.event,Q);return{...J,...$.label!==void 0?{label:$.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function Y9(J,$,Q){if($.finishReason!=="awaiting-input")return!1;return!J.messages.some((Z)=>Z.content.some((W)=>W.type==="tool-result"&&W.toolCallId===Q))}function VZ(J,$){let Q=J.messages.find((Z)=>Z.id===$);return Q!==void 0&&Q.finishReason!==void 0}function v(J,$,Q,Z){let W=J.messages.findIndex((G)=>G.id===$),K=J.runMessageIds.includes($)?J.runMessageIds:[...J.runMessageIds,$];if(W===-1){let G={id:$,role:"assistant",content:[],createdAt:Q};return{...J,runMessageIds:K,messages:[...J.messages,Z(G)]}}let X=J.messages.slice();return X[W]=Z(X[W]),{...J,runMessageIds:K,messages:X}}function V9(J,$){let Q=J[J.length-1];if(Q&&Q.type==="text")return[...J.slice(0,-1),{type:"text",text:Q.text+$}];return[...J,{type:"text",text:$}]}function z9(J,$,Q,Z){let W=J[J.length-1];if(W&&W.type==="reasoning"&&W.id===Q&&!W.providerMetadata)return[...J.slice(0,-1),{...W,text:(W.text??"")+$,...Z?{providerMetadata:Z}:{}}];return[...J,{type:"reasoning",...Q?{id:Q}:{},text:$,...Z?{providerMetadata:Z}:{}}]}function zZ(J,$,Q){let Z=J.findIndex(Q);if(Z===-1)return[...J,$];let W=J.slice();return W[Z]=$,W}class T${store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(J,$,Q,Z){this.store=J;this.threadId=$;this.report=Z;this.state=DZ({messages:Q})}finish(J){if(this.closed)return;this.done.add(J.id),this.write(()=>[k$(J)])}frame(J){if(this.closed)return;let $=J.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=HZ(this.state,J),$.type){case"message":this.write(()=>[k$($.message)]);return;case"tool-call":if($.part.partial)return;this.checkpoint($.messageId);return;case"message-start":case"tool-result":this.checkpoint($.messageId);return;default:return}}close(J=[]){this.closed=!0;for(let $ of J)this.done.add($.id)}settled(){return this.chain}checkpoint(J){if(this.done.has(J))return;let $=this.state.messages.find((Z)=>Z.id===J);if(!$)return;let Q=this.runId;this.write(()=>{let Z=k$($);if(Z.finishReason===void 0&&Q)Z.runId=Q;return[Z]})}write(J){let $;try{$=J()}catch(Q){this.report(Q);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,$)).catch((Q)=>this.report(Q))}}function k$(J){return structuredClone(J)}async function FZ(J,$){let Q=[],Z=null,W=J.slice();for(let K=0;K<W.length;K++){let X=W[K];if(X.role!=="assistant"||X.finishReason!==void 0)continue;if(X.runId&&await $(X.runId))continue;Z??=new Set(J.flatMap((Y)=>Y.content.flatMap((z)=>z.type==="tool-result"?[z.toolCallId]:[])));let G=X.content.map((Y)=>Y.type==="tool-call"?OZ(Y):Y);for(let Y of X.content){if(Y.type!=="tool-call"||Z.has(Y.toolCallId))continue;let z={type:"tool-result",toolCallId:Y.toolCallId,name:Y.name,status:"denied",cause:"interrupted"};G.push(z)}let V={...X,content:G,finishReason:"interrupted"};W[K]=V,Q.push(V)}return{messages:W,settled:Q}}function OZ(J){let{partial:$,...Q}=J;if(!Q.nested?.some((Z)=>Z.finishReason===void 0))return Q;return{...Q,nested:Q.nested.map(D9)}}function D9(J){if(J.finishReason!==void 0)return J;return{...J,finishReason:"interrupted",messages:J.messages.map(($)=>$.role==="assistant"&&$.finishReason===void 0?{...$,finishReason:"interrupted",content:$.content.map((Q)=>Q.type==="tool-call"?OZ(Q):Q)}:$)}}var H9=50,P9=["waiting","running","ok","error"];async function LZ(J,$){let{store:Q,threadId:Z}=$,W=Math.max(H9,$.scan??0),K=await Q.listForThread(Z,{limit:W}),X,G=async(H)=>{if(H.state!=="running")return H;if(X??=await UZ(Q),H.deadlineAt>X)return H;return await CZ(Q,H),await Q.get(H.id)??H};for(let H=0;H<K.length;H++)K[H]=await G(K[H]);let V=new Map(K.map((H)=>[H.id,H])),Y=J.slice(),z=[],D=new Set;for(let H=0;H<Y.length;H++){let C=Y[H],O=null;for(let P=0;P<C.content.length;P++){let F=C.content[P];if(F.type==="tool-call")D.add(F.toolCallId);if(F.type!=="tool-result"||F.status!=="running")continue;let U=F.job?.id,L=U?V.get(U):void 0;if(U&&L===void 0){let R=await Q.get(U);if(L=R?await G(R):void 0,L)V.set(U,L)}if(L&&!b(L.state))continue;O??=C.content.slice(),O[P]=N9(F,L,$.outputSchemaFor,$.modelOutputFor)}if(O){let P={...C,content:O};Y[H]=P,z.push(P)}}let N=[];for(let H of K){if(H.orphaned||H.toolCallId===""||D.has(H.toolCallId))continue;if(await $.isRunLive(H.runId))continue;N.push(H)}return{messages:Y,settled:z,orphans:N,jobs:K}}async function _Z(J,$,Q){for(let Z of $)try{await J.transition(Z.id,P9,{orphaned:!0})}catch(W){Q(W)}}function N9(J,$,Q,Z){let W={type:"tool-result",toolCallId:J.toolCallId,name:J.name},K=(V,Y)=>{let z=Z?.(String(J.name),V);return{...W,status:"ok",job:Y,output:V,...z!==void 0?{modelOutput:z}:{}}};if(!$)return{...W,status:"error",job:J.job,error:{code:"tool_error",message:`The background job for "${String(J.name)}" can no longer be found, so its result was lost. It may have run in part or in full: check its effects before repeating it.`,toolCallId:J.toolCallId,retryable:!0}};let X={id:$.id,...$.summary!==void 0?{summary:$.summary}:{},...$.usage?{usage:$.usage}:{}};if($.state==="error")return{...W,status:"error",job:X,error:$.error??{code:"tool_error",message:`The background job for "${String(J.name)}" failed.`,toolCallId:J.toolCallId,retryable:!0}};let G=Q?.(String(J.name));if(G){let V=G.safeParse($.output);if(V.ok===!1)return{...W,status:"error",job:X,error:{code:"invalid_tool_result",message:`The background job for "${String(J.name)}" finished with an output that does not match the tool's output schema: ${V.errors.join(", ")}`,toolCallId:J.toolCallId,retryable:!0}};return K(V.value,X)}return K($.output,X)}var F9=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;class lJ extends Error{status;code;kind;constructor(J,$){super(J);this.name="AgentTurnError",this.status=$.status,this.code=$.code,this.kind=$.kind}static async from(J){let $={};try{let Z=await J.json();if(Z?.error&&typeof Z.error==="object")$=Z.error}catch{}let Q=(Z)=>typeof $[Z]==="string"?$[Z]:void 0;return new lJ(Q("message")??`The agent turn was refused with status ${J.status}.`,{status:J.status,code:Q("code"),kind:Q("kind")})}}function O9(J){for(let $=J.length-1;$>=0;$--){let Q=J[$];if(Q.role!=="assistant")continue;return Q.content.map((Z)=>Z.type==="text"?Z.text:"").join("")}return""}var U9=qZ,NJ=new Map,j$=new WeakMap,JJ=new WeakMap,BZ=new WeakMap,SZ=new WeakMap,x$=new WeakMap,Q8="thread_busy",MZ="http://gemi.internal/__gemi/agent-turn",bJ=new Map,C9=4194304,L9=1000,_9=5,FJ=65536,QJ=()=>{};class Z8{byKey=new Map;take(J,$,Q){let Z=this.byKey.get(J);if(!Z?.has($)&&(Z?.size??0)>=Q)return null;if(!Z)Z=new Map,this.byKey.set(J,Z);Z.set($,(Z.get($)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let K=this.byKey.get(J),X=(K?.get($)??1)-1;if(!K)return;if(X>0)K.set($,X);else if(K.delete($),K.size===0)this.byKey.delete(J)}}}var AZ=new WeakMap,f$=new WeakMap;function B9(J){let $=f$.get(J);if(!$)$=new Map,f$.set(J,$);return $}function S9(J,$,Q){let Z=f$.get(J)?.get($);if(!Z)return;for(let W of[...Z])try{W(Q)}catch{}}function M9(J){let $=AZ.get(J);if(!$)$=new Z8,AZ.set(J,$);return $}function A9(J){return J}class gJ extends U9{static kind="agent-controller";hooks;store=E$;storeScope(J,$){return null}boundScope=void 0;async threadInScope(J,$){if(await this.scopeStore(J,{}),this.boundScope===null)return!0;return await this.store.loadThread($)!==null}async scopeStore(J,$){let Z=BZ.get(J)??await this.storeScope(J,{body:$})??null;if(this.boundScope!==void 0){if(this.boundScope!==Z)throw Error("This AgentController instance already served a request in another store scope. Build a controller per request (the router and startTurn do).");return}if(Z!==null)this.store=yZ(this.store,Z);this.boundScope=Z}liveRuns=L$;voice;voiceStore=O$;attachments=pJ;attachmentStorage=gZ;turnAttachmentMaxAgeMs=3600000;fileOwners=_$;nonces=g$;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=C9;maxHistoryMessages=L9;contextWindow=void 0;prepareStep(J,$){return this.hooks?.prepareStep?.(J,$)}maxConcurrentRuns=_9;runLimitKey(J,$){let Q=this.hooks?.runLimitKey;if(Q)return Q(J,$);return $.owner}authorizeRequest(J,$){let Q=this.hooks?.authorizeRequest;if(Q)return Q(J,$);return this.resource?.authorize(J,$)}resource;runOwner(J){let $=this.hooks?.runOwner;if($)return $(J);let Q=J.ctx?.()?.user,Z=Q?.id??Q?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}static async startTurn(J){let{threadId:$}=J;if(typeof $!=="string"||$==="")throw TypeError("AgentController.startTurn needs a `threadId`: a server turn is stored on a thread. Create one with the store's `createThread`.");let Q=J.ifBusy??"supersede";if(Q!=="supersede"&&Q!=="queue"&&Q!=="skip")throw TypeError(`AgentController.startTurn's \`ifBusy\` is "supersede", "queue" or "skip"; got ${JSON.stringify(J.ifBusy)}.`);let Z=J.event===void 0?void 0:q9(J),W={...J.turn,...J.text!==void 0?{text:J.text}:{}},K={...J.body,threadId:$,turn:W},X=new I(new Request(MZ,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(K)}),{},"api",new URL(MZ).pathname),G=new this;if(JJ.set(X,null),J.scope!==void 0)BZ.set(X,J.scope);if(SZ.set(X,Q),Z)x$.set(X,Z);let V=await c.run(X,()=>G.stream(X),{user:J.user??null}),Y=JJ.get(X);if(!Y){let O=await lJ.from(V);if(Q==="skip"&&O.code===Q8)return{skipped:!0,threadId:$};throw O}JJ.delete(X),V.body?.cancel().catch(QJ);let{run:z,hooks:D}=Y,N=[],H=(async()=>{for await(let O of z)if(O.type==="awaiting-input")N=O.pending})().catch(QJ),C;return{runId:z.runId,threadId:$,run:z,stop:(O)=>z.stop(O),result:()=>C??=(async()=>{let O=await z.result();await Promise.all([D,H]);let P=O.messages;return{...O,threadId:$,text:O9(P),pending:O.finishReason==="awaiting-input"?N:[]}})()}}async stream(J=new I){let $=await $J(J,this.maxBodyBytes);if($.error)return l($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:void 0,W=w9(Q);if(W.error)return l({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=hJ(Q);if(this.requireThread&&!Z)return B(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(await this.scopeStore(J,V),X&&!this.store.removeMessages)return B(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 v$(413,"history_too_long",`The conversation has ${Q.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let Y=await this.runOwner(J),z=G?{cancelled:!1,owner:Y}:null;if(z)bJ.set(G,z);let D=null,N=[],H=async()=>{try{return await C()}finally{if(Z&&N.length>0&&D===null)await this.store.appendMessages(Z,N).catch((O)=>this.reportHookFailure(O))}},C=async()=>{let O,P=null;if(Z){let M=await this.store.loadThread(Z);if(!M)return B(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let d=await this.settleThread(Z,M,{write:!0});if(O=d.messages,P=this.jobsBlock(d.jobs),X){let ZJ=b9(O);if(!ZJ)return B(409,{code:"nothing_to_regenerate",message:`Thread ${Z} has no user turn to answer again.`});N=O.slice(ZJ.index),await this.store.removeMessages(Z,N.map((V8)=>V8.id)),O=O.slice(0,ZJ.index),K=K?.localId?{...ZJ.turn,localId:K.localId}:ZJ.turn}}else O=Array.isArray(Q.messages)?Q.messages:[],l9(this.nonces);let F=[await this.instructions(J,{body:V})||void 0,P??void 0].filter(Boolean).join(`
|
|
324
|
+
return 0`;class x${injectedClient;prefix;constructor(J={}){this.injectedClient=J.client,this.prefix=J.prefix??"gemi:ai:receipt"}async claim(J,$){let Q=await this.client.send("EVAL",[B9,"1",this.key(J),FZ,UZ($)]);if(Q==="claimed")return{status:"claimed"};let Z=String(Q??"");if(Z.startsWith(k$))return{status:"replay",result:JSON.parse(Z.slice(k$.length))};return{status:"blocked"}}async complete(J,$,Q){await this.client.send("SET",[this.key(J),k$+JSON.stringify($),"PX",UZ(Q)])}async release(J){await this.client.send("EVAL",[M9,"1",this.key(J),FZ])}key(J){return`${this.prefix}:${J}`}get client(){if(this.injectedClient)return this.injectedClient;let J=CZ(),$=J.bound(T$)?J.make(T$).client:void 0;if(!$)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return $}}function UZ(J){return String(Math.max(1,Math.ceil(J-Date.now())))}var S9=86400000,A9=60000;class UJ{ttlMs;slidingTtl;clientOwnedIds;scope=null;threads=new Map;lastSweep=0;constructor(J={}){this.ttlMs=J.ttlMs??S9,this.slidingTtl=J.slidingTtl??!0,this.clientOwnedIds=J.clientOwnedIds??!1}forScope(J){if(typeof J!=="string"||J==="")throw TypeError("A MemoryAgentStore scope is a non-empty string.");let $=new UJ({ttlMs:this.ttlMs,slidingTtl:this.slidingTtl,clientOwnedIds:this.clientOwnedIds});return $.threads=this.threads,$.scope=J,$}visible(J,$=Date.now()){let Q=this.threads.get(J);if(Q&&w$(Q,$)){this.threads.delete(J);return}if(!Q||this.scope===null||Q.scope===this.scope)return Q;return}fresh(J={}){let $=Date.now(),Q,Z=null;if(J.expiresAt!==void 0){if(Q=J.expiresAt instanceof Date?J.expiresAt.getTime():J.expiresAt,!Number.isFinite(Q))throw TypeError("createThread: `expiresAt` is not a valid time.")}else{let W=J.ttlMs===void 0?this.ttlMs:J.ttlMs;if(W!==null&&!(typeof W==="number"&&W>0))throw TypeError("createThread: ttlMs must be a positive number of milliseconds.");Q=W===null?null:$+W,Z=this.slidingTtl?W:null}return{messages:[],expiresAt:Q,slideMs:Z,...this.scope!==null?{scope:this.scope}:{}}}touch(J){if(J.slideMs!==null)J.expiresAt=Date.now()+J.slideMs}async createThread(J={}){let $=crypto.randomUUID();return this.threads.set($,this.fresh(J)),this.sweep(),{threadId:$}}async loadThread(J){this.sweep();let $=this.visible(J);if(!$){if(this.threads.has(J))return null;return this.clientOwnedIds?[]:null}return this.touch($),$.messages.slice()}async appendMessages(J,$){this.sweep();let Q=this.visible(J);if(!Q){if(!this.clientOwnedIds||this.threads.has(J))throw Error(`Thread ${J} does not exist here, or has expired.`);Q=this.fresh(),this.threads.set(J,Q)}for(let Z of $){let W=JSON.parse(JSON.stringify(Z)),X=Q.messages.findIndex((K)=>K.id===W.id);if(X===-1)Q.messages.push(W);else Q.messages[X]=W}this.touch(Q)}async removeMessages(J,$){this.sweep();let Q=this.visible(J);if(!Q)return;let Z=new Set($);Q.messages=Q.messages.filter((W)=>!Z.has(W.id)),this.touch(Q)}async loadSummaries(J){return this.visible(J)?.summaries?.slice()??[]}async saveSummary(J,$){let Q=this.visible(J);if(!Q)return;Q.summaries=NJ(Q.summaries??[],$)}delete(J){if(this.visible(J))this.threads.delete(J)}get size(){return this.threads.size}sweep(J=Date.now()){if(J-this.lastSweep<A9)return;this.lastSweep=J;for(let[$,Q]of this.threads)if(w$(Q,J))this.threads.delete($)}async sweepExpired(J={}){let $=J.now??Date.now(),Q=Math.max(0,Math.floor(J.limit??500)),Z=0;for(let[W,X]of this.threads){if(Q===0)break;if(this.scope!==null&&X.scope!==this.scope)continue;if(w$(X,$))this.threads.delete(W),Z+=1,Q-=1}return{deleted:Z}}}function w$(J,$){return J.expiresAt!==null&&$>=J.expiresAt}var I$=new UJ;class OZ{buffer="";textDecoder=new TextDecoder;pendingCR=!1;lastSeq=-1;get cursor(){return this.lastSeq}push(J){return this.append(typeof J==="string"?J:this.textDecoder.decode(J,{stream:!0})),this.drain()}flush(){this.append(this.textDecoder.decode());let J=this.drain();return this.buffer="",this.pendingCR=!1,J}append(J){if(J==="")return;let $=J;if(this.pendingCR){if(this.buffer+=`
|
|
325
|
+
`,this.pendingCR=!1,$.startsWith(`
|
|
326
|
+
`))$=$.slice(1)}if($.endsWith("\r"))$=$.slice(0,-1),this.pendingCR=!0;this.buffer+=$.replace(/\r\n/g,`
|
|
327
|
+
`).replace(/\r/g,`
|
|
328
|
+
`)}drain(){let J=[],$=this.buffer.indexOf(`
|
|
325
329
|
|
|
326
|
-
`)||void 0,U=await this.context(J,{body:V}),L=await this.reasoning(J,{body:V})||void 0,R=await this.skills(J,{body:V})||void 0,E=await this.runTools(J,{body:V,context:U})||void 0,j=await this.usageLimits(J,{body:V,context:U})||void 0,x=await this.attachmentsFor(J,Z,{body:V}),y=await this.attachmentRetention(J,{route:"stream",threadId:Z,body:V});vJ(y,this.turnAttachmentMaxAgeMs);let _=[],k=x&&y?x.withLifetime({next:()=>vJ(y,this.turnAttachmentMaxAgeMs),onPut:(M)=>_.push(M)}):x,S=this.agent.memory?await this.memoryScopes(J,{body:V}):void 0;if(z?.cancelled)return xZ();let h=Z?new T$(this.store,Z,O,(M)=>this.reportHookFailure(M)):null,p$=`run_${crypto.randomUUID()}`,l$=[],i={req:J,runId:p$,threadId:Z,get denials(){return l$}},UJ={id:null,notified:Promise.resolve()},f=this.agent.stream({runId:p$,messages:O,turn:K,threadId:Z,...h?{onMessage:(M)=>h.finish(M)}:{},onTurn:(M)=>{if(UJ.id!==null)return;UJ.id=M.id;let d=h?h.settled():Promise.resolve();UJ.notified=d.then(()=>this.safely(()=>this.onMessage(M,i)))},instructions:F,...x$.has(J)?{event:x$.get(J)}:{},...JJ.has(J)?{echoTurn:!0}:{},...L?{reasoning:L}:{},...R&&R.length>0?{skills:R}:{},...E?.tools&&E.tools.length>0?{tools:E.tools}:{},...E?.activeTools?{activeTools:E.activeTools}:{},...j?{usageLimits:j}:{},context:U,attachments:k,body:V,redactError:(M,d)=>this.redactError(M,d,i),onProviderRetry:(M)=>this.onProviderRetry(M,i),nonces:this.nonces,receipts:this.receipts,subject:Y,...S?{memory:{scopes:S,...this.memoryMaxTokens!==void 0?{maxTokens:this.memoryMaxTokens}:{}}}:{},...Z?{jobs:{owner:Y}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...Z&&eZ(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==gJ.prototype.prepareStep||this.hooks?.prepareStep?{prepareStep:(M)=>this.prepareStep(M,i)}:{}});l$=f.denials;let X8=this.liveRuns.register(f,{threadId:Z,owner:Y,clientRunId:G,onEvent:(M)=>this.dispatchEvent(M,i),onInternalError:(M)=>this.reportHookFailure(M),maxRunDurationMs:this.agent.maxRunDurationMs});if(D=f,h)this.follow(f,h);if(Z)S9(this.liveRuns,Z,f.runId);let i$=K?.files??[],G8=this.definesRetention()&&(i$.length>0||y==="turn")?()=>this.expireTurn({scoped:x,files:i$,made:_,owner:Y}):null,{stored:Y8,hooks:d$}=this.persistRun(f,i,X8,h,UJ,G8);if(j$.set(f,Y8),JJ.has(J))JJ.set(J,{run:f,hooks:d$});return J.ctx?.()?.waitUntil(d$),f.toResponse()};try{await this.authorizeRequest(J,{route:"stream",threadId:Z,body:V});let O=await this.foreignFile([...K?.files??[],...Z?[]:h9(Q.messages)],Y);if(O)return O;if(z?.cancelled)return xZ();let P=await this.runLimitKey(J,{owner:Y,threadId:Z}),F=P===null?QJ:M9(this.liveRuns).take(P,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!F)return v$(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,H,SZ.get(J)??"supersede"):await H()}finally{let U=D;if(U)U.result().then(F,F);else F()}}finally{if(z&&bJ.get(G)===z)bJ.delete(G)}}async withThread(J,$,Q,Z="supersede"){if(Z==="skip"&&NJ.has(J))return IZ(J);for(;;){let W=await this.underThreadLock(J,$,Q,Z);if(!("waitFor"in W))return W.response;await W.waitFor}}async underThreadLock(J,$,Q,Z){let W=NJ.get(J)??Promise.resolve(),K,X=new Promise((V)=>{K=V}),G=W.then(()=>X);NJ.set(J,G),await W;try{let V=await this.liveRuns.find({threadId:J});if(V&&Z!=="supersede"&&this.liveRuns.isRunning(V.runId)){if(Z==="skip")return{response:IZ(J)};let z=this.liveRuns.get(V.runId),D=z?j$.get(z)??z.result():null;if(D)return{waitFor:D.then(QJ,QJ)}}if(V&&this.liveRuns.isRunning(V.runId)&&!this.liveRuns.mayAccess(V.runId,$))return{response:OJ()};let Y=V?this.liveRuns.get(V.runId):null;if(Y)Y.stop({reason:"superseded by a later turn on this thread"}),await j$.get(Y);return{response:await Q()}}finally{if(K(),NJ.get(J)===G)NJ.delete(J)}}async attach(J=new I){let $=await $J(J,FJ);if($.error)return l($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:jZ(J,"threadId");if(!Z)return B(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(J,{route:"attach",threadId:Z});let W=Q.emptyMiss===!0;if(!await this.threadInScope(J,Z))return bZ(Z,W);let K=await this.liveRuns.find({threadId:Z});if(K&&!this.liveRuns.mayAccess(K.runId,await this.runOwner(J)))return OJ();if(!K)return bZ(Z,W);let X=typeof Q.runId==="string"?Q.runId:void 0,G=X&&X!==K.runId?void 0:y9(J,Q);try{return pZ(this.liveRuns.replay(K.runId,G))}catch(V){if(V instanceof e)return B(410,{code:V.code,message:V.message,oldestSeq:V.oldest});if(V instanceof HJ)return B(404,{code:V.code,message:V.message});throw V}}async watch(J=new I){let $=await $J(J,FJ);if($.error)return l($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:jZ(J,"threadId");if(!Z)return B(400,{code:"invalid_request",message:"watch needs a threadId: it is the thread whose runs are announced."});if(await this.authorizeRequest(J,{route:"attach",threadId:Z}),!await this.threadInScope(J,Z))return B(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let W=await this.runOwner(J),K=this.liveRuns,X=B9(K),G=await K.find({threadId:Z}),V=null,Y=null,z=0,D=()=>{if(Y?.stop(),!V)return;let H=X.get(Z);if(H?.delete(V),H&&H.size===0)X.delete(Z);V=null},N=new ReadableStream({start(H){Y=cZ(H);let C=(P)=>{if(!K.mayAccess(P,W))return;try{H.enqueue(new TextEncoder().encode(uZ({seq:++z,event:{type:"run-start",runId:P,threadId:Z}}))),Y?.touch()}catch{D()}};V=C;let O=X.get(Z);if(!O)O=new Set,X.set(Z,O);if(O.add(C),G&&K.isRunning(G.runId))C(G.runId)},cancel(){D()}});return J.rawRequest?.signal?.addEventListener("abort",D,{once:!0}),new Response(N,{status:200,headers:mZ()})}async stop(J=new I){let $=await $J(J,FJ);if($.error)return l($);let Q=$.body;await this.authorizeRequest(J,{route:"stop",threadId:typeof Q.threadId==="string"?Q.threadId:void 0});let Z=await this.runOwner(J),W=typeof Q.runId==="string"?Q.runId:void 0;if(!W&&typeof Q.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId(Q.clientRunId)??void 0,!W){let X=bJ.get(Q.clientRunId);if(X){if(X.owner!==null&&X.owner!==Z)return OJ();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 OJ();return K.stop({reason:typeof Q.reason==="string"?Q.reason:void 0}),{stopped:!0}}attachmentScope(J,$,Q){let Z=this.hooks?.attachmentScope;if(Z)return Z(J,$,Q);let W=J.ctx()?.user,K=W?.id??W?.publicId;if(K!==void 0&&K!==null&&String(K)!=="")return{key:`user:${String(K)}`};if($)return{key:`thread:${$}`};return null}attachmentRetention(J,$){return this.hooks?.attachmentRetention?.(J,$)??null}definesRetention(){return this.attachmentRetention!==gJ.prototype.attachmentRetention||Boolean(this.hooks?.attachmentRetention)}async sweepAttachments(J={}){let $=J.now??new Date,Q=J.limit??500;if(!this.attachments.expired||!this.attachments.delete)throw Error("sweepAttachments() needs an attachment store with expired() and delete(). Implement both on the controller's `attachments` store.");let Z={deleted:0,failed:0},W=this.deletionTargets();for(let K of await this.attachments.expired($,Q))try{await w$(K,W),Z.deleted++}catch(X){Z.failed++,this.reportHookFailure(X)}for(let K of await this.fileOwners.expired?.($,Q)??[])try{await this.deleteProviderFile(K),Z.deleted++}catch(X){Z.failed++,this.reportHookFailure(X)}return Z}deletionTargets(){return{store:this.attachments,storage:this.attachmentStorage,provider:this.agent.provider,fileOwners:this.fileOwners}}async deleteProviderFile(J){let $=this.agent.provider;if(!$.deleteFile)throw Error(`Cannot delete provider file ${J}: the agent's provider has no deleteFile().`);await $.deleteFile(J),await this.fileOwners.delete?.(J)}async expireTurn(J){let $=this.deletionTargets(),Q=new Set,Z=new Set,W=async(K)=>{if(Q.has(K.id))return;if(Q.add(K.id),K.fileId)Z.add(K.fileId);try{await w$(K,$)}catch(X){this.reportHookFailure(X)}};for(let K of J.made)if(K.deleteAfterTurn)await W(K);for(let K of J.files){if(K.attachmentId&&J.scoped){let X=await J.scoped.get(K.attachmentId).catch(()=>null);if(X?.deleteAfterTurn)await W(X)}if(K.fileId&&!Z.has(K.fileId)){Z.add(K.fileId);let X=await this.fileOwners.get(K.fileId);if(X?.deleteAfterTurn&&X.owner===J.owner)try{await this.deleteProviderFile(K.fileId)}catch(G){this.reportHookFailure(G)}}}}attachmentLimits(J){let $=this.hooks?.attachmentLimits;if($)return $(J);return null}checkUpload(J,$,Q){return this.hooks?.checkUpload?.(J,$,Q)}attachmentDestination(J,$,Q){let Z=this.hooks?.attachmentDestination;if(Z)return Z(J,$,Q);return"both"}async attachmentsFor(J,$,Q={body:{}}){let Z=await this.attachmentScope(J,$,Q);if(!Z)return null;return new mJ(this.attachments,this.attachmentStorage,Z)}async voiceStart(J=new I){let $=this.voice;if(!$)return I$();let Q=await $J(J,FJ);if(Q.error)return l(Q);let{sdp:Z,threadId:W,pushToTalk:K}=Q.body;if(typeof Z!=="string"||!Z.trimStart().startsWith("v="))return B(400,{code:"invalid_request",message:"`sdp` must be the browser's SDP offer."});let X=hJ(Q.body,g9),G=typeof W==="string"&&W!==""?W:void 0;await this.authorizeRequest(J,{route:"stream",threadId:G,body:X});let V=J.ctx?.()?.user??null,Y=await $.start({req:J,body:X,threadId:G,user:V,pushToTalk:K===!0}),z=Date.now(),D,N=async(U)=>{if(U!==void 0)console.error("[gemi/ai] a voice session could not start.",U);if(D)await $.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:z,endedAt:Date.now(),durationMs:0,seconds:0,usage:A(),transcription:{usage:A(),seconds:0},transcript:[],requests:[],toolCalls:[],errors:[]})}catch(L){console.error("[gemi/ai] a voice session's onEnd threw.",L)}},H=Y.threadId??G;if(!H)return await N(void 0),B(400,{code:"invalid_request",message:"A voice session needs a thread: send `threadId`, or answer one from `voice.start`."});try{if(H!==G)await this.authorizeRequest(J,{route:"stream",threadId:H,body:X})}catch(U){throw await N(void 0),U}let C=crypto.randomUUID(),O=Y.tools??[];try{if(Y.mcp)O=[...O,...await N$(Y.mcp,{user:V,sessionId:C})]}catch(U){return await N(U),B(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}let P={...Y.session,tools:[...VJ($.delegate),...Y.session?.tools??[],...O.map((U)=>U.tool)],...K===!0?{turnDetection:null}:{}},F;try{F=await $.realtime.createCall({sdp:Z,session:P,safetyIdentifier:Y.safetyIdentifier})}catch(U){await N(U);let L=U instanceof m$&&U.code==="rate_limited";return B(L?429:502,{code:"voice_unavailable",message:"Voice isn't available right now."})}D=F.callId;try{await this.voiceStore.create({id:C,callId:F.callId,threadId:H,owner:await this.runOwner(J),body:X,startedAt:z});let{threadId:U,session:L,safetyIdentifier:R,mcp:E,tools:j,...x}=Y;return{sessionId:p.start({...x,tools:O,controller:this.constructor,threadId:H,user:V,body:X,call:{realtime:$.realtime,callId:F.callId},sessionId:C,store:this.voiceStore,liveRuns:this.liveRuns,delegate:$.delegate,session:P}).sessionId,sdp:F.sdpAnswer,threadId:H,delegate:$.delegate?.name??zJ,endsAt:z+(Y.limits?.maxDurationMs??900000)}}catch(U){return await N(U),B(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}}async voiceUpdate(J=new I){if(!this.voice)return I$();let $=await this.voiceSession(J);if($ instanceof Response)return $;let Q=await $J(J,FJ);if(Q.error)return l(Q);let Z=hJ(Q.body,[]);if(await this.authorizeRequest(J,{route:"stream",threadId:$.threadId,body:Z}),$.endedAt!==void 0)return B(409,{code:"voice_ended",message:"This voice session has ended."});return await this.voiceStore.update($.id,{body:Z}),p.get($.id)?.setBody(Z),{updated:!0}}async voiceEnd(J=new I){let $=this.voice;if(!$)return I$();let Q=await this.voiceSession(J);if(Q instanceof Response)return Q;if(await this.authorizeRequest(J,{route:"stream",threadId:Q.threadId,body:Q.body}),Q.endedAt!==void 0)return{ended:!1};let Z=p.get(Q.id);if(Z)await Z.end("hangup");else await $.realtime.hangup(Q.callId),await this.voiceStore.update(Q.id,{endedAt:Date.now(),endReason:"hangup"});return{ended:!0}}async voiceSession(J){let $=J.params?.sessionId,Q=typeof $==="string"&&$?await this.voiceStore.get($):null;if(!Q)return B(404,{code:"voice_not_found",message:"No such voice session."});if(Q.owner!==null&&Q.owner!==await this.runOwner(J))return OJ();return Q}async upload(J=new I){let $=await J.rawRequest.formData(),Q=$.get("file");if(!(Q instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let Z=Q instanceof File&&Q.name?Q.name:"upload",W=Q.type||"application/octet-stream",K=E9($.get("body")),X=$.get("threadId");await this.authorizeRequest(J,{route:"upload",threadId:typeof X==="string"&&X.length>0?X:void 0,body:K});let G=T9(await this.attachmentLimits(J),Q,Z,W);if(G)throw new q$(G.code,G.message);await this.scopeStore(J,K);let V=typeof X==="string"&&X.length>0&&await this.store.loadThread(X)!==null?X:void 0,Y=await this.runOwner(J),z=null,D=(j)=>this.fileOwners.record(j,{owner:Y,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString(),...z}),N={body:K,threadId:V},H=await this.checkUpload({name:Z,size:Q.size,mimeType:W},J,N);if(H)throw new q$(H.code||"upload_refused",H.message);let C=await this.attachmentDestination(Q,J,N),O=u9(C,$.get("destination")),P=await this.attachmentScope(J,V,{body:K});z=vJ(await this.attachmentRetention(J,{route:"upload",threadId:V,body:K}),this.turnAttachmentMaxAgeMs);let F=O!=="provider"&&!P;if(F){if(O==="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()`.');c9()}if(O==="provider"||!P){let j=await RZ(this.agent.provider,Q);await D(j);let x={fileId:j,name:Z,mimeType:W,size:Q.size,destination:"provider"};if(F)x.downgraded="no_scope";return x}let U=sZ(),L=await this.attachmentStorage.put({name:aZ(U,Z),body:Q,contentType:W}),R=O==="both"?await RZ(this.agent.provider,Q):void 0;if(R)await D(R);let E={id:U,scopeKey:P.key,fileId:R,objectName:L,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString(),destination:O,...z};return await this.attachments.put(P,E),{fileId:R,attachmentId:U,name:Z,mimeType:W,size:Q.size,destination:O}}async foreignFile(J,$){let Q=new Set(J.map((Z)=>Z.fileId).filter((Z)=>typeof Z==="string"));for(let Z of Q){let W=await this.fileOwners.get(Z);if(W?W.owner!==null&&W.owner!==$:this.requireKnownFiles)return v9()}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 u$(J,$)}onError(J,$){return this.hooks?.onError?.(J,$)}onProviderRetry(J,$){return this.hooks?.onProviderRetry?.(J,$)}onStreamComplete(J,$){return this.hooks?.onStreamComplete?.(J,$)}reportHookFailure(J){let $=this.hooks?.reportHookFailure;if($)try{return $(J)}catch(Q){console.error("[gemi/ai] reportHookFailure hook failed",Q)}console.error("[gemi/ai] agent controller hook failed",J)}async dispatchEvent(J,$){switch(J.type){case"tool-call":if(!J.part.partial&&!J.resent)await this.onToolCall({toolCallId:J.part.toolCallId,name:String(J.part.name),input:J.part.input},$);return;case"tool-result":{let Q=J.part;await this.onToolResult(Q,$,{toolCallId:Q.toolCallId,name:String(Q.name),input:$8(Q)});return}case"awaiting-input":await this.onAwaitingInput(J.pending,$);return;case"error":await this.onError(dZ(J.error),$);return;default:return}}async readThread(J,$={}){let Z=await($.scope===null||$.scope===void 0?this.store:yZ(this.store,$.scope)).loadThread(J);if(!Z)return null;let{messages:W}=await this.settleThread(J,Z,{write:!1});return W}isRunLive(J,$){return this.liveRuns.get(J)!==null}async settleThread(J,$,{write:Q}){let Z=(V)=>this.isRunLive(V,J),W=await FZ($,Z),K=W.messages,X=[],G=new Map(W.settled.map((V)=>[V.id,V]));if(i9(K)||Q)try{let V=await LZ(K,{threadId:J,store:g.store,isRunLive:Z,outputSchemaFor:(Y)=>this.toolNamed(Y)?.outputSchema,modelOutputFor:(Y,z)=>J8(this.toolNamed(Y),z,(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 _Z(g.store,V.orphans,(z)=>this.reportHookFailure(z));let Y=new Set(V.orphans.map((z)=>z.id));X=X.map((z)=>Y.has(z.id)?{...z,orphaned:!0}:z)}}catch(V){this.reportHookFailure(V)}if(Q&&G.size>0)try{await this.store.appendMessages(J,[...G.values()])}catch(V){this.reportHookFailure(V)}return{messages:K,jobs:X}}jobsBlockMax(){let J=this.agent.jobs?.contextBlock;if(J===!1)return 0;return J?.max??SJ}jobsBlock(J){return $Q(J,this.jobsBlockMax())}toolNamed(J){let $=(Q)=>{for(let Z of Q){let W=Z;if(Array.isArray(W.tools)){let K=$(W.tools);if(K)return K}else if(W.name===J)return W}return};return $(this.agent.tools??[])}follow(J,$){(async()=>{try{for await(let Q of J.frames())$.frame(Q)}catch(Q){this.reportHookFailure(Q)}})()}persistRun(J,$,Q,Z=null,W={id:null,notified:Promise.resolve()},K=null){let X=(z)=>K?z.then(()=>this.safely(K)):z,G=Promise.resolve(),V=(async()=>{let z;try{z=await J.result()}catch(N){Z?.close(),await Z?.settled(),G=X(W.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:N instanceof Error?N.message:String(N),retryable:!1},$))));return}let D=z.messages;if(Z?.close(D),await Z?.settled(),$.threadId&&D.length>0)try{await this.store.appendMessages($.threadId,D)}catch(N){this.reportHookFailure(N)}G=X(this.notifyRun(z,D,$,W))})(),Y=V.then(()=>p9(Promise.all([G,Q]).then(()=>{}),this.hookHoldMs));return{stored:V,hooks:Y}}async notifyRun(J,$,Q,Z){await Z.notified;for(let W of $){if(W.id===Z.id)continue;await this.safely(()=>this.onMessage(W,Q))}await this.safely(()=>this.onStreamComplete(J,Q))}async safely(J){try{await J()}catch($){this.reportHookFailure($)}}}var y$=["turn","clientRunId","threadId","messages","regenerate"],R9=["text","files","toolResults"];function hJ(J,$=K8(J)?y$:[...y$,...R9]){let Q={};for(let[Z,W]of Object.entries(J)){if($.includes(Z))continue;Object.defineProperty(Q,Z,{value:W,writable:!0,enumerable:!0,configurable:!0})}return Q}function E9(J){if(J===null)return{};let $;if(typeof J==="string")try{$=JSON.parse(J)}catch{throw new b$("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new b$("The upload's `body` field must be a JSON object.");return hJ($,y$)}class b$ extends uJ{constructor(J){super(J);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:J}}},view:{}}}}async function RZ(J,$){try{return await J.upload($)}catch(Q){if(Q instanceof rZ&&k9.has(Q.status))throw new W8(a(Q).message);throw Q}}var k9=new Set([400,413,415,422]);class q$ extends uJ{constructor(J,$){super($);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:J,message:$}}},view:{}}}}function T9(J,$,Q,Z){if(!J)return null;let{maxBytes:W,accept:K}=J;if(typeof W==="number"&&$.size>W)return{code:"file_too_large",message:`${JSON.stringify(Q)} is ${EZ($.size)}; the limit is ${EZ(W)}.`};if(K&&K.length>0&&!K.some((X)=>j9(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 j9(J,$,Q){let Z=J.trim().toLowerCase();if(!Z)return!1;if(Z.startsWith("."))return $.toLowerCase().endsWith(Z);let W=Q.toLowerCase().split(";")[0].trim();if(Z.endsWith("/*"))return W.startsWith(Z.slice(0,-1));return W===Z}function EZ(J){if(J<1024)return`${J} B`;let $=["KB","MB","GB"],Q=J/1024,Z=0;while(Q>=1024&&Z<$.length-1)Q/=1024,Z++;return`${Math.round(Q*10)/10} ${$[Z]}`}class W8 extends uJ{constructor(J){super(J);this.name="RejectedUploadError";let $=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test(J)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:$,message:J}}},view:{}}}}async function $J(J,$){let Q=J?.rawRequest;if(!Q||Q.method==="GET"||Q.method==="HEAD"||!Q.body)return{body:{}};if(!x9(Q.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let Z=Number(Q.headers.get("Content-Length"));if(Number.isFinite(Z)&&Z>$)return kZ($);let W;try{let X=await I9(Q,$);if(X===null)return kZ($);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 x9(J){return hZ(J)==="application/json"}async function I9(J,$){if(!Number.isFinite($)||!J.body)return await J.text();let Q=J.body.getReader(),Z=[],W=0;for(;;){let{done:G,value:V}=await Q.read();if(G)break;if(W+=V.byteLength,W>$)return await Q.cancel().catch(QJ),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 kZ(J){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${J} bytes).`}}function v$(J,$,Q){return B(J,{...cJ(vZ(J),Q,J),code:$})}function l(J){if(J.status===413)return v$(413,J.code??"body_too_large",J.error??"");return B(J.status??400,{code:J.code??"invalid_request",message:J.error})}function K8(J){return Boolean(J.turn)&&typeof J.turn==="object"}function w9(J){let $=K8(J)?J.turn:J,Q={};if(typeof $.text==="string")Q.text=$.text;if(Array.isArray($.files)){let Z=f9($.files);if(typeof Z==="string")return{error:Z};Q.files=Z}if(Array.isArray($.toolResults))Q.toolResults=$.toolResults;if(Object.keys(Q).length===0)return{};if($===J.turn&&$.localId!==void 0&&$.localId!==null&&$.localId!==""){let{localId:Z}=$;if(typeof Z!=="string")return{error:"turn.localId must be a string."};if(Z.length>TZ)return{error:`turn.localId is longer than ${TZ} characters.`};Q.localId=Z}return{turn:Q}}var TZ=200;function f9(J){let $=[];for(let[Q,Z]of J.entries()){let W=`turn.files[${Q}]`;if(!Z||typeof Z!=="object"||Array.isArray(Z))return`${W} must be an object.`;let K={};for(let z of["fileId","attachmentId","name","mimeType"]){let D=Z[z];if(D===void 0||D===null||D==="")continue;if(typeof D!=="string")return`${W}.${z} must be a string.`;K[z]=D}let{fileId:X,attachmentId:G,name:V,mimeType:Y}=K;if(X?.startsWith(qJ))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(qJ))return`${W}.attachmentId is not a gemi attachment id: it must start with "${qJ}".`;if(!X&&!G)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...X?{fileId:X}:{},...G?{attachmentId:G}:{},...V!==void 0?{name:V}:{},...Y!==void 0?{mimeType:Y}:{}})}return $}function y9(J,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let Z=Math.floor($.cursor);if(Z>=0)return Z+1;return}let Q=J?.rawRequest?.headers?.get("Last-Event-ID");if(Q){let Z=Number.parseInt(Q,10);if(Number.isFinite(Z))return Math.max(0,Z+1)}return}function jZ(J,$){let Q=J?.search?.get($);return typeof Q==="string"?Q:void 0}function b9(J){let $=c$(J);for(let Q=J.length-1;Q>=0;Q--){let Z=J[Q];if(Z.role!=="user"||$.has(Z.id))continue;let W="",K=[];for(let X of Z.content){if(X.type==="text")W+=X.text;if(X.type==="file")K.push({...X.fileId?{fileId:X.fileId}:{},...X.attachmentId?{attachmentId:X.attachmentId}:{},...X.name?{name:X.name}:{},...X.mimeType?{mimeType:X.mimeType}:{}})}if(!W&&K.length===0)continue;return{index:Q,turn:{...W?{text:W}:{},...K.length>0?{files:K}:{}}}}return null}function xZ(){return B(409,{code:"stopped",message:"The turn was stopped before it started."})}function q9(J){let $=J.event;if(J.text!==void 0||J.turn!==void 0)throw TypeError("AgentController.startTurn takes an `event` or a `text`/`turn`, not both: an event is not a person's message.");if(typeof $!=="object"||$===null||typeof $.name!=="string"||!F9.test($.name))throw TypeError('AgentController.startTurn\'s `event.name` must be letters, digits and `.`, `_`, `:`, `-` (at most 64), like "job-settled".');if($.text!==void 0&&typeof $.text!=="string")throw TypeError("AgentController.startTurn's `event.text` must be a string.");let Q;if($.data!==void 0)try{Q=JSON.parse(JSON.stringify($.data))}catch(Z){throw TypeError(`AgentController.startTurn's \`event.data\` is not JSON: ${String(Z)}`)}return{name:$.name,...$.text?{text:$.text}:{},...Q!==void 0?{data:Q}:{}}}function IZ(J){return B(409,{code:Q8,message:`Thread ${J} has a run going, and this turn was not to interrupt it.`})}function OJ(){return B(403,cJ("permission","This run belongs to someone else.",403))}function v9(){return B(403,cJ("permission","A file in this turn was uploaded by someone else.",403))}function h9(J){if(!Array.isArray(J))return[];let $=[];for(let Q of J){let Z=Q?.content;if(!Array.isArray(Z))continue;for(let W of Z)if(W&&typeof W==="object"&&typeof W.fileId==="string")$.push({fileId:W.fileId})}return $}var g9=["sdp","threadId","pushToTalk"];function I$(){return B(404,{code:"voice_not_enabled",message:"This agent has no voice: set `voice` on its controller."})}function B(J,$){return new Response(JSON.stringify({error:$}),{status:J,headers:{"Content-Type":"application/json"}})}function u9(J,$){if(typeof $!=="string"||$.length===0)return J;if($!=="both"&&$!=="provider"&&$!=="storage")throw Error(`Unknown attachment destination "${$}". Expected "both", "provider" or "storage".`);if($===J||J==="both"&&$==="storage")return $;if(J==="both"&&$==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${$}" destination, but the server's policy for it is "${J}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var wZ=!1;function c9(){if(wZ)return;wZ=!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 m9=2147483647;function p9(J,$){let Q=J.then(()=>{},()=>{});if(!($<=m9))return Q;let Z,W=new Promise((K)=>{Z=setTimeout(K,$)});return Promise.race([Q,W]).finally(()=>clearTimeout(Z))}var fZ=!1;function l9(J){if(fZ||Bun.env.NODE_ENV!=="production")return;if(!(J instanceof h$))return;fZ=!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 i9(J){return J.some(($)=>$.content.some((Q)=>Q.type==="tool-result"&&Q.status==="running"))}function yZ(J,$){if(typeof $!=="string"||$==="")throw TypeError("A store scope is a non-empty string.");if(!J.forScope)throw Error("This controller's store cannot be scoped: storeScope() or a turn's `scope` needs a store that implements `forScope` (DatabaseAgentStore or MemoryAgentStore).");return J.forScope($)}function bZ(J,$=!1){if($)return new Response(null,{status:204});return B(404,{code:"no_live_run",message:`No run in progress for thread ${J} in this process.`})}export{$6 as windowMessages,VJ as voiceTools,a9 as turnStarts,S6 as toRealtimeUsage,w8 as toAgentTools,o9 as supportsStrict,t9 as splitTurns,Y6 as settleSummaries,n9 as s,u$ as redactError,L6 as parsePartialJson,r9 as messageSize,GJ as measureUsage,N$ as mcpVoiceTools,L$ as liveRuns,DJ as keepSummary,A6 as isCallNotFound,c$ as injectedMessageIds,Z$ as generate,p8 as evalChain,A9 as defineAgentHooks,O$ as defaultVoiceStore,z6 as defaultUsageLimitStore,G6 as defaultSummaryStore,C6 as defaultPromptCacheKey,g$ as defaultNonceStore,_$ as defaultFileOwners,pJ as defaultAttachmentStore,E$ as defaultAgentStore,wJ as VoiceHangup,p as VoiceBridge,s9 as Usage,K$ as ToolNamespace,m as ToolError,O6 as ToolArgumentsTooLongError,H6 as Skill,mJ as ScopedAttachments,P6 as SKILLS_NAMESPACE,A$ as RedisReceiptStore,lZ as RedisNonceStore,_6 as RealtimeSideband,m$ as RealtimeRequestError,M6 as RealtimeClient,r$ as Prompt,iZ as PrismaNonceStore,D6 as PendingEscalation,R6 as OpenAIProvider,V$ as OpenAIImageProvider,F$ as MemoryVoiceSessionStore,V6 as MemoryUsageLimitStore,X6 as MemorySummaryStore,M$ as MemoryReceiptStore,h$ as MemoryNonceStore,fJ as MemoryLiveRuns,yJ as MemoryFileOwners,xJ as MemoryCircuitStore,tZ as MemoryAttachmentStore,PJ as MemoryAgentStore,KQ as MemoryAgentJobStore,SQ as MEMORY_NAMESPACE,HJ as LiveRunNotFoundError,GQ as JobsRequireThreadError,XQ as JobHandle,d9 as JSONSchemaError,oZ as InvalidAttachmentScopeError,OQ as InMemoryAgentMemoryStore,TJ as ImageRequestError,jJ as ImageProvider,X$ as ImageModel,e as FrameCursorEvictedError,YJ as FallbackProvider,_Q as FakeAgentMemoryStore,EJ as Eval,U$ as DatabaseAgentStore,tJ as DatabaseAgentMemoryStore,sJ as DatabaseAgentJobStore,B6 as DEFAULT_TRANSCRIPTION_MODEL,FQ as DEFAULT_MEMORY_MAX_TOKENS,BQ as DEFAULT_MEMORY_LIMITS,Q6 as DEFAULT_MAX_SUMMARY_TOKENS,N6 as DEFAULT_MAX_RUN_DURATION_MS,YQ as DEFAULT_JOB_DEADLINE_MS,SJ as DEFAULT_JOBS_CONTEXT_MAX,zJ as DEFAULT_DELEGATE_NAME,e9 as DEFAULT_CONTEXT_WINDOW_STEP,J6 as DEFAULT_CONTEXT_WINDOW_NOTE,Z6 as DEFAULT_COMPACT_TRIGGER_TOKENS,W6 as DEFAULT_COMPACT_INSTRUCTIONS,K6 as COMPACT_SUMMARY_HEADER,T6 as AzureOpenAIProvider,z$ as AzureOpenAIImageProvider,k6 as AzureAnthropicProvider,nZ as AttachmentNotFoundError,E6 as AnthropicProvider,lJ as AgentTurnError,kJ as AgentTool,F6 as AgentRunError,P$ as AgentProvider,UQ as AgentMemoryRefusedError,CQ as AgentMemoryConflictError,LQ as AgentMemories,g as AgentJobs,oJ as AgentJobDeadlineSweep,VQ as AgentJob,gJ as AgentController,U6 as Agent};
|
|
330
|
+
`);while($!==-1){let Q=this.buffer.slice(0,$);this.buffer=this.buffer.slice($+2);let Z=this.parse(Q);if(Z)J.push(Z);$=this.buffer.indexOf(`
|
|
327
331
|
|
|
328
|
-
|
|
332
|
+
`)}return J}parse(J){let $,Q=[];for(let K of J.split(`
|
|
333
|
+
`)){if(K===""||K.startsWith(":"))continue;let G=K.indexOf(":"),z=G===-1?K:K.slice(0,G),V=G===-1?"":K.slice(G+1);if(V.startsWith(" "))V=V.slice(1);if(z==="data")Q.push(V);else if(z==="id")$=V}if(Q.length===0)return null;let Z;try{Z=JSON.parse(Q.join(`
|
|
334
|
+
`))}catch{return null}let W=$===void 0||$===""?Number.NaN:Number($),X=Number.isFinite(W)?W:this.lastSeq+1;return this.lastSeq=X,{seq:X,event:Z}}}async function*_Z(J){if(!J)return;let $=J.getReader(),Q=new OZ;try{while(!0){let{done:Z,value:W}=await $.read();if(Z){yield*Q.flush();return}if(W)yield*Q.push(W)}}finally{try{await $.cancel()}catch{}}}function SZ(J={}){return{messages:J.messages?[...J.messages]:[],pending:J.pending?[...J.pending]:[],error:null,threadId:J.threadId,seq:J.seq??-1,cursorRunId:J.cursorRunId,runMessageIds:[],loadedTools:[]}}function AZ(J,$,Q=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==J.cursorRunId)&&$.seq<=J.seq)return J;return{...RZ(J,$.event,Q),seq:$.seq}}function RZ(J,$,Q){switch($.type){case"run-start":return{...J,messages:R9(J.messages,$.runId),runId:$.runId,cursorRunId:$.runId,threadId:$.threadId??J.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return c(J,$.messageId,Q,(Z)=>({...Z,role:$.role}));case"text-delta":if(BZ(J,$.messageId))return J;return c(J,$.messageId,Q,(Z)=>({...Z,content:x9(Z.content,$.delta)}));case"reasoning-delta":if(BZ(J,$.messageId))return J;return c(J,$.messageId,Q,(Z)=>({...Z,content:w9(Z.content,$.delta,$.id,$.providerMetadata)}));case"output-delta":return c(J,$.messageId,Q,(Z)=>({...Z,content:MZ(Z.content,{type:"output",value:$.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return c(J,$.messageId,Q,(Z)=>{let W=Z.content.findIndex((D)=>D.type==="tool-call"&&D.toolCallId===$.part.toolCallId),X=W===-1?void 0:Z.content[W],K=$.part.progress??X?.progress,G=$.part.nested??X?.nested,z=$.part.attachments??X?.attachments,V={...$.part,...K?{progress:K}:{},...G?{nested:G}:{},...z?{attachments:z}:{}},Y=Z.content.slice();if(W===-1)Y.push(V);else Y[W]=V;return{...Z,content:Y}});case"tool-call-discard":return c(J,$.messageId,Q,(Z)=>{let W=Z.content.filter((X)=>!(X.type==="tool-call"&&X.partial&&$.toolCallIds.includes(X.toolCallId)));return W.length===Z.content.length?Z:{...Z,content:W}});case"tool-search":{let Z=$.loaded.filter((W)=>!J.loadedTools.includes(W));if(Z.length===0)return J;return{...J,loadedTools:[...J.loadedTools,...Z]}}case"tool-progress":return LZ(J,$.toolCallId,(Z)=>({...Z,progress:[...Z.progress??[],$.data]}));case"nested-event":{let Z=$;return LZ(J,$.toolCallId,(W)=>{let X=W.nested??[],K=X.findIndex((Y)=>Y.runId===Z.runId),G=X[K]??{runId:Z.runId,agent:Z.agent,messages:[]},z=T9(G,Z,Q),V=K===-1?[...X,z]:X.map((Y,D)=>D===K?z:Y);return{...W,nested:V}})}case"tool-result":{let Z=c(J,$.messageId,Q,(W)=>({...W,content:MZ(W.content,$.part,(X)=>X.type==="tool-result"&&X.toolCallId===$.part.toolCallId)}));return{...Z,pending:Z.pending.filter((W)=>W.toolCallId!==$.part.toolCallId)}}case"message":{let Z=J.messages.findIndex((K)=>K.id===$.message.id),W=J.messages.slice();if(Z===-1)W.push($.message);else W[Z]=$.message;let X=J.runMessageIds.includes($.message.id)?J.runMessageIds:[...J.runMessageIds,$.message.id];return{...J,messages:W,runMessageIds:X}}case"message-id":{let Z=J.messages.findIndex((G)=>G.id===$.localId);if(Z===-1){if(!$.message||J.messages.some((G)=>G.id===$.messageId))return J;return{...J,messages:[...J.messages,$.message]}}let W=J.messages[Z],X={localId:W.localId??W.id,...W.metadata?{metadata:W.metadata}:{}},K=J.messages.some((G)=>G.id===$.messageId)?J.messages.filter((G,z)=>z!==Z).map((G)=>G.id===$.messageId?{...G,...X}:G):J.messages.map((G,z)=>z===Z?{...G,...X,id:$.messageId}:G);return{...J,messages:K}}case"awaiting-input":return{...J,runId:$.runId,pending:[...$.pending]};case"message-end":return c(J,$.messageId,Q,(Z)=>({...Z,finishReason:$.finishReason,...$.outputTruncated?{outputTruncated:!0}:{},...$.usage?{usage:$.usage}:{},content:$.outputTruncated||$.finishReason==="length"?Z.content.filter((W)=>!(W.type==="output"&&W.partial)):Z.content.map((W)=>W.type==="output"&&W.partial?{...W,partial:!1}:W)}));case"usage":return{...J,usage:$.usage};case"retry":return J;case"error":return{...J,error:$.error,pending:[]};case"run-end":return{...J,runId:void 0,finishReason:$.finishReason,messages:EZ(J,$.finishReason)};default:return J}}function R9(J,$){if(!J.some((Q)=>Q.runId===$&&Q.finishReason===void 0))return J;return J.map((Q)=>{if(Q.runId!==$||Q.finishReason!==void 0)return Q;let{runId:Z,...W}=Q;return{...W,content:[]}})}function EZ(J,$){return J.messages.map((Q)=>Q.role==="assistant"&&J.runMessageIds.includes(Q.id)?E9(Q,$):Q)}function E9(J,$){let Q=J.content.map((W)=>W.type==="tool-call"&&W.nested?.some((X)=>X.finishReason===void 0)?{...W,nested:W.nested.map((X)=>X.finishReason===void 0?k9(X,$):X)}:W);if(J.finishReason===void 0)return{...J,finishReason:$,content:Q};return Q.some((W,X)=>W!==J.content[X])?{...J,content:Q}:J}function k9(J,$){let Q={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((Z)=>Z.id),loadedTools:[]};return{...J,finishReason:$,messages:EZ(Q,$)}}function LZ(J,$,Q){for(let Z=J.messages.length-1;Z>=0;Z--){let W=J.messages[Z],X=W.content.findIndex((V)=>V.type==="tool-call"&&V.toolCallId===$);if(X===-1)continue;if(W.finishReason!==void 0&&!j9(J,W,$))return J;let K=W.content.slice();K[X]=Q(K[X]);let G=J.messages.slice();G[Z]={...W,content:K};let z=J.runMessageIds.includes(W.id)?J.runMessageIds:[...J.runMessageIds,W.id];return{...J,runMessageIds:z,messages:G}}return J}function T9(J,$,Q){let Z={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((X)=>X.id),loadedTools:[],finishReason:J.finishReason},W=RZ(Z,$.event,Q);return{...J,...$.label!==void 0?{label:$.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function j9(J,$,Q){if($.finishReason!=="awaiting-input")return!1;return!J.messages.some((Z)=>Z.content.some((W)=>W.type==="tool-result"&&W.toolCallId===Q))}function BZ(J,$){let Q=J.messages.find((Z)=>Z.id===$);return Q!==void 0&&Q.finishReason!==void 0}function c(J,$,Q,Z){let W=J.messages.findIndex((G)=>G.id===$),X=J.runMessageIds.includes($)?J.runMessageIds:[...J.runMessageIds,$];if(W===-1){let G={id:$,role:"assistant",content:[],createdAt:Q};return{...J,runMessageIds:X,messages:[...J.messages,Z(G)]}}let K=J.messages.slice();return K[W]=Z(K[W]),{...J,runMessageIds:X,messages:K}}function x9(J,$){let Q=J[J.length-1];if(Q&&Q.type==="text")return[...J.slice(0,-1),{type:"text",text:Q.text+$}];return[...J,{type:"text",text:$}]}function w9(J,$,Q,Z){let W=J[J.length-1];if(W&&W.type==="reasoning"&&W.id===Q&&!W.providerMetadata)return[...J.slice(0,-1),{...W,text:(W.text??"")+$,...Z?{providerMetadata:Z}:{}}];return[...J,{type:"reasoning",...Q?{id:Q}:{},text:$,...Z?{providerMetadata:Z}:{}}]}function MZ(J,$,Q){let Z=J.findIndex(Q);if(Z===-1)return[...J,$];let W=J.slice();return W[Z]=$,W}class q${store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(J,$,Q,Z){this.store=J;this.threadId=$;this.report=Z;this.state=SZ({messages:Q})}finish(J){if(this.closed)return;this.done.add(J.id),this.write(()=>[f$(J)])}frame(J){if(this.closed)return;let $=J.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=AZ(this.state,J),$.type){case"message":this.write(()=>[f$($.message)]);return;case"tool-call":if($.part.partial)return;this.checkpoint($.messageId);return;case"message-start":case"tool-result":this.checkpoint($.messageId);return;default:return}}close(J=[]){this.closed=!0;for(let $ of J)this.done.add($.id)}settled(){return this.chain}checkpoint(J){if(this.done.has(J))return;let $=this.state.messages.find((Z)=>Z.id===J);if(!$)return;let Q=this.runId;this.write(()=>{let Z=f$($);if(Z.finishReason===void 0&&Q)Z.runId=Q;return[Z]})}write(J){let $;try{$=J()}catch(Q){this.report(Q);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,$)).catch((Q)=>this.report(Q))}}function f$(J){return structuredClone(J)}async function kZ(J,$){let Q=[],Z=null,W=J.slice();for(let X=0;X<W.length;X++){let K=W[X];if(K.role!=="assistant"||K.finishReason!==void 0)continue;if(K.runId&&await $(K.runId))continue;Z??=new Set(J.flatMap((V)=>V.content.flatMap((Y)=>Y.type==="tool-result"?[Y.toolCallId]:[])));let G=K.content.map((V)=>V.type==="tool-call"?TZ(V):V);for(let V of K.content){if(V.type!=="tool-call"||Z.has(V.toolCallId))continue;let Y={type:"tool-result",toolCallId:V.toolCallId,name:V.name,status:"denied",cause:"interrupted"};G.push(Y)}let z={...K,content:G,finishReason:"interrupted"};W[X]=z,Q.push(z)}return{messages:W,settled:Q}}function TZ(J){let{partial:$,...Q}=J;if(!Q.nested?.some((Z)=>Z.finishReason===void 0))return Q;return{...Q,nested:Q.nested.map(I9)}}function I9(J){if(J.finishReason!==void 0)return J;return{...J,finishReason:"interrupted",messages:J.messages.map(($)=>$.role==="assistant"&&$.finishReason===void 0?{...$,finishReason:"interrupted",content:$.content.map((Q)=>Q.type==="tool-call"?TZ(Q):Q)}:$)}}var f9=50,q9=["waiting","running","ok","error"];async function wZ(J,$){let{store:Q,threadId:Z}=$,W=Math.max(f9,$.scan??0),X=await Q.listForThread(Z,{limit:W}),K,G=async(H)=>{if(H.state!=="running")return H;if(K??=await jZ(Q),H.deadlineAt>K)return H;return await xZ(Q,H),await Q.get(H.id)??H};for(let H=0;H<X.length;H++)X[H]=await G(X[H]);let z=new Map(X.map((H)=>[H.id,H])),V=J.slice(),Y=[],D=new Set;for(let H=0;H<V.length;H++){let O=V[H],C=null;for(let N=0;N<O.content.length;N++){let F=O.content[N];if(F.type==="tool-call")D.add(F.toolCallId);if(F.type!=="tool-result"||F.status!=="running")continue;let U=F.job?.id,_=U?z.get(U):void 0;if(U&&_===void 0){let E=await Q.get(U);if(_=E?await G(E):void 0,_)z.set(U,_)}if(_&&!h(_.state))continue;C??=O.content.slice(),C[N]=b9(F,_,$.outputSchemaFor,$.modelOutputFor)}if(C){let N={...O,content:C};V[H]=N,Y.push(N)}}let P=[];for(let H of X){if(H.orphaned||H.toolCallId===""||D.has(H.toolCallId))continue;if(await $.isRunLive(H.runId))continue;P.push(H)}return{messages:V,settled:Y,orphans:P,jobs:X}}async function IZ(J,$,Q){for(let Z of $)try{await J.transition(Z.id,q9,{orphaned:!0})}catch(W){Q(W)}}function b9(J,$,Q,Z){let W={type:"tool-result",toolCallId:J.toolCallId,name:J.name},X=(z,V)=>{let Y=Z?.(String(J.name),z);return{...W,status:"ok",job:V,output:z,...Y!==void 0?{modelOutput:Y}:{}}};if(!$)return{...W,status:"error",job:J.job,error:{code:"tool_error",message:`The background job for "${String(J.name)}" can no longer be found, so its result was lost. It may have run in part or in full: check its effects before repeating it.`,toolCallId:J.toolCallId,retryable:!0}};let K={id:$.id,...$.summary!==void 0?{summary:$.summary}:{},...$.usage?{usage:$.usage}:{}};if($.state==="error")return{...W,status:"error",job:K,error:$.error??{code:"tool_error",message:`The background job for "${String(J.name)}" failed.`,toolCallId:J.toolCallId,retryable:!0}};let G=Q?.(String(J.name));if(G){let z=G.safeParse($.output);if(z.ok===!1)return{...W,status:"error",job:K,error:{code:"invalid_tool_result",message:`The background job for "${String(J.name)}" finished with an output that does not match the tool's output schema: ${z.errors.join(", ")}`,toolCallId:J.toolCallId,retryable:!0}};return X(z.value,K)}return X($.output,K)}var v9=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;class KJ extends Error{status;code;kind;constructor(J,$){super(J);this.name="AgentTurnError",this.status=$.status,this.code=$.code,this.kind=$.kind}static async from(J){let $={};try{let Z=await J.json();if(Z?.error&&typeof Z.error==="object")$=Z.error}catch{}let Q=(Z)=>typeof $[Z]==="string"?$[Z]:void 0;return new KJ(Q("message")??`The agent turn was refused with status ${J.status}.`,{status:J.status,code:Q("code"),kind:Q("kind")})}}function y9(J){for(let $=J.length-1;$>=0;$--){let Q=J[$];if(Q.role!=="assistant")continue;return Q.content.map((Z)=>Z.type==="text"?Z.text:"").join("")}return""}function m$(J,$,Q,Z=!1){let W=[],X=(async()=>{for await(let G of $)if(G.type==="awaiting-input")W=G.pending})().catch(A),K;return{runId:$.runId,threadId:J,run:$,joined:Z,stop:(G)=>BJ($,G),result:()=>K??=(async()=>{let G=await $.result();await Promise.all([Q,X]);let z=G.messages;return{...G,threadId:J,text:y9(z),pending:G.finishReason==="awaiting-input"?W:[]}})()}}function h9(J,$){let Q=m$(J,$.run,o.get($.run)??$.run.result().then(A,A),!0),Z;return{...Q,stop:(W)=>{BJ($.run,W),$.answer.then((X)=>{if("run"in X)BJ(X.run,W)},A)},result:()=>Z??=(async()=>{let W=await $.answer;if(W.kind==="refused")throw await Q.result(),W.error;if(W.kind==="dropped"||W.run===$.run)return Q.result();return m$(J,W.run,W.hooks).result()})()}}var fZ=["supersede","queue","join","parallel","skip"];function g9(J,$){if($)return{event:{name:$.name,...$.text!==void 0?{text:$.text}:{},...$.data!==void 0?{data:$.data}:{}}};if(!J||J.toolResults&&J.toolResults.length>0)return null;if(!J.text&&!(J.files&&J.files.length>0))return null;return{...J.text?{text:J.text}:{},...J.files&&J.files.length>0?{files:J.files}:{},...J.localId?{localId:J.localId}:{}}}function qZ(J){if(!J)return{};let $="event"in J?J.event:void 0,Q=$?$.text:J.text;return{...Q?{text:Q}:{},...!$&&J.files&&J.files.length>0?{files:J.files}:{},...$?{event:{name:$.name}}:{}}}var c9=["supersede","queue","join","parallel"],u9=Q8,CJ=new Map,o=new WeakMap,v=new WeakMap,bZ=new WeakMap,vZ=new WeakMap;function m9(J){return J.headers.get("Content-Type")?.startsWith("text/event-stream")??!1}var b$=new WeakMap,v$=new WeakMap,yZ=new WeakMap,hZ=new WeakMap,y$={parallel:!1},p9=5000,gZ=new WeakMap,h$=new WeakMap,cZ=new WeakMap,p$=new WeakSet;function BJ(J,$){p$.add(J),J.stop($)}function uZ(J,$){let Q=gZ.get(J);if(Q)return Q;let Z=(async()=>{for await(let X of J.frames()){let K=X.event.type;if(K==="message-start"||K==="awaiting-input"||K==="run-end")return}})().catch(A),W={done:!1,promise:Promise.resolve()};return W.promise=Promise.race([Z,J.result().then(A,A)]).then(()=>$?.settled()).then(A,A).then(()=>{W.done=!0}),gZ.set(J,W),W}var OJ=new WeakMap,M8="thread_busy",mZ="http://gemi.internal/__gemi/agent-turn",uJ=new Map,l9=4194304,i9=1000,d9=5,n9=3,_J=65536,A=()=>{};class S8{byKey=new Map;take(J,$,Q){let Z=this.byKey.get(J);if(!Z?.has($)&&(Z?.size??0)>=Q)return null;if(!Z)Z=new Map,this.byKey.set(J,Z);Z.set($,(Z.get($)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let X=this.byKey.get(J),K=(X?.get($)??1)-1;if(!X)return;if(K>0)X.set($,K);else if(X.delete($),X.size===0)this.byKey.delete(J)}}}var pZ=new WeakMap,l$=new WeakMap;function o9(J){let $=l$.get(J);if(!$)$=new Map,l$.set(J,$);return $}function s9(J,$,Q){let Z=l$.get(J)?.get($);if(!Z)return;for(let W of[...Z])try{W(Q)}catch{}}function lZ(J){let $=pZ.get(J);if(!$)$=new S8,pZ.set(J,$);return $}function a9(J){return J}class iJ extends u9{static kind="agent-controller";hooks;store=I$;storeScope(J,$){return null}boundScope=void 0;async threadInScope(J,$){if(await this.scopeStore(J,{}),this.boundScope===null)return!0;return await this.store.loadThread($)!==null}async scopeStore(J,$){let Z=bZ.get(J)??await this.storeScope(J,{body:$})??null;if(this.boundScope!==void 0){if(this.boundScope!==Z)throw Error("This AgentController instance already served a request in another store scope. Build a controller per request (the router and startTurn do).");return}if(Z!==null)this.store=J8(this.store,Z);this.boundScope=Z}liveRuns=R$;voice;voiceStore=M$;attachments=sJ;attachmentStorage=X8;turnAttachmentMaxAgeMs=3600000;fileOwners=E$;nonces=s$;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=l9;maxHistoryMessages=i9;contextWindow=void 0;prepareStep(J,$){return this.hooks?.prepareStep?.(J,$)}maxConcurrentRuns=d9;maxThreadRuns(J,$){let Q=this.hooks?.maxThreadRuns;if(Q)return Q(J,$);return n9}busyPolicy(J,$){let Q=this.hooks?.busyPolicy;if(Q)return Q(J,$);return $.requested??"supersede"}runLimitKey(J,$){let Q=this.hooks?.runLimitKey;if(Q)return Q(J,$);return $.owner}authorizeRequest(J,$){let Q=this.hooks?.authorizeRequest;if(Q)return Q(J,$);return this.resource?.authorize(J,$)}resource;runOwner(J){let $=this.hooks?.runOwner;if($)return $(J);let Q=J.ctx?.()?.user,Z=Q?.id??Q?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}static async startTurn(J){let{threadId:$}=J;if(typeof $!=="string"||$==="")throw TypeError("AgentController.startTurn needs a `threadId`: a server turn is stored on a thread. Create one with the store's `createThread`.");let Q=J.ifBusy;if(Q!==void 0&&!fZ.includes(Q))throw TypeError(`AgentController.startTurn's \`ifBusy\` is "supersede", "queue", "join", "parallel" or "skip"; got ${JSON.stringify(J.ifBusy)}.`);let Z=J.event===void 0?void 0:V6(J),W={...J.turn,...J.text!==void 0?{text:J.text}:{}},X={...J.body,threadId:$,turn:W},K=new f(new Request(mZ,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X)}),{},"api",new URL(mZ).pathname),G=new this;if(v.set(K,null),J.scope!==void 0)bZ.set(K,J.scope);if(Q!==void 0)vZ.set(K,Q);if(Z)OJ.set(K,Z);let z=await l.run(K,()=>G.stream(K),{user:J.user??null}),V=h$.get(K),Y=v.get(K);if(!Y&&!V){let H=await KJ.from(z);if(Q==="skip"&&H.code===M8)return{skipped:!0,threadId:$};throw H}if(v.delete(K),h$.delete(K),z.body?.cancel().catch(A),V)return h9($,V);let{run:D,hooks:P}=Y;return m$($,D,P)}async stream(J=new f){let $=await XJ(J,this.maxBodyBytes);if($.error)return u($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:void 0,W=W6(Q);if(W.error)return u({body:{},error:W.error});let X=W.turn,K=Z!==void 0&&Q.regenerate===!0,G=typeof Q.clientRunId==="string"?Q.clientRunId:void 0,z=vZ.get(J);if(!v.has(J)&&Q.ifBusy!==void 0){if(!c9.includes(Q.ifBusy))return u({body:{},error:`\`ifBusy\` is "supersede", "queue", "join" or "parallel"; got ${JSON.stringify(Q.ifBusy)}.`});z=Q.ifBusy}let V=lJ(Q);if(this.requireThread&&!Z)return B(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(await this.scopeStore(J,V),K&&!this.store.removeMessages)return B(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 LJ(413,"history_too_long",`The conversation has ${Q.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let Y=await this.runOwner(J),D=G?{cancelled:!1,owner:Y}:null;if(D)uJ.set(G,D);let P=null,H=[],O=async(N=y$)=>{try{return await C(N)}finally{if(Z&&H.length>0&&P===null)await this.store.appendMessages(Z,H).catch((F)=>this.reportHookFailure(F));if(N.release&&P===null)N.release()}},C=async(N)=>{let F,U=null;if(Z){let S=await this.store.loadThread(Z);if(!S)return B(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let t=await this.settleThread(Z,S,{write:!0});if(F=t.messages.filter((q)=>!(q.role==="assistant"&&q.finishReason===void 0&&q.runId&&this.liveRuns.isRunning(q.runId))),U=this.jobsBlock(t.jobs),K){let q=G6(F);if(!q)return B(409,{code:"nothing_to_regenerate",message:`Thread ${Z} has no user turn to answer again.`});H=F.slice(q.index),await this.store.removeMessages(Z,H.map((x8)=>x8.id)),F=F.slice(0,q.index),X=X?.localId?{...q.turn,localId:X.localId}:q.turn}}else F=Array.isArray(Q.messages)?Q.messages:[],U6(this.nonces);let _=[await this.instructions(J,{body:V})||void 0,U??void 0].filter(Boolean).join(`
|
|
335
|
+
|
|
336
|
+
`)||void 0,E=await this.context(J,{body:V}),T=await this.reasoning(J,{body:V})||void 0,x=await this.skills(J,{body:V})||void 0,w=await this.runTools(J,{body:V,context:E})||void 0,s=await this.usageLimits(J,{body:V,context:E})||void 0,L=await this.attachmentsFor(J,Z,{body:V}),k=await this.attachmentRetention(J,{route:"stream",threadId:Z,body:V});pJ(k,this.turnAttachmentMaxAgeMs);let M=[],E8=L&&k?L.withLifetime({next:()=>pJ(k,this.turnAttachmentMaxAgeMs),onPut:(S)=>M.push(S)}):L,e$=this.agent.memory?await this.memoryScopes(J,{body:V}):void 0;if(D?.cancelled)return aZ();let y=Z?new q$(this.store,Z,F,(S)=>this.reportHookFailure(S)):null,JQ=`run_${crypto.randomUUID()}`,$Q=[],a={req:J,runId:JQ,threadId:Z,get denials(){return $Q}},MJ={id:null,notified:Promise.resolve()},I=this.agent.stream({runId:JQ,messages:F,turn:X,threadId:Z,...y?{onMessage:(S)=>y.finish(S)}:{},onTurn:(S)=>{if(MJ.id!==null)return;MJ.id=S.id;let t=y?y.settled():Promise.resolve();MJ.notified=t.then(()=>this.safely(()=>this.onMessage(S,a)))},instructions:_,...OJ.has(J)?{event:OJ.get(J)}:{},...v.has(J)?{echoTurn:!0}:{},...T?{reasoning:T}:{},...x&&x.length>0?{skills:x}:{},...w?.tools&&w.tools.length>0?{tools:w.tools}:{},...w?.activeTools?{activeTools:w.activeTools}:{},...s?{usageLimits:s}:{},context:E,attachments:E8,body:V,redactError:(S,t)=>this.redactError(S,t,a),onProviderRetry:(S)=>this.onProviderRetry(S,a),nonces:this.nonces,receipts:this.receipts,subject:Y,...e$?{memory:{scopes:e$,...this.memoryMaxTokens!==void 0?{maxTokens:this.memoryMaxTokens}:{}}}:{},...Z?{jobs:{owner:Y}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...Z&&O8(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==iJ.prototype.prepareStep||this.hooks?.prepareStep?{prepareStep:(S)=>this.prepareStep(S,a)}:{}});$Q=I.denials;let k8=this.liveRuns.register(I,{threadId:Z,owner:Y,clientRunId:G,onEvent:(S)=>this.dispatchEvent(S,a),onInternalError:(S)=>this.reportHookFailure(S),maxRunDurationMs:this.agent.maxRunDurationMs});P=I;let SJ=OJ.get(J);if(b$.set(I,{startedAt:new Date,owner:Y,turn:SJ?{...SJ.text?{text:SJ.text}:{},event:{name:SJ.name}}:qZ(X),joined:[]}),y)v$.set(I,y),this.follow(I,y);if(Z)s9(this.liveRuns,Z,I.runId);let QQ=X?.files??[],T8=this.definesRetention()&&(QQ.length>0||k==="turn")?()=>this.expireTurn({scoped:L,files:QQ,made:M,owner:Y}):null,{stored:j8,hooks:aJ}=this.persistRun(I,a,k8,y,MJ,T8);if(o.set(I,j8),hZ.set(J,{run:I,hooks:aJ}),v.has(J))v.set(J,{run:I,hooks:aJ});if(N.release)I.result().then(N.release,N.release);return J.ctx?.()?.waitUntil(aJ),I.toResponse()};try{await this.authorizeRequest(J,{route:"stream",threadId:Z,body:V});let N=await this.foreignFile([...X?.files??[],...Z?[]:Y6(Q.messages)],Y);if(N)return N;if(D?.cancelled)return aZ();let F=await this.runLimitKey(J,{owner:Y,threadId:Z}),U=F===null?A:lZ(this.liveRuns).take(F,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!U)return LJ(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);let _;try{return _=Z?await this.withThread(Z,Y,O,{req:J,requested:K?"supersede":z,decide:!K,source:v.has(J)?"server":"client",turn:X,body:V,limitKey:F}):await O(),_}finally{let E=P,T=_?yZ.get(_):void 0;if(E)E.result().then(U,U);else if(T)T.then(U,U);else U()}}finally{if(D&&uJ.get(G)===D)uJ.delete(G)}}async withThread(J,$,Q,Z){if(Z.requested==="skip"&&CJ.has(J))return tZ(J);for(;;){let W=await this.underThreadLock(J,$,Q,Z);if(!("waitFor"in W))return W.response;await W.waitFor}}async underThreadLock(J,$,Q,Z){let W=CJ.get(J)??Promise.resolve(),X,K=new Promise((z)=>{X=z}),G=W.then(()=>K);CJ.set(J,G),await W;try{let z=this.liveRuns.running({threadId:J}).map((D)=>({info:D,run:this.liveRuns.get(D.runId)})).filter((D)=>D.run!==null);if(z.length===0){let D=await this.liveRuns.find({threadId:J}),P=D?this.liveRuns.get(D.runId):null;if(P)await o.get(P);return{response:await Q(y$)}}let V=Z.intake?.policy??(Z.decide?await this.decideBusy(J,$,z,Z):Z.requested??"supersede"),Y=(D)=>(o.get(D)??D.result()).then(A,A);if(V==="skip")return{response:tZ(J)};if(V==="queue")return{waitFor:Promise.all(z.map(({run:D})=>Y(D)))};if(V==="join"){let D=z.filter(({info:C})=>this.liveRuns.mayAccess(C.runId,$));if(D.length===0)return{response:n()};let P=D[D.length-1],H=g9(Z.turn,OJ.get(Z.req)),O=H?P.run.join?.(H)??null:null;if(!O)return{waitFor:Y(P.run)};return b$.get(P.run)?.joined.push(qZ(H)),{response:this.joinResponse(J,$,P.run,O,H,Q,Z)}}if(V==="parallel"){let D=Z.intake??={policy:V,waited:new WeakSet},P=z.filter(({run:C})=>!uZ(C,v$.get(C)).done&&!D.waited.has(C));if(P.length>0){for(let{run:U}of P)D.waited.add(U);let C=Promise.all(P.map(({run:U})=>uZ(U,v$.get(U)).promise)),N,F=new Promise((U)=>{N=setTimeout(U,p9)});return{waitFor:Promise.race([C,F]).finally(()=>clearTimeout(N))}}let H=await this.maxThreadRuns(Z.req,{threadId:J,owner:$,body:Z.body});if(z.length>=H)return{response:LJ(429,"too_many_runs",`This conversation already has ${z.length} answers going. Wait for one to finish, or stop it, and send again.`)};let O=Z.limitKey===null?A:lZ(this.liveRuns).take(Z.limitKey,`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!O)return{response:LJ(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`)};return{response:await Q({parallel:!0,release:O})}}if(z.some(({info:D})=>!this.liveRuns.mayAccess(D.runId,$)))return{response:n()};for(let{run:D}of z)D.stop({reason:"superseded by a later turn on this thread"});return await Promise.all(z.map(({run:D})=>o.get(D))),{response:await Q(y$)}}finally{if(X(),CJ.get(J)===G)CJ.delete(J)}}async decideBusy(J,$,Q,Z){let W=await this.busyPolicy(Z.req,{threadId:J,owner:$,requested:Z.requested,source:Z.source,turn:Z.turn,body:Z.body,running:Q.map(({info:X,run:K})=>{let G=b$.get(K);return{runId:X.runId,startedAt:G?.startedAt??new Date(X.startedAt),owner:this.liveRuns.ownerOf(X.runId),turn:G?.turn??{},joined:[...G?.joined??[]]}})});if(!fZ.includes(W))throw TypeError(`AgentController.busyPolicy answers "supersede", "queue", "join", "parallel" or "skip"; got ${JSON.stringify(W)}.`);return W}joinResponse(J,$,Q,Z,W,X,K){let G=(H)=>({kind:"answered",run:H,hooks:o.get(H)??H.result().then(A,A)}),z=Z.taken.then(async(H)=>{if(H||p$.has(Q))return null;return this.withThread(J,$,X,K)}),V=z.then(async(H)=>{if(!H)return p$.has(Q)?{kind:"dropped"}:G(Q);let O=cZ.get(H);if(O)return O;let C=hZ.get(K.req);if(C&&m9(H))return{kind:"answered",...C};return{kind:"refused",error:await KJ.from(H),stored:await this.storeUnanswered(J,Q,W)}},async(H)=>{return this.reportHookFailure(H),{kind:"refused",error:new KJ("The turn started for a joined message failed.",{status:500}),stored:await this.storeUnanswered(J,Q,W)}});if(v.has(K.req))h$.set(K.req,{run:Q,answer:V});async function*Y(){let H=-1;for await(let N of Q.frames())H=N.seq,yield N;let O=await z.catch(()=>null),C=await V;if(C.kind==="refused"){if(O?.body?.cancel().catch(A),C.stored&&W.localId)yield{seq:++H,event:{type:"message-id",localId:W.localId,messageId:C.stored.id,message:C.stored}};let N=C.error.status===429;yield{seq:++H,event:{type:"error",error:{code:N?"rate_limited":"unknown",message:`Your message was not answered: ${C.error.message}`,retryable:N}}};return}if(!O?.body)return;try{for await(let N of _Z(O.body))yield N}finally{O.body.cancel().catch(A)}}let D=(async()=>{await Q.result().catch(A);let H=await V;if(H.kind==="answered")await H.run.result().catch(A)})(),P=c$(Y());return yZ.set(P,D),cZ.set(P,V),P}async storeUnanswered(J,$,Q){await o.get($);let Z=B8(Q.event?Q.event.text:Q.text,Q.files,Q.event);try{return await this.store.appendMessages(J,[Z]),Z}catch(W){return this.reportHookFailure(W),null}}async attach(J=new f){let $=await XJ(J,_J);if($.error)return u($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:sZ(J,"threadId");if(!Z)return B(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(J,{route:"attach",threadId:Z});let W=Q.emptyMiss===!0;if(!await this.threadInScope(J,Z))return $8(Z,W);let X=typeof Q.runId==="string"?Q.runId:void 0,K=X&&this.liveRuns.isRunning(X)&&this.liveRuns.threadOf(X)===Z?{runId:X}:await this.liveRuns.find({threadId:Z});if(K&&!this.liveRuns.mayAccess(K.runId,await this.runOwner(J)))return n();if(!K)return $8(Z,W);let G=typeof Q.runId==="string"?Q.runId:void 0,z=G&&G!==K.runId?void 0:K6(J,Q);try{return c$(this.liveRuns.replay(K.runId,z))}catch(V){if(V instanceof WJ)return B(410,{code:V.code,message:V.message,oldestSeq:V.oldest});if(V instanceof FJ)return B(404,{code:V.code,message:V.message});throw V}}async watch(J=new f){let $=await XJ(J,_J);if($.error)return u($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:sZ(J,"threadId");if(!Z)return B(400,{code:"invalid_request",message:"watch needs a threadId: it is the thread whose runs are announced."});if(await this.authorizeRequest(J,{route:"attach",threadId:Z}),!await this.threadInScope(J,Z))return B(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let W=await this.runOwner(J),X=this.liveRuns,K=o9(X),G=null,z=null,V=0,Y=()=>{if(z?.stop(),!G)return;let P=K.get(Z);if(P?.delete(G),P&&P.size===0)K.delete(Z);G=null},D=new ReadableStream({start(P){z=G8(P);let H=(C)=>{if(!X.mayAccess(C,W))return;try{P.enqueue(new TextEncoder().encode(K8({seq:++V,event:{type:"run-start",runId:C,threadId:Z}}))),z?.touch()}catch{Y()}};G=H;let O=K.get(Z);if(!O)O=new Set,K.set(Z,O);O.add(H);for(let{runId:C}of X.running({threadId:Z}))H(C)},cancel(){Y()}});return J.rawRequest?.signal?.addEventListener("abort",Y,{once:!0}),new Response(D,{status:200,headers:V8()})}async stop(J=new f){let $=await XJ(J,_J);if($.error)return u($);let Q=$.body;await this.authorizeRequest(J,{route:"stop",threadId:typeof Q.threadId==="string"?Q.threadId:void 0});let Z=await this.runOwner(J),W=typeof Q.runId==="string"?Q.runId:void 0;if(!W&&typeof Q.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId(Q.clientRunId)??void 0,!W){let K=uJ.get(Q.clientRunId);if(K){if(K.owner!==null&&K.owner!==Z)return n();return K.cancelled=!0,{stopped:!0}}}}if(!W&&typeof Q.threadId==="string"){let K=this.liveRuns.running({threadId:Q.threadId});if(K.length>1){let G=K.filter((V)=>this.liveRuns.mayAccess(V.runId,Z));if(G.length===0)return n();let z=typeof Q.reason==="string"?Q.reason:void 0;for(let V of G){let Y=this.liveRuns.get(V.runId);if(Y)BJ(Y,{reason:z})}return{stopped:!0}}W=(await this.liveRuns.find({threadId:Q.threadId}))?.runId}let X=W?this.liveRuns.get(W):null;if(!X)return{stopped:!1};if(!this.liveRuns.mayAccess(X.runId,Z))return n();return BJ(X,{reason:typeof Q.reason==="string"?Q.reason:void 0}),{stopped:!0}}attachmentScope(J,$,Q){let Z=this.hooks?.attachmentScope;if(Z)return Z(J,$,Q);let W=J.ctx()?.user,X=W?.id??W?.publicId;if(X!==void 0&&X!==null&&String(X)!=="")return{key:`user:${String(X)}`};if($)return{key:`thread:${$}`};return null}attachmentRetention(J,$){return this.hooks?.attachmentRetention?.(J,$)??null}definesRetention(){return this.attachmentRetention!==iJ.prototype.attachmentRetention||Boolean(this.hooks?.attachmentRetention)}async sweepAttachments(J={}){let $=J.now??new Date,Q=J.limit??500;if(!this.attachments.expired||!this.attachments.delete)throw Error("sweepAttachments() needs an attachment store with expired() and delete(). Implement both on the controller's `attachments` store.");let Z={deleted:0,failed:0},W=this.deletionTargets();for(let X of await this.attachments.expired($,Q))try{await u$(X,W),Z.deleted++}catch(K){Z.failed++,this.reportHookFailure(K)}for(let X of await this.fileOwners.expired?.($,Q)??[])try{await this.deleteProviderFile(X),Z.deleted++}catch(K){Z.failed++,this.reportHookFailure(K)}return Z}deletionTargets(){return{store:this.attachments,storage:this.attachmentStorage,provider:this.agent.provider,fileOwners:this.fileOwners}}async deleteProviderFile(J){let $=this.agent.provider;if(!$.deleteFile)throw Error(`Cannot delete provider file ${J}: the agent's provider has no deleteFile().`);await $.deleteFile(J),await this.fileOwners.delete?.(J)}async expireTurn(J){let $=this.deletionTargets(),Q=new Set,Z=new Set,W=async(X)=>{if(Q.has(X.id))return;if(Q.add(X.id),X.fileId)Z.add(X.fileId);try{await u$(X,$)}catch(K){this.reportHookFailure(K)}};for(let X of J.made)if(X.deleteAfterTurn)await W(X);for(let X of J.files){if(X.attachmentId&&J.scoped){let K=await J.scoped.get(X.attachmentId).catch(()=>null);if(K?.deleteAfterTurn)await W(K)}if(X.fileId&&!Z.has(X.fileId)){Z.add(X.fileId);let K=await this.fileOwners.get(X.fileId);if(K?.deleteAfterTurn&&K.owner===J.owner)try{await this.deleteProviderFile(X.fileId)}catch(G){this.reportHookFailure(G)}}}}attachmentLimits(J){let $=this.hooks?.attachmentLimits;if($)return $(J);return null}checkUpload(J,$,Q){return this.hooks?.checkUpload?.(J,$,Q)}attachmentDestination(J,$,Q){let Z=this.hooks?.attachmentDestination;if(Z)return Z(J,$,Q);return"both"}async attachmentsFor(J,$,Q={body:{}}){let Z=await this.attachmentScope(J,$,Q);if(!Z)return null;return new oJ(this.attachments,this.attachmentStorage,Z)}async voiceStart(J=new f){let $=this.voice;if(!$)return g$();let Q=await XJ(J,_J);if(Q.error)return u(Q);let{sdp:Z,threadId:W,pushToTalk:X}=Q.body;if(typeof Z!=="string"||!Z.trimStart().startsWith("v="))return B(400,{code:"invalid_request",message:"`sdp` must be the browser's SDP offer."});let K=lJ(Q.body,D6),G=typeof W==="string"&&W!==""?W:void 0;await this.authorizeRequest(J,{route:"stream",threadId:G,body:K});let z=J.ctx?.()?.user??null,V=await $.start({req:J,body:K,threadId:G,user:z,pushToTalk:X===!0}),Y=Date.now(),D,P=async(U)=>{if(U!==void 0)console.error("[gemi/ai] a voice session could not start.",U);if(D)await $.realtime.hangup(D).catch((_)=>{console.error("[gemi/ai] a voice call that failed to start could not be hung up.",_)});try{await V.onEnd?.({sessionId:"",...D?{callId:D}:{},threadId:V.threadId??G??"",reason:"start_failed",startedAt:Y,endedAt:Date.now(),durationMs:0,seconds:0,usage:R(),transcription:{usage:R(),seconds:0},transcript:[],requests:[],toolCalls:[],errors:[]})}catch(_){console.error("[gemi/ai] a voice session's onEnd threw.",_)}},H=V.threadId??G;if(!H)return await P(void 0),B(400,{code:"invalid_request",message:"A voice session needs a thread: send `threadId`, or answer one from `voice.start`."});try{if(H!==G)await this.authorizeRequest(J,{route:"stream",threadId:H,body:K})}catch(U){throw await P(void 0),U}let O=crypto.randomUUID(),C=V.tools??[];try{if(V.mcp)C=[...C,...await L$(V.mcp,{user:z,sessionId:O})]}catch(U){return await P(U),B(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}let N={...V.session,tools:[...HJ($.delegate),...V.session?.tools??[],...C.map((U)=>U.tool)],...X===!0?{turnDetection:null}:{}},F;try{F=await $.realtime.createCall({sdp:Z,session:N,safetyIdentifier:V.safetyIdentifier})}catch(U){await P(U);let _=U instanceof r$&&U.code==="rate_limited";return B(_?429:502,{code:"voice_unavailable",message:"Voice isn't available right now."})}D=F.callId;try{await this.voiceStore.create({id:O,callId:F.callId,threadId:H,owner:await this.runOwner(J),body:K,startedAt:Y});let{threadId:U,session:_,safetyIdentifier:E,mcp:T,tools:x,...w}=V;return{sessionId:d.start({...w,tools:C,controller:this.constructor,threadId:H,user:z,body:K,call:{realtime:$.realtime,callId:F.callId},sessionId:O,store:this.voiceStore,liveRuns:this.liveRuns,delegate:$.delegate,session:N}).sessionId,sdp:F.sdpAnswer,threadId:H,delegate:$.delegate?.name??PJ,endsAt:Y+(V.limits?.maxDurationMs??900000)}}catch(U){return await P(U),B(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}}async voiceUpdate(J=new f){if(!this.voice)return g$();let $=await this.voiceSession(J);if($ instanceof Response)return $;let Q=await XJ(J,_J);if(Q.error)return u(Q);let Z=lJ(Q.body,[]);if(await this.authorizeRequest(J,{route:"stream",threadId:$.threadId,body:Z}),$.endedAt!==void 0)return B(409,{code:"voice_ended",message:"This voice session has ended."});return await this.voiceStore.update($.id,{body:Z}),d.get($.id)?.setBody(Z),{updated:!0}}async voiceEnd(J=new f){let $=this.voice;if(!$)return g$();let Q=await this.voiceSession(J);if(Q instanceof Response)return Q;if(await this.authorizeRequest(J,{route:"stream",threadId:Q.threadId,body:Q.body}),Q.endedAt!==void 0)return{ended:!1};let Z=d.get(Q.id);if(Z)await Z.end("hangup");else await $.realtime.hangup(Q.callId),await this.voiceStore.update(Q.id,{endedAt:Date.now(),endReason:"hangup"});return{ended:!0}}async voiceSession(J){let $=J.params?.sessionId,Q=typeof $==="string"&&$?await this.voiceStore.get($):null;if(!Q)return B(404,{code:"voice_not_found",message:"No such voice session."});if(Q.owner!==null&&Q.owner!==await this.runOwner(J))return n();return Q}async upload(J=new f){let $=await J.rawRequest.formData(),Q=$.get("file");if(!(Q instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let Z=Q instanceof File&&Q.name?Q.name:"upload",W=Q.type||"application/octet-stream",X=r9($.get("body")),K=$.get("threadId");await this.authorizeRequest(J,{route:"upload",threadId:typeof K==="string"&&K.length>0?K:void 0,body:X});let G=J6(await this.attachmentLimits(J),Q,Z,W);if(G)throw new n$(G.code,G.message);await this.scopeStore(J,X);let z=typeof K==="string"&&K.length>0&&await this.store.loadThread(K)!==null?K:void 0,V=await this.runOwner(J),Y=null,D=(x)=>this.fileOwners.record(x,{owner:V,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString(),...Y}),P={body:X,threadId:z},H=await this.checkUpload({name:Z,size:Q.size,mimeType:W},J,P);if(H)throw new n$(H.code||"upload_refused",H.message);let O=await this.attachmentDestination(Q,J,P),C=H6(O,$.get("destination")),N=await this.attachmentScope(J,z,{body:X});Y=pJ(await this.attachmentRetention(J,{route:"upload",threadId:z,body:X}),this.turnAttachmentMaxAgeMs);let F=C!=="provider"&&!N;if(F){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()`.');P6()}if(C==="provider"||!N){let x=await iZ(this.agent.provider,Q);await D(x);let w={fileId:x,name:Z,mimeType:W,size:Q.size,destination:"provider"};if(F)w.downgraded="no_scope";return w}let U=N8(),_=await this.attachmentStorage.put({name:F8(U,Z),body:Q,contentType:W}),E=C==="both"?await iZ(this.agent.provider,Q):void 0;if(E)await D(E);let T={id:U,scopeKey:N.key,fileId:E,objectName:_,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString(),destination:C,...Y};return await this.attachments.put(N,T),{fileId:E,attachmentId:U,name:Z,mimeType:W,size:Q.size,destination:C}}async foreignFile(J,$){let Q=new Set(J.map((Z)=>Z.fileId).filter((Z)=>typeof Z==="string"));for(let Z of Q){let W=await this.fileOwners.get(Z);if(W?W.owner!==null&&W.owner!==$:this.requireKnownFiles)return z6()}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 a$(J,$)}onError(J,$){return this.hooks?.onError?.(J,$)}onProviderRetry(J,$){return this.hooks?.onProviderRetry?.(J,$)}onStreamComplete(J,$){return this.hooks?.onStreamComplete?.(J,$)}reportHookFailure(J){let $=this.hooks?.reportHookFailure;if($)try{return $(J)}catch(Q){console.error("[gemi/ai] reportHookFailure hook failed",Q)}console.error("[gemi/ai] agent controller hook failed",J)}async dispatchEvent(J,$){switch(J.type){case"tool-call":if(!J.part.partial&&!J.resent)await this.onToolCall({toolCallId:J.part.toolCallId,name:String(J.part.name),input:J.part.input},$);return;case"tool-result":{let Q=J.part;await this.onToolResult(Q,$,{toolCallId:Q.toolCallId,name:String(Q.name),input:L8(Q)});return}case"awaiting-input":await this.onAwaitingInput(J.pending,$);return;case"error":await this.onError(D8(J.error),$);return;default:return}}async readThread(J,$={}){let Z=await($.scope===null||$.scope===void 0?this.store:J8(this.store,$.scope)).loadThread(J);if(!Z)return null;let{messages:W}=await this.settleThread(J,Z,{write:!1});return W}isRunLive(J,$){return this.liveRuns.get(J)!==null}async settleThread(J,$,{write:Q}){let Z=(z)=>this.isRunLive(z,J),W=await kZ($,Z),X=W.messages,K=[],G=new Map(W.settled.map((z)=>[z.id,z]));if(C6(X)||Q)try{let z=await wZ(X,{threadId:J,store:m.store,isRunLive:Z,outputSchemaFor:(V)=>this.toolNamed(V)?.outputSchema,modelOutputFor:(V,Y)=>_8(this.toolNamed(V),Y,(D)=>this.reportHookFailure(D)),scan:this.jobsBlockMax()});X=z.messages,K=z.jobs;for(let V of z.settled)G.set(V.id,V);if(Q&&z.orphans.length>0){await IZ(m.store,z.orphans,(Y)=>this.reportHookFailure(Y));let V=new Set(z.orphans.map((Y)=>Y.id));K=K.map((Y)=>V.has(Y.id)?{...Y,orphaned:!0}:Y)}}catch(z){this.reportHookFailure(z)}if(Q&&G.size>0)try{await this.store.appendMessages(J,[...G.values()])}catch(z){this.reportHookFailure(z)}return{messages:X,jobs:K}}jobsBlockMax(){let J=this.agent.jobs?.contextBlock;if(J===!1)return 0;return J?.max??TJ}jobsBlock(J){return DQ(J,this.jobsBlockMax())}toolNamed(J){let $=(Q)=>{for(let Z of Q){let W=Z;if(Array.isArray(W.tools)){let X=$(W.tools);if(X)return X}else if(W.name===J)return W}return};return $(this.agent.tools??[])}follow(J,$){(async()=>{try{for await(let Q of J.frames())$.frame(Q)}catch(Q){this.reportHookFailure(Q)}})()}persistRun(J,$,Q,Z=null,W={id:null,notified:Promise.resolve()},X=null){let K=(Y)=>X?Y.then(()=>this.safely(X)):Y,G=Promise.resolve(),z=(async()=>{let Y;try{Y=await J.result()}catch(P){Z?.close(),await Z?.settled(),G=K(W.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:P instanceof Error?P.message:String(P),retryable:!1},$))));return}let D=Y.messages;if(Z?.close(D),await Z?.settled(),$.threadId&&D.length>0)try{await this.store.appendMessages($.threadId,D)}catch(P){this.reportHookFailure(P)}G=K(this.notifyRun(Y,D,$,W))})(),V=z.then(()=>F6(Promise.all([G,Q]).then(()=>{}),this.hookHoldMs));return{stored:z,hooks:V}}async notifyRun(J,$,Q,Z){await Z.notified;for(let W of $){if(W.id===Z.id)continue;await this.safely(()=>this.onMessage(W,Q))}await this.safely(()=>this.onStreamComplete(J,Q))}async safely(J){try{await J()}catch($){this.reportHookFailure($)}}}var i$=["turn","clientRunId","threadId","messages","regenerate","ifBusy"],t9=["text","files","toolResults"];function lJ(J,$=R8(J)?i$:[...i$,...t9]){let Q={};for(let[Z,W]of Object.entries(J)){if($.includes(Z))continue;Object.defineProperty(Q,Z,{value:W,writable:!0,enumerable:!0,configurable:!0})}return Q}function r9(J){if(J===null)return{};let $;if(typeof J==="string")try{$=JSON.parse(J)}catch{throw new d$("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new d$("The upload's `body` field must be a JSON object.");return lJ($,i$)}class d$ extends dJ{constructor(J){super(J);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:J}}},view:{}}}}async function iZ(J,$){try{return await J.upload($)}catch(Q){if(Q instanceof C8&&e9.has(Q.status))throw new A8($J(Q).message);throw Q}}var e9=new Set([400,413,415,422]);class n$ extends dJ{constructor(J,$){super($);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:J,message:$}}},view:{}}}}function J6(J,$,Q,Z){if(!J)return null;let{maxBytes:W,accept:X}=J;if(typeof W==="number"&&$.size>W)return{code:"file_too_large",message:`${JSON.stringify(Q)} is ${dZ($.size)}; the limit is ${dZ(W)}.`};if(X&&X.length>0&&!X.some((K)=>$6(K,Q,Z)))return{code:"unsupported_file_type",message:`${JSON.stringify(Q)} is not a type this chat accepts. Accepted: ${X.join(", ")}.`};return null}function $6(J,$,Q){let Z=J.trim().toLowerCase();if(!Z)return!1;if(Z.startsWith("."))return $.toLowerCase().endsWith(Z);let W=Q.toLowerCase().split(";")[0].trim();if(Z.endsWith("/*"))return W.startsWith(Z.slice(0,-1));return W===Z}function dZ(J){if(J<1024)return`${J} B`;let $=["KB","MB","GB"],Q=J/1024,Z=0;while(Q>=1024&&Z<$.length-1)Q/=1024,Z++;return`${Math.round(Q*10)/10} ${$[Z]}`}class A8 extends dJ{constructor(J){super(J);this.name="RejectedUploadError";let $=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test(J)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:$,message:J}}},view:{}}}}async function XJ(J,$){let Q=J?.rawRequest;if(!Q||Q.method==="GET"||Q.method==="HEAD"||!Q.body)return{body:{}};if(!Q6(Q.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let Z=Number(Q.headers.get("Content-Length"));if(Number.isFinite(Z)&&Z>$)return nZ($);let W;try{let K=await Z6(Q,$);if(K===null)return nZ($);W=K}catch{return{body:{},error:"The request body could not be read."}}if(!W.trim())return{body:{}};let X;try{X=JSON.parse(W)}catch{return{body:{},error:"The request body is not valid JSON."}}if(X===null||typeof X!=="object"||Array.isArray(X))return{body:{},error:"The request body must be a JSON object."};return{body:X}}function Q6(J){return W8(J)==="application/json"}async function Z6(J,$){if(!Number.isFinite($)||!J.body)return await J.text();let Q=J.body.getReader(),Z=[],W=0;for(;;){let{done:G,value:z}=await Q.read();if(G)break;if(W+=z.byteLength,W>$)return await Q.cancel().catch(A),null;Z.push(z)}let X=new Uint8Array(W),K=0;for(let G of Z)X.set(G,K),K+=G.byteLength;return new TextDecoder().decode(X)}function nZ(J){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${J} bytes).`}}function LJ(J,$,Q){return B(J,{...nJ(Z8(J),Q,J),code:$})}function u(J){if(J.status===413)return LJ(413,J.code??"body_too_large",J.error??"");return B(J.status??400,{code:J.code??"invalid_request",message:J.error})}function R8(J){return Boolean(J.turn)&&typeof J.turn==="object"}function W6(J){let $=R8(J)?J.turn:J,Q={};if(typeof $.text==="string")Q.text=$.text;if(Array.isArray($.files)){let Z=X6($.files);if(typeof Z==="string")return{error:Z};Q.files=Z}if(Array.isArray($.toolResults))Q.toolResults=$.toolResults;if(Object.keys(Q).length===0)return{};if($===J.turn&&$.localId!==void 0&&$.localId!==null&&$.localId!==""){let{localId:Z}=$;if(typeof Z!=="string")return{error:"turn.localId must be a string."};if(Z.length>oZ)return{error:`turn.localId is longer than ${oZ} characters.`};Q.localId=Z}return{turn:Q}}var oZ=200;function X6(J){let $=[];for(let[Q,Z]of J.entries()){let W=`turn.files[${Q}]`;if(!Z||typeof Z!=="object"||Array.isArray(Z))return`${W} must be an object.`;let X={};for(let Y of["fileId","attachmentId","name","mimeType"]){let D=Z[Y];if(D===void 0||D===null||D==="")continue;if(typeof D!=="string")return`${W}.${Y} must be a string.`;X[Y]=D}let{fileId:K,attachmentId:G,name:z,mimeType:V}=X;if(K?.startsWith(mJ))return`${W}.fileId holds a gemi attachment id (${K}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(G!==void 0&&!G.startsWith(mJ))return`${W}.attachmentId is not a gemi attachment id: it must start with "${mJ}".`;if(!K&&!G)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...K?{fileId:K}:{},...G?{attachmentId:G}:{},...z!==void 0?{name:z}:{},...V!==void 0?{mimeType:V}:{}})}return $}function K6(J,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let Z=Math.floor($.cursor);if(Z>=0)return Z+1;return}let Q=J?.rawRequest?.headers?.get("Last-Event-ID");if(Q){let Z=Number.parseInt(Q,10);if(Number.isFinite(Z))return Math.max(0,Z+1)}return}function sZ(J,$){let Q=J?.search?.get($);return typeof Q==="string"?Q:void 0}function G6(J){let $=t$(J);for(let Q=J.length-1;Q>=0;Q--){let Z=J[Q];if(Z.role!=="user"||$.has(Z.id))continue;let W="",X=[];for(let K of Z.content){if(K.type==="text")W+=K.text;if(K.type==="file")X.push({...K.fileId?{fileId:K.fileId}:{},...K.attachmentId?{attachmentId:K.attachmentId}:{},...K.name?{name:K.name}:{},...K.mimeType?{mimeType:K.mimeType}:{}})}if(!W&&X.length===0)continue;return{index:Q,turn:{...W?{text:W}:{},...X.length>0?{files:X}:{}}}}return null}function aZ(){return B(409,{code:"stopped",message:"The turn was stopped before it started."})}function V6(J){let $=J.event;if(J.text!==void 0||J.turn!==void 0)throw TypeError("AgentController.startTurn takes an `event` or a `text`/`turn`, not both: an event is not a person's message.");if(typeof $!=="object"||$===null||typeof $.name!=="string"||!v9.test($.name))throw TypeError('AgentController.startTurn\'s `event.name` must be letters, digits and `.`, `_`, `:`, `-` (at most 64), like "job-settled".');if($.text!==void 0&&typeof $.text!=="string")throw TypeError("AgentController.startTurn's `event.text` must be a string.");let Q;if($.data!==void 0)try{Q=JSON.parse(JSON.stringify($.data))}catch(Z){throw TypeError(`AgentController.startTurn's \`event.data\` is not JSON: ${String(Z)}`)}return{name:$.name,...$.text?{text:$.text}:{},...Q!==void 0?{data:Q}:{}}}function tZ(J){return B(409,{code:M8,message:`Thread ${J} has a run going, and this turn was not to interrupt it.`})}function n(){return B(403,nJ("permission","This run belongs to someone else.",403))}function z6(){return B(403,nJ("permission","A file in this turn was uploaded by someone else.",403))}function Y6(J){if(!Array.isArray(J))return[];let $=[];for(let Q of J){let Z=Q?.content;if(!Array.isArray(Z))continue;for(let W of Z)if(W&&typeof W==="object"&&typeof W.fileId==="string")$.push({fileId:W.fileId})}return $}var D6=["sdp","threadId","pushToTalk"];function g$(){return B(404,{code:"voice_not_enabled",message:"This agent has no voice: set `voice` on its controller."})}function B(J,$){return new Response(JSON.stringify({error:$}),{status:J,headers:{"Content-Type":"application/json"}})}function H6(J,$){if(typeof $!=="string"||$.length===0)return J;if($!=="both"&&$!=="provider"&&$!=="storage")throw Error(`Unknown attachment destination "${$}". Expected "both", "provider" or "storage".`);if($===J||J==="both"&&$==="storage")return $;if(J==="both"&&$==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${$}" destination, but the server's policy for it is "${J}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var rZ=!1;function P6(){if(rZ)return;rZ=!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 N6=2147483647;function F6(J,$){let Q=J.then(()=>{},()=>{});if(!($<=N6))return Q;let Z,W=new Promise((X)=>{Z=setTimeout(X,$)});return Promise.race([Q,W]).finally(()=>clearTimeout(Z))}var eZ=!1;function U6(J){if(eZ||Bun.env.NODE_ENV!=="production")return;if(!(J instanceof o$))return;eZ=!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 C6(J){return J.some(($)=>$.content.some((Q)=>Q.type==="tool-result"&&Q.status==="running"))}function J8(J,$){if(typeof $!=="string"||$==="")throw TypeError("A store scope is a non-empty string.");if(!J.forScope)throw Error("This controller's store cannot be scoped: storeScope() or a turn's `scope` needs a store that implements `forScope` (DatabaseAgentStore or MemoryAgentStore).");return J.forScope($)}function $8(J,$=!1){if($)return new Response(null,{status:204});return B(404,{code:"no_live_run",message:`No run in progress for thread ${J} in this process.`})}export{k6 as windowMessages,HJ as voiceTools,M6 as turnStarts,o6 as toRealtimeUsage,e8 as toAgentTools,L6 as supportsStrict,S6 as splitTurns,q6 as settleSummaries,_6 as s,a$ as redactError,i6 as parsePartialJson,A6 as messageSize,YJ as measureUsage,L$ as mcpVoiceTools,R$ as liveRuns,NJ as keepSummary,a6 as isCallNotFound,t$ as injectedMessageIds,z$ as generate,Y9 as evalChain,a9 as defineAgentHooks,M$ as defaultVoiceStore,v6 as defaultUsageLimitStore,f6 as defaultSummaryStore,l6 as defaultPromptCacheKey,s$ as defaultNonceStore,E$ as defaultFileOwners,sJ as defaultAttachmentStore,I$ as defaultAgentStore,hJ as VoiceHangup,d as VoiceBridge,B6 as Usage,D$ as ToolNamespace,i as ToolError,m6 as ToolArgumentsTooLongError,h6 as Skill,oJ as ScopedAttachments,g6 as SKILLS_NAMESPACE,x$ as RedisReceiptStore,z8 as RedisNonceStore,d6 as RealtimeSideband,r$ as RealtimeRequestError,s6 as RealtimeClient,VQ as Prompt,Y8 as PrismaNonceStore,y6 as PendingEscalation,t6 as OpenAIProvider,F$ as OpenAIImageProvider,B$ as MemoryVoiceSessionStore,b6 as MemoryUsageLimitStore,I6 as MemorySummaryStore,j$ as MemoryReceiptStore,o$ as MemoryNonceStore,gJ as MemoryLiveRuns,cJ as MemoryFileOwners,vJ as MemoryCircuitStore,U8 as MemoryAttachmentStore,UJ as MemoryAgentStore,FQ as MemoryAgentJobStore,IQ as MEMORY_NAMESPACE,FJ as LiveRunNotFoundError,CQ as JobsRequireThreadError,UQ as JobHandle,O6 as JSONSchemaError,P8 as InvalidAttachmentScopeError,EQ as InMemoryAgentMemoryStore,qJ as ImageRequestError,bJ as ImageProvider,H$ as ImageModel,WJ as FrameCursorEvictedError,DJ as FallbackProvider,xQ as FakeAgentMemoryStore,IJ as Eval,S$ as DatabaseAgentStore,Z$ as DatabaseAgentMemoryStore,$$ as DatabaseAgentJobStore,n6 as DEFAULT_TRANSCRIPTION_MODEL,RQ as DEFAULT_MEMORY_MAX_TOKENS,wQ as DEFAULT_MEMORY_LIMITS,T6 as DEFAULT_MAX_SUMMARY_TOKENS,c6 as DEFAULT_MAX_RUN_DURATION_MS,OQ as DEFAULT_JOB_DEADLINE_MS,TJ as DEFAULT_JOBS_CONTEXT_MAX,PJ as DEFAULT_DELEGATE_NAME,R6 as DEFAULT_CONTEXT_WINDOW_STEP,E6 as DEFAULT_CONTEXT_WINDOW_NOTE,j6 as DEFAULT_COMPACT_TRIGGER_TOKENS,x6 as DEFAULT_COMPACT_INSTRUCTIONS,w6 as COMPACT_SUMMARY_HEADER,J0 as AzureOpenAIProvider,U$ as AzureOpenAIImageProvider,e6 as AzureAnthropicProvider,H8 as AttachmentNotFoundError,r6 as AnthropicProvider,KJ as AgentTurnError,fJ as AgentTool,u6 as AgentRunError,_$ as AgentProvider,kQ as AgentMemoryRefusedError,TQ as AgentMemoryConflictError,jQ as AgentMemories,m as AgentJobs,J$ as AgentJobDeadlineSweep,_Q as AgentJob,iJ as AgentController,p6 as Agent};
|
|
337
|
+
|
|
338
|
+
//# debugId=BB791163EF8332A764756E2164756E21
|