gemi 0.131.0 → 0.133.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/AgentController.d.ts +73 -0
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/AgentProvider.d.ts +25 -0
- package/dist/ai/AgentProvider.d.ts.map +1 -1
- package/dist/ai/VoiceBridge.d.ts +365 -0
- package/dist/ai/VoiceBridge.d.ts.map +1 -0
- package/dist/ai/index.d.ts +13 -0
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +18 -18
- package/dist/ai/index.js.map +11 -6
- package/dist/ai/providers/endpoints.d.ts +19 -0
- package/dist/ai/providers/endpoints.d.ts.map +1 -1
- package/dist/ai/providers/realtime.d.ts +272 -0
- package/dist/ai/providers/realtime.d.ts.map +1 -0
- package/dist/ai/providers/sideband.d.ts +254 -0
- package/dist/ai/providers/sideband.d.ts.map +1 -0
- package/dist/ai/runtime.d.ts.map +1 -1
- package/dist/ai/types.d.ts +15 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/voice/index.d.ts +23 -0
- package/dist/ai/voice/index.d.ts.map +1 -0
- package/dist/ai/voice/index.js +433 -0
- package/dist/ai/voice/index.js.map +1 -0
- package/dist/ai/voice/state.d.ts +34 -0
- package/dist/ai/voice/state.d.ts.map +1 -0
- package/dist/ai/voice/useVoiceSession.d.ts +82 -0
- package/dist/ai/voice/useVoiceSession.d.ts.map +1 -0
- package/dist/ai/voice/voiceCall.d.ts +57 -0
- package/dist/ai/voice/voiceCall.d.ts.map +1 -0
- package/dist/ai/voice/wire.d.ts +66 -0
- package/dist/ai/voice/wire.d.ts.map +1 -0
- package/dist/ai/voiceConfig.d.ts +70 -0
- package/dist/ai/voiceConfig.d.ts.map +1 -0
- package/dist/ai/voiceMcp.d.ts +89 -0
- package/dist/ai/voiceMcp.d.ts.map +1 -0
- package/dist/ai/voiceStore.d.ts +52 -0
- package/dist/ai/voiceStore.d.ts.map +1 -0
- package/dist/app/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-4gmhx2ba.js → chunk-0eamc2tr.js} +2 -2
- package/dist/{chunk-4gmhx2ba.js.map → chunk-0eamc2tr.js.map} +1 -1
- package/dist/{chunk-2x0n3ze1.js → chunk-0gg4e94v.js} +2 -2
- package/dist/{chunk-2x0n3ze1.js.map → chunk-0gg4e94v.js.map} +1 -1
- package/dist/{chunk-p642ja42.js → chunk-0rhf4g12.js} +3 -3
- package/dist/{chunk-p642ja42.js.map → chunk-0rhf4g12.js.map} +1 -1
- package/dist/{chunk-dxm5gxqk.js → chunk-1awxdnb6.js} +1 -1
- package/dist/{chunk-2senwsdq.js → chunk-2cnawkke.js} +12 -12
- package/dist/{chunk-2senwsdq.js.map → chunk-2cnawkke.js.map} +3 -3
- package/dist/{chunk-fxm8fqh9.js → chunk-33hdxe7v.js} +1 -1
- package/dist/{chunk-63xekerg.js → chunk-3g5q0cj5.js} +2 -2
- package/dist/{chunk-63xekerg.js.map → chunk-3g5q0cj5.js.map} +1 -1
- package/dist/{chunk-xjs72pb0.js → chunk-3h37f124.js} +2 -2
- package/dist/{chunk-xjs72pb0.js.map → chunk-3h37f124.js.map} +1 -1
- package/dist/{chunk-65fq5a9d.js → chunk-4278e429.js} +2 -2
- package/dist/{chunk-65fq5a9d.js.map → chunk-4278e429.js.map} +1 -1
- package/dist/chunk-47e7fbsp.js +5 -0
- package/dist/{chunk-mvka90rq.js.map → chunk-47e7fbsp.js.map} +1 -1
- package/dist/{chunk-p6b0cyf8.js → chunk-4pvv8qs0.js} +2 -2
- package/dist/{chunk-p6b0cyf8.js.map → chunk-4pvv8qs0.js.map} +1 -1
- package/dist/{chunk-rjyw1thg.js → chunk-4t41m5f1.js} +2 -2
- package/dist/{chunk-rjyw1thg.js.map → chunk-4t41m5f1.js.map} +1 -1
- package/dist/{chunk-f21v4n2v.js → chunk-53rr32zm.js} +1 -1
- package/dist/{chunk-xhvknqvn.js → chunk-5pdgh9a1.js} +2 -2
- package/dist/{chunk-xhvknqvn.js.map → chunk-5pdgh9a1.js.map} +1 -1
- package/dist/{chunk-e4ay1vg9.js → chunk-65j32dtn.js} +2 -2
- package/dist/{chunk-e4ay1vg9.js.map → chunk-65j32dtn.js.map} +1 -1
- package/dist/{chunk-jxvec7jc.js → chunk-6fr6j338.js} +2 -2
- package/dist/{chunk-jxvec7jc.js.map → chunk-6fr6j338.js.map} +1 -1
- package/dist/{chunk-jd1afbrs.js → chunk-6hz63ts4.js} +4 -4
- package/dist/{chunk-jd1afbrs.js.map → chunk-6hz63ts4.js.map} +1 -1
- package/dist/{chunk-4z0rt6ws.js → chunk-6qty7at2.js} +2 -2
- package/dist/{chunk-4z0rt6ws.js.map → chunk-6qty7at2.js.map} +1 -1
- package/dist/{chunk-pzb3agv9.js → chunk-7nxnyw7x.js} +2 -2
- package/dist/{chunk-pzb3agv9.js.map → chunk-7nxnyw7x.js.map} +1 -1
- package/dist/{chunk-7n0zn5h4.js → chunk-8ryrjtn0.js} +2 -2
- package/dist/{chunk-7n0zn5h4.js.map → chunk-8ryrjtn0.js.map} +1 -1
- package/dist/{chunk-c1gq2ttb.js → chunk-8sde8337.js} +2 -2
- package/dist/{chunk-c1gq2ttb.js.map → chunk-8sde8337.js.map} +1 -1
- package/dist/{chunk-cggywjzz.js → chunk-99a4e6zf.js} +2 -2
- package/dist/{chunk-cggywjzz.js.map → chunk-99a4e6zf.js.map} +1 -1
- package/dist/chunk-b6yb3svm.js +6 -0
- package/dist/{chunk-539w9yt3.js.map → chunk-b6yb3svm.js.map} +2 -2
- package/dist/{chunk-822p54vc.js → chunk-beb265c9.js} +2 -2
- package/dist/{chunk-822p54vc.js.map → chunk-beb265c9.js.map} +1 -1
- package/dist/{chunk-hdgbh8hn.js → chunk-cxsvzqd4.js} +2 -2
- package/dist/{chunk-hdgbh8hn.js.map → chunk-cxsvzqd4.js.map} +1 -1
- package/dist/{chunk-pahr13xg.js → chunk-dt95z6et.js} +2 -2
- package/dist/{chunk-pahr13xg.js.map → chunk-dt95z6et.js.map} +1 -1
- package/dist/{chunk-hr8annr1.js → chunk-feajsgns.js} +2 -2
- package/dist/{chunk-hr8annr1.js.map → chunk-feajsgns.js.map} +1 -1
- package/dist/{chunk-2tda49mv.js → chunk-ff60bzvf.js} +2 -2
- package/dist/{chunk-2tda49mv.js.map → chunk-ff60bzvf.js.map} +1 -1
- package/dist/{chunk-b00z33zg.js → chunk-gng5e7pd.js} +1 -1
- package/dist/{chunk-mz73066c.js → chunk-gqgpwb88.js} +2 -2
- package/dist/{chunk-mz73066c.js.map → chunk-gqgpwb88.js.map} +1 -1
- package/dist/{chunk-h0xye69a.js → chunk-ha15x5ns.js} +2 -2
- package/dist/{chunk-h0xye69a.js.map → chunk-ha15x5ns.js.map} +1 -1
- package/dist/{chunk-d5g1caxb.js → chunk-hb9hm8za.js} +3 -3
- package/dist/{chunk-d5g1caxb.js.map → chunk-hb9hm8za.js.map} +1 -1
- package/dist/{chunk-8fvt7kys.js → chunk-hf492gg2.js} +1 -1
- package/dist/{chunk-fgtr9cds.js → chunk-hj88dcss.js} +3 -3
- package/dist/{chunk-fgtr9cds.js.map → chunk-hj88dcss.js.map} +1 -1
- package/dist/{chunk-hnf11jhc.js → chunk-j5g7qc5f.js} +2 -2
- package/dist/{chunk-hnf11jhc.js.map → chunk-j5g7qc5f.js.map} +1 -1
- package/dist/{chunk-e1fhy2h5.js → chunk-jgx8ggbz.js} +2 -2
- package/dist/{chunk-e1fhy2h5.js.map → chunk-jgx8ggbz.js.map} +1 -1
- package/dist/{chunk-35zw2s61.js → chunk-jx2mgvvt.js} +3 -3
- package/dist/{chunk-35zw2s61.js.map → chunk-jx2mgvvt.js.map} +1 -1
- package/dist/{chunk-w26cw41m.js → chunk-jx5zx48j.js} +2 -2
- package/dist/{chunk-w26cw41m.js.map → chunk-jx5zx48j.js.map} +1 -1
- package/dist/{chunk-z1gjgr1c.js → chunk-jy9dkgt0.js} +2 -2
- package/dist/{chunk-z1gjgr1c.js.map → chunk-jy9dkgt0.js.map} +1 -1
- package/dist/{chunk-7j48ymk1.js → chunk-k2xeskp6.js} +2 -2
- package/dist/{chunk-7j48ymk1.js.map → chunk-k2xeskp6.js.map} +1 -1
- package/dist/{chunk-jxmc33m9.js → chunk-ka991yx4.js} +2 -2
- package/dist/{chunk-jxmc33m9.js.map → chunk-ka991yx4.js.map} +1 -1
- package/dist/{chunk-65s63bdh.js → chunk-krk880my.js} +2 -2
- package/dist/{chunk-65s63bdh.js.map → chunk-krk880my.js.map} +1 -1
- package/dist/{chunk-x4yq0c9v.js → chunk-m9vwg9j1.js} +3 -3
- package/dist/{chunk-x4yq0c9v.js.map → chunk-m9vwg9j1.js.map} +1 -1
- package/dist/{chunk-x07rp3fc.js → chunk-mpqvmge4.js} +1 -1
- package/dist/{chunk-n7sbwpce.js → chunk-mw7ft5bs.js} +2 -2
- package/dist/{chunk-n7sbwpce.js.map → chunk-mw7ft5bs.js.map} +1 -1
- package/dist/{chunk-v5esvs66.js → chunk-njpnstck.js} +2 -2
- package/dist/{chunk-v5esvs66.js.map → chunk-njpnstck.js.map} +1 -1
- package/dist/{chunk-p320fd3g.js → chunk-p82868xx.js} +2 -2
- package/dist/{chunk-p320fd3g.js.map → chunk-p82868xx.js.map} +1 -1
- package/dist/{chunk-jbd723h1.js → chunk-pm8wjatv.js} +3 -3
- package/dist/{chunk-jbd723h1.js.map → chunk-pm8wjatv.js.map} +1 -1
- package/dist/{chunk-t227jn4b.js → chunk-q15f5g86.js} +2 -2
- package/dist/{chunk-t227jn4b.js.map → chunk-q15f5g86.js.map} +1 -1
- package/dist/{chunk-838cdh6v.js → chunk-qfra7gah.js} +2 -2
- package/dist/{chunk-838cdh6v.js.map → chunk-qfra7gah.js.map} +1 -1
- package/dist/{chunk-aprjvzrz.js → chunk-rnp5k8m3.js} +2 -2
- package/dist/{chunk-aprjvzrz.js.map → chunk-rnp5k8m3.js.map} +1 -1
- package/dist/{chunk-qz89m7ss.js → chunk-rzqft8q8.js} +2 -2
- package/dist/{chunk-qz89m7ss.js.map → chunk-rzqft8q8.js.map} +1 -1
- package/dist/{chunk-zc5962gh.js → chunk-s025aycr.js} +2 -2
- package/dist/{chunk-zc5962gh.js.map → chunk-s025aycr.js.map} +1 -1
- package/dist/{chunk-y14weak4.js → chunk-s21kn0x8.js} +2 -2
- package/dist/{chunk-y14weak4.js.map → chunk-s21kn0x8.js.map} +1 -1
- package/dist/{chunk-3wnczt5w.js → chunk-s55t7rxw.js} +2 -2
- package/dist/{chunk-3wnczt5w.js.map → chunk-s55t7rxw.js.map} +1 -1
- package/dist/{chunk-fzs7g6mc.js → chunk-s782bzeq.js} +2 -2
- package/dist/{chunk-fzs7g6mc.js.map → chunk-s782bzeq.js.map} +1 -1
- package/dist/{chunk-77ymcf7q.js → chunk-sa6cxt3g.js} +2 -2
- package/dist/{chunk-77ymcf7q.js.map → chunk-sa6cxt3g.js.map} +1 -1
- package/dist/{chunk-dz76qhx8.js → chunk-swwkdm75.js} +2 -2
- package/dist/{chunk-dz76qhx8.js.map → chunk-swwkdm75.js.map} +1 -1
- package/dist/{chunk-58mg4rpd.js → chunk-t33yh84d.js} +2 -2
- package/dist/{chunk-58mg4rpd.js.map → chunk-t33yh84d.js.map} +1 -1
- package/dist/{chunk-mym7egdq.js → chunk-vnw91fe1.js} +2 -2
- package/dist/{chunk-mym7egdq.js.map → chunk-vnw91fe1.js.map} +1 -1
- package/dist/{chunk-4wda9teq.js → chunk-w1cksc5z.js} +3 -3
- package/dist/{chunk-4wda9teq.js.map → chunk-w1cksc5z.js.map} +1 -1
- package/dist/chunk-wevj4981.js +122 -0
- package/dist/{chunk-fx7r6pdf.js.map → chunk-wevj4981.js.map} +3 -3
- package/dist/{chunk-ayjfs5mm.js → chunk-wrsf2abe.js} +2 -2
- package/dist/{chunk-ayjfs5mm.js.map → chunk-wrsf2abe.js.map} +1 -1
- package/dist/{chunk-j1wc4afr.js → chunk-x16ckgq1.js} +2 -2
- package/dist/{chunk-j1wc4afr.js.map → chunk-x16ckgq1.js.map} +1 -1
- package/dist/{chunk-gnaxedwh.js → chunk-x51tegk3.js} +2 -2
- package/dist/{chunk-gnaxedwh.js.map → chunk-x51tegk3.js.map} +1 -1
- package/dist/{chunk-qspam5cf.js → chunk-x5hj0mqp.js} +2 -2
- package/dist/{chunk-qspam5cf.js.map → chunk-x5hj0mqp.js.map} +1 -1
- package/dist/{chunk-dp2yz8bj.js → chunk-x9bk5s21.js} +2 -2
- package/dist/{chunk-dp2yz8bj.js.map → chunk-x9bk5s21.js.map} +1 -1
- package/dist/{chunk-p462p2xe.js → chunk-xvvsc58s.js} +2 -2
- package/dist/{chunk-p462p2xe.js.map → chunk-xvvsc58s.js.map} +1 -1
- package/dist/{chunk-0g5f8ymy.js → chunk-xymr3asa.js} +2 -2
- package/dist/{chunk-0g5f8ymy.js.map → chunk-xymr3asa.js.map} +1 -1
- package/dist/{chunk-j4y0sjdc.js → chunk-ysc7ykss.js} +2 -2
- package/dist/{chunk-j4y0sjdc.js.map → chunk-ysc7ykss.js.map} +1 -1
- package/dist/{chunk-3xy41vc0.js → chunk-z61dj480.js} +3 -3
- package/dist/{chunk-3xy41vc0.js.map → chunk-z61dj480.js.map} +1 -1
- package/dist/{chunk-0q68t71d.js → chunk-z9xxthp1.js} +3 -3
- package/dist/{chunk-0q68t71d.js.map → chunk-z9xxthp1.js.map} +1 -1
- package/dist/{chunk-47eav3ex.js → chunk-zv5qyrqg.js} +2 -2
- package/dist/{chunk-47eav3ex.js.map → chunk-zv5qyrqg.js.map} +1 -1
- package/dist/{chunk-asmszzkp.js → chunk-zyhmn3hy.js} +3 -3
- package/dist/{chunk-asmszzkp.js.map → chunk-zyhmn3hy.js.map} +1 -1
- package/dist/{chunk-zzgt759n.js → chunk-zypmy8yq.js} +2 -2
- package/dist/{chunk-zzgt759n.js.map → chunk-zypmy8yq.js.map} +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/ApiRouter.d.ts +27 -5
- package/dist/http/ApiRouter.d.ts.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/defaults.d.ts.map +1 -1
- package/dist/orm/index.js +3 -3
- package/dist/orm/index.js.map +3 -3
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/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 +2 -1
- package/dist/chunk-539w9yt3.js +0 -6
- package/dist/chunk-fx7r6pdf.js +0 -122
- package/dist/chunk-mvka90rq.js +0 -5
- /package/dist/{chunk-dxm5gxqk.js.map → chunk-1awxdnb6.js.map} +0 -0
- /package/dist/{chunk-fxm8fqh9.js.map → chunk-33hdxe7v.js.map} +0 -0
- /package/dist/{chunk-f21v4n2v.js.map → chunk-53rr32zm.js.map} +0 -0
- /package/dist/{chunk-b00z33zg.js.map → chunk-gng5e7pd.js.map} +0 -0
- /package/dist/{chunk-8fvt7kys.js.map → chunk-hf492gg2.js.map} +0 -0
- /package/dist/{chunk-x07rp3fc.js.map → chunk-mpqvmge4.js.map} +0 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ac as
|
|
3
|
-
`)}function
|
|
2
|
+
import{Ac as k,Bc as EQ,Cc as X9,Dc as Y9,Ec as V9,Fc as H9,Gc as z9,Hc as D9,Ic as B9,Jc as P9,Kc as F9,Lc as U9,Mc as N9,Nc as OQ,Oc as O9,Pc as V6,Qc as L9,Rc as C9,Sc as DJ,Tc as uJ,Uc as _9,Vc as S9,Wc as M9,Xb as TQ,Xc as A9,Yb as $6,Yc as k9,Zb as jQ,Zc as R9,ac as j,bc as b,cc as y,dc as qQ,ec as Z6,fc as W6,gc as G6,hc as c,ic as K6,jc as wJ,kc as X6,lc as Y6,mc as IJ,nc as uQ,oc as cQ,qc as mQ,rc as v,sc as h$,tc as y$,uc as pQ,wc as lQ,xc as I,yc as rQ,zc as i}from"../chunk-2cnawkke.js";import{pd as wQ}from"../chunk-qpwb3gnh.js";import"../chunk-xymr3asa.js";import{Ah as W9,Bh as G9,Ch as K9,Dh as x,gh as t$,hi as J6,jh as e$,ki as FQ,oi as Q6,zh as N$}from"../chunk-0rhf4g12.js";import{pi as r$,ri as EJ,si as xJ}from"../chunk-zv5qyrqg.js";import{Bi as h}from"../chunk-4t41m5f1.js";import"../chunk-ysc7ykss.js";import"../chunk-jx5zx48j.js";import{Ej as hQ,Fj as yQ,Tj as gQ}from"../chunk-z9xxthp1.js";import"../chunk-65j32dtn.js";import{Gk as T$}from"../chunk-jx2mgvvt.js";import"../chunk-ha15x5ns.js";import"../chunk-gqgpwb88.js";import"../chunk-cxsvzqd4.js";import"../chunk-rnp5k8m3.js";class fJ extends wQ{name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await v.sweep({limit:100})===100);}}var VJ=20;function bQ(J,Q){if(Q<=0||J.length===0)return null;let $=(G,K)=>K.createdAt-G.createdAt||(G.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((G)=>G.state==="running").sort($),...J.filter((G)=>G.state!=="running").sort($)].slice(0,Q).map((G)=>{let K=[`- ${G.id} (${G.toolName})`];if(G.state==="running")K.push(`running since ${vJ(G.createdAt)}`);else if(G.state==="ok")K.push(`finished at ${vJ(G.settledAt??G.updatedAt)}`);else{let X=G.error?`${G.error.code}: ${IQ(G.error.message,200)}`:"failed";K.push(`failed at ${vJ(G.settledAt??G.updatedAt)} (${X})`)}if(G.summary!==void 0)K.push(`summary: ${IQ(JSON.stringify(G.summary),300)}`);if(G.orphaned)K.push("its tool call was lost when the turn that started it was cut short");return K.join("; ")}),"</jobs>"].join(`
|
|
3
|
+
`)}function vJ(J){return new Date(J).toISOString().replace(/\.\d{3}Z$/,"Z")}function IQ(J,Q){return J.length<=Q?J:`${J.slice(0,Q-1)}\u2026`}class yJ{table;sql;dialect;connection;constructor(J,Q={}){let $=Q.table??"gemi_agent_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test($))throw Error(`The agent jobs table name "${$}" is not a plain identifier. Use letters, digits and underscores.`);this.table=$,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of P6(this.dialect,this.table))await this.sql.unsafe(J)}async transaction(J){if(this.connection===void 0||this.joinable())return J();return gQ(this.sql,()=>J(),{connection:this.connection})}async create(J){let Q=this.q(),$=this.clock(Q);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
|
VALUES
|
|
8
8
|
(${J.id}, ${J.threadId}, ${J.runId}, ${J.toolCallId}, ${J.toolName},
|
|
9
|
-
${J.owner}, ${J.job}, ${
|
|
9
|
+
${J.owner}, ${J.job}, ${HJ(J.summary)}, 'running', 0, ${J.attachmentScope},
|
|
10
10
|
${$}, ${$}, ${$} + ${this.ms(Q,J.deadlineMs)})
|
|
11
|
-
`;let Z=await this.get(J.id);if(!Z)throw Error(`The background job ${J.id} was not found after it was written.`);return Z}async get(J){let Q=this.q(),$=await Q`SELECT * FROM ${this.name(Q)} WHERE id = ${J}`;return $[0]?
|
|
11
|
+
`;let Z=await this.get(J.id);if(!Z)throw Error(`The background job ${J.id} was not found after it was written.`);return Z}async get(J){let Q=this.q(),$=await Q`SELECT * FROM ${this.name(Q)} WHERE id = ${J}`;return $[0]?hJ($[0]):null}async listForThread(J,Q={}){let $=this.q(),Z=Q.states===void 0?$`1 = 1`:Q.states.length===0?$`1 = 0`:$`state IN (${fQ($,Q.states)})`;return(Q.limit===void 0?await $`
|
|
12
12
|
SELECT * FROM ${this.name($)}
|
|
13
13
|
WHERE thread_id = ${J} AND ${Z}
|
|
14
14
|
ORDER BY created_at DESC, id DESC
|
|
@@ -17,18 +17,18 @@ import{Ac as R,Bc as BQ,Cc as S9,Dc as M9,Ec as A9,Fc as R9,Gc as T9,Hc as j9,Ic
|
|
|
17
17
|
WHERE thread_id = ${J} AND ${Z}
|
|
18
18
|
ORDER BY created_at DESC, id DESC
|
|
19
19
|
LIMIT ${Math.max(0,Math.floor(Q.limit))}
|
|
20
|
-
`).map(
|
|
21
|
-
UPDATE ${this.name(Z)} SET ${
|
|
22
|
-
WHERE id = ${J} AND state IN (${
|
|
23
|
-
`;return
|
|
20
|
+
`).map(hJ)}async transition(J,Q,$){if(Q.length===0)return!1;let Z=this.q(),W=this.clock(Z),G=[Z`updated_at = ${W}`];if($.state!==void 0)G.push(Z`state = ${$.state}`);if("output"in $)G.push(Z`output = ${HJ($.output)}`);if("error"in $)G.push(Z`error = ${HJ($.error)}`);if("usage"in $)G.push(Z`${this.column(Z,"usage")} = ${HJ($.usage)}`);if("orphaned"in $)G.push(Z`orphaned = ${$.orphaned?1:0}`);if($.state!==void 0&&$.state!=="running")G.push($.settledAt!==void 0?Z`settled_at = COALESCE(settled_at, ${this.ms(Z,$.settledAt)})`:Z`settled_at = COALESCE(settled_at, ${W})`);let K=G.reduce((V,Y)=>Z`${V}, ${Y}`),X=await Z`
|
|
21
|
+
UPDATE ${this.name(Z)} SET ${K}
|
|
22
|
+
WHERE id = ${J} AND state IN (${fQ(Z,Q)})
|
|
23
|
+
`;return vQ(X)>0}async overdue(J,Q){let $=this.q();return(await $`
|
|
24
24
|
SELECT * FROM ${this.name($)}
|
|
25
25
|
WHERE state = 'running' AND deadline_at <= ${this.ms($,J)}
|
|
26
26
|
ORDER BY deadline_at, id
|
|
27
27
|
LIMIT ${Math.max(0,Math.floor(Q))}
|
|
28
|
-
`).map(
|
|
28
|
+
`).map(hJ)}async now(){let J=this.q(),[Q]=await J`SELECT ${this.clock(J)} AS now`;return Number(Q.now)}async prune(J){let Q=this.q(),$=await Q`
|
|
29
29
|
DELETE FROM ${this.name(Q)}
|
|
30
30
|
WHERE state <> 'running' AND settled_at <= ${this.clock(Q)} - ${this.ms(Q,J)}
|
|
31
|
-
`;return
|
|
31
|
+
`;return vQ($)}joinable(){if(this.connection===void 0)return;let J=hQ();if(J===void 0||yQ()!==this.connection)return;return J}q(){return this.joinable()??this.sql}column(J,Q){let $=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe($?`\`${Q}\``:`"${Q}"`)}name(J){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe(Q?`\`${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,Q){let $=Math.max(0,Math.round(Q));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${$} AS SIGNED)`:J`CAST(${$} AS BIGINT)`}}function fQ(J,Q){return Q.map(($)=>J`${$}`).reduce(($,Z)=>J`${$}, ${Z}`)}function HJ(J){return J===void 0?null:JSON.stringify(J)}function zJ(J){if(J===null||J===void 0)return;return JSON.parse(String(J))}function hJ(J){let Q=zJ(J.summary),$=zJ(J.output),Z=zJ(J.error),W=zJ(J.usage);return{id:String(J.id),threadId:String(J.thread_id),runId:String(J.run_id),toolCallId:String(J.tool_call_id),toolName:String(J.tool_name),owner:J.owner===null||J.owner===void 0?null:String(J.owner),job:J.job===null||J.job===void 0?null:String(J.job),...Q!==void 0?{summary:Q}:{},state:String(J.state),...$!==void 0?{output:$}:{},...Z!==void 0?{error:Z}:{},...W!==void 0?{usage:W}:{},...Number(J.orphaned)===1?{orphaned:!0}:{},attachmentScope:J.attachment_scope===null||J.attachment_scope===void 0?null:String(J.attachment_scope),createdAt:Number(J.created_at),updatedAt:Number(J.updated_at),deadlineAt:Number(J.deadline_at),...J.settled_at===null||J.settled_at===void 0?{}:{settledAt:Number(J.settled_at)}}}function vQ(J){let Q=J;return Math.max(Number(Q.count??0),Number(Q.affectedRows??0))}function P6(J,Q){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Q}\` (
|
|
32
32
|
\`id\` VARCHAR(191) NOT NULL,
|
|
33
33
|
\`thread_id\` VARCHAR(191) NOT NULL,
|
|
34
34
|
\`run_id\` VARCHAR(191) NOT NULL,
|
|
@@ -72,17 +72,17 @@ import{Ac as R,Bc as BQ,Cc as S9,Dc as M9,Ec as A9,Fc as R9,Gc as T9,Hc as j9,Ic
|
|
|
72
72
|
"updated_at" BIGINT NOT NULL,
|
|
73
73
|
"deadline_at" BIGINT NOT NULL,
|
|
74
74
|
"settled_at" BIGINT${Z}
|
|
75
|
-
)`,`CREATE INDEX IF NOT EXISTS "${Q}_thread_id_created_at_idx" ON "${Q}"("thread_id", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Q}_state_deadline_at_idx" ON "${Q}"("state", "deadline_at")`]}var l$=/^[A-Za-z0-9_-]{1,64}$/;function d$(J,Q){let $=i$(Q)?Q:{filter:Q},Z=$.deferred===!0,W=J.descriptors($.filter);if(!$.namespaces)return W.map((H)=>RJ(J,H,Z));let G=Object.entries($.namespaces),V=new Set(J.descriptors().flatMap((H)=>H.tags));for(let[H,B]of G){if(!l$.test(H))throw Error(`toAgentTools: "${H}" is not a valid namespace name. A namespace is named by its tag and sent to the provider as a tool name is \u2014 letters, digits, "_" and "-", at most 64.`);if(typeof B?.description!=="string"||B.description.trim()==="")throw Error(`toAgentTools: the namespace "${H}" needs a description. It is what the model reads to decide whether to look inside.`);if(!V.has(H))throw Error(`toAgentTools: no tool is tagged "${H}", so its namespace would be empty.`)}let K=new Map(G.map(([H])=>[H,[]])),Y=[];for(let H of W){let B=G.find(([D])=>H.tags.includes(D))?.[0];if(B===void 0)Y.push(RJ(J,H,Z));else K.get(B).push(RJ(J,H,!1))}let X=[];for(let[H,B]of G){let D=K.get(H);if(D.length===0)continue;X.push(jJ.create({name:H,description:B.description,tools:D,deferred:B.deferred??Z}))}return[...X,...Y]}function i$(J){return typeof J==="object"&&J!==null&&(("filter"in J)||("namespaces"in J)||("deferred"in J))}function RJ(J,Q,$){if(Q.kind==="tool")return n$(J,Q,$);return QJ.create({name:Q.name,description:Q.description,inputSchema:Q.inputSchema,...Q.outputSchema?{outputSchema:Q.outputSchema}:{},requiresApproval:Q.requiresApproval,deferred:$,execute:(Z,W)=>{let G=n.getStore()?.req;if(!G)throw new TJ(`"${Q.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:G},Q.name,Z,W)}})}function n$(J,Q,$){let Z=J.nativeTool(Q.name);return QJ.create({name:Q.name,description:Q.description,inputSchema:Q.inputSchema,...Q.outputSchema?{outputSchema:Q.outputSchema}:{},requiresApproval:Q.requiresApproval,deferred:$,...Z.timeoutMs!==void 0?{timeoutMs:Z.timeoutMs}:{},...Z.async?{async:Z.async}:{},execute:(W,G)=>{let V=n.getStore()?.req;return J.startNative(V?{kind:"local",req:V}:void 0,Q.name,W,G)}})}function o$(J){if(J==="auto")return;let Q=/^(\d+)x(\d+)$/.exec(J);if(!Q)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(J)}.`);let $=Number(Q[1]),Z=Number(Q[2]);if($%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($/Z,Z/$)>3)throw Error(`Image size ${J} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function kQ(J,Q){if(J.size!==void 0)try{o$(J.size)}catch($){throw Error(`${Q}: ${$.message}`)}if(J.background==="transparent"&&J.format==="jpeg")throw Error(`${Q}: a transparent background needs "png"; JPEG has no alpha channel.`);if(J.compression!==void 0){let $=J.compression;if(!Number.isInteger($)||$<0||$>100)throw Error(`${Q}: compression is an integer from 0 to 100; got ${$}.`)}}function EQ(J,Q){if(J instanceof File)return J;let $=J.type||"image/png",Z=$==="image/jpeg"?"jpg":$.split("/")[1]??"png";return new File([J],`${Q}.${Z}`,{type:$})}class kJ{name;provider;settings;constructor(J){let{name:Q,provider:$,...Z}=J;kQ(Z,`ImageModel "${Q}"`),this.name=Q,this.provider=$,this.settings=Z}static create(J){return new kJ(J)}async generate(J){let Q=this.merge(J);return qQ(await this.provider.generate({prompt:J.prompt,...Q,signal:J.signal}))}async edit(J){let Q=this.merge(J);return qQ(await this.provider.edit({prompt:J.prompt,...Q,images:J.images.map(($,Z)=>EQ($,`image-${Z}`)),...J.mask?{mask:EQ(J.mask,"mask")}:{},signal:J.signal}))}merge(J){let Q={...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 kQ(Q,`ImageModel "${this.name}"`),Q}}function qQ(J){return{image:new Blob([J.bytes],{type:J.mimeType}),mimeType:J.mimeType,size:J.size,usage:J.usage}}function I(J){return typeof process>"u"?void 0:process.env?.[J]}var s$="preview";function xQ(J){let Q=J.trim().replace(/\/+$/,"");if(!Q)return"";return`${Q.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function a$(J){return/^\d{4}-\d{2}-\d{2}/.test(J)?"":"/v1"}function $J(J,Q={}){return{base:(J.baseURL??I("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=J.apiKey??I("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...J.headers}},timeoutMs:J.timeoutMs??Q.timeoutMs??120000,maxRetries:J.maxRetries??2}}function t$(J){let Q=J.baseURL??J.endpoint??I("AZURE_OPENAI_ENDPOINT");if(Q)return xQ(Q);let $=J.resourceName??I("AZURE_OPENAI_RESOURCE_NAME")??I("AZURE_RESOURCE_NAME");return $?xQ(`https://${$.trim()}.cognitiveservices.azure.com`):""}function ZJ(J,Q={}){let $=J.apiVersion??I("AZURE_OPENAI_API_VERSION")??s$;return{base:`${t$(J)}${a$($)}`,query:`?api-version=${encodeURIComponent($)}`,headers:async()=>{if(J.getToken)return{authorization:`Bearer ${await J.getToken()}`,...J.headers};let Z=J.apiKey??I("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...J.headers}},timeoutMs:J.timeoutMs??Q.timeoutMs??120000,maxRetries:J.maxRetries??2}}var r$=500,bQ=20000;function e$(J,Q){if(!J)return;let $=J.trim();if(/^\d+(\.\d+)?$/.test($))return Math.max(0,Number($)*1000);let Z=Date.parse($);if(Number.isNaN(Z))return;return Math.max(0,Z-Q)}function wQ(J,Q){let $=Math.min(bQ,r$*2**J);return Math.round($*(0.5+Q()*0.5))}function J3(J){return J===429||J===408||J===409||J>=500}function Q3(J,Q){return J3(J)&&R(Q).retryable}function vQ(J){return J.reason??new DOMException("The operation was aborted.","AbortError")}function $3(J,Q){return new Promise(($,Z)=>{let W=setTimeout($,J);Q?.addEventListener("abort",()=>{clearTimeout(W),Z(vQ(Q))},{once:!0})})}async function o(J,Q,$){let Z=$.fetchImpl??((H,B)=>fetch(H,B)),W=$.sleep??$3,G=$.random??Math.random,V=$.now??Date.now,K=Math.max(0,$.maxRetries),Y=async(H)=>{let B=$.signal;if(!B)return await W(H);B.throwIfAborted();let D;try{await Promise.race([W(H,B),new Promise((z,F)=>{D=()=>F(vQ(B)),B.addEventListener("abort",D,{once:!0})})])}finally{if(D)B.removeEventListener("abort",D)}},X;for(let H=0;H<=K;H++){$.signal?.throwIfAborted();let B=new AbortController,D=()=>B.abort($.signal?.reason);$.signal?.addEventListener("abort",D,{once:!0});let z=!1,F=$.timeoutMs>0?setTimeout(()=>{z=!0,B.abort()},$.timeoutMs):void 0,U;try{U=await Z(J,{...Q,signal:B.signal})}catch(O){if(F!==void 0)clearTimeout(F);if($.signal?.removeEventListener("abort",D),$.signal?.aborted)throw O;if(X=z?new IQ($.timeoutMs):O,z&&$.retryTimeouts===!1)throw X;if(H===K)throw X;await Y(wQ(H,G));continue}if(F!==void 0)clearTimeout(F);if(U.ok)return U;$.signal?.removeEventListener("abort",D);let N=await Z3(U),P=new h(U.status,N,U.headers.get("x-request-id")??void 0);if(H===K||!Q3(U.status,P))throw P;let _=e$(U.headers.get("retry-after"),V());await Y(_===void 0?wQ(H,G):Math.min(_,bQ)),X=P}throw X??Error("Provider request failed with no response.")}async function Z3(J){let Q;try{Q=await J.text()}catch{return null}try{return JSON.parse(Q)}catch{return Q}}var EJ=300000;function qJ(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 WJ extends Error{code;retryable;constructor(J,Q={}){super(J.message,Q);this.name="ImageRequestError",this.code=J.code,this.retryable=J.retryable}}var W3={png:"image/png",jpeg:"image/jpeg"};function G3(J){let Q=Number(J?.input_tokens??0),$=Number(J?.output_tokens??0),Z={inputTokens:Q,outputTokens:$,totalTokens:Number(J?.total_tokens??Q+$)},W=J?.input_tokens_details?.image_tokens;if(typeof W==="number")Z.imageInputTokens=W;let G=J?.output_tokens_details?.image_tokens;if(typeof G==="number")Z.imageOutputTokens=G;return Z}function V3(J){let Q=atob(J),$=new Uint8Array(Q.length);for(let Z=0;Z<Q.length;Z++)$[Z]=Q.charCodeAt(Z);return $}function K3(J){let $=J?.data?.[0]?.b64_json;if(typeof $!=="string"||$.length===0)throw new WJ({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:V3($),mimeType:W3[Z]??`image/${Z}`,size:typeof J.size==="string"?J.size:"",...typeof J.background==="string"?{background:J.background}:{},usage:G3(J.usage)}}async function fQ(J,Q,$,Z){let W;try{W=await o(J,Q,{maxRetries:$.maxRetries,timeoutMs:$.timeoutMs,retryTimeouts:!1,signal:Z.signal,fetchImpl:$.fetchImpl})}catch(G){if(Z.signal?.aborted)throw G;throw new WJ(R(G),{cause:G})}return K3(await W.json())}async function hQ(J,Q,$={}){return await fQ(J.generationsUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify(Q)},J,$)}async function yQ(J,Q,$={}){return await fQ(J.editsUrl,{method:"POST",headers:await J.headers(),body:Q},J,$)}class GJ{static models(){return[]}modelName(){return this.model}async generate(J){return await hQ(this.endpoint(),this.body(J),{signal:J.signal})}async edit(J){let Q=new FormData;for(let[$,Z]of Object.entries(this.body(J)))if(Z!==void 0)Q.set($,String(Z));for(let $ of J.images)Q.append("image[]",$,$.name);if(J.mask)Q.set("mask",J.mask,J.mask.name);return await yQ(this.endpoint(),Q,{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 R(J)}}var gQ=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class xJ extends GJ{model;config;constructor(J,Q={}){super();this.model=J,this.config=Q}static model(J,Q){return new xJ(J,Q)}static models(){return gQ}endpoint(){return qJ($J(this.config,{timeoutMs:EJ}))}}class wJ extends GJ{model;config;constructor(J,Q={}){super();this.model=J,this.config=Q}static model(J,Q){return new wJ(J,Q)}static models(){return gQ}modelName(){return this.config.deployment??this.model}endpoint(){return qJ(ZJ(this.config,{timeoutMs:EJ}))}}var mQ=3;function IJ(J){let Q=new Map;for(let $ of J)for(let Z of $.content??[]){if(Z.type!=="file"||!Z.fileId||Q.has(Z.fileId))continue;Q.set(Z.fileId,{name:Z.name,mimeType:Z.mimeType})}return Q}function pQ(J,Q,$=new Map){if(!(Q instanceof h))return[];if(Q.status!==400&&Q.status!==404)return[];let Z=Y3(Q.body);if(!Z)return[];let W=X3(J.input);if(W.length===0)return[];let G=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(G){let X=J.input[Number(G[1])],H=vJ(X)[Number(G[2])],B=H&&typeof H.file_id==="string"?H.file_id:void 0;if(B)return[B]}let V=Z.message??"",K=cQ(W.map((X)=>X.fileId).filter((X)=>H3(V,X)));if(K.length>0)return K;let Y=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(V);if(Y){let X=Y[1].toLowerCase()==="image type"?"input_image":"input_file",H=Y[2].toLowerCase(),B=cQ(W.filter((z)=>z.type===X).map((z)=>z.fileId)),D=B.filter((z)=>($.get(z)?.name??"").trim().toLowerCase().endsWith(`.${H}`));if(D.length===1)return D;if(D.length===0&&B.length===1)return B}return[]}function lQ(J,Q,$=new Map){return{...J,input:J.input.map((Z)=>{let W=vJ(Z);if(!W.some((G)=>uQ(G,Q)))return Z;return{...Z,content:W.map((G)=>uQ(G,Q)?{type:"input_text",text:bJ($.get(String(G.file_id))?.name)}:G)}})}}function bJ(J){return`[${J?`attachment ${JSON.stringify(J)}`:"an attachment"} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`}function uQ(J,Q){return typeof J.file_id==="string"&&Q.has(J.file_id)}function vJ(J){let Q=J?.content;return Array.isArray(Q)?Q:[]}function X3(J){let Q=[];for(let $ of J)for(let Z of vJ($))if(typeof Z.file_id==="string"&&Z.file_id)Q.push({type:String(Z.type),fileId:Z.file_id});return Q}function Y3(J){if(!J||typeof J!=="object")return null;let Q=J,$=Q.error&&typeof Q.error==="object"?Q.error:J;return{message:typeof $.message==="string"?$.message:void 0,param:typeof $.param==="string"?$.param:void 0}}function H3(J,Q){let $=Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${$}($|[^A-Za-z0-9_-])`).test(J)}function cQ(J){return[...new Set(J)]}async function*D3(J){let Q="",$="",Z=[],W,G=()=>{if(Z.length===0&&!$)return null;let Y={event:$,data:Z.join(`
|
|
76
|
-
`),id:W};return $="",Z=[],W=void 0,
|
|
77
|
-
`);while(
|
|
78
|
-
`)}}if(Q.length>0){let Y=V(Q);if(Y)yield Y}let K=G();if(K)yield K}async function*dQ(J,Q={}){let $=new Map,Z=new Set,W,G=!1,V,K=(Y,X)=>({type:"finish",reason:Y,usage:X,...V?{model:V}:{}});for await(let Y of D3(J)){if(Y.data==="[DONE]")break;let X;try{X=JSON.parse(Y.data)}catch{continue}let H=typeof X.type==="string"?X.type:Y.event,B=X.response?.model;if(typeof B==="string"&&B)V=B;switch(H){case"response.output_text.delta":{let D=String(X.delta??"");if(!D)break;yield Q.structuredOutput?{type:"output-delta",delta:D}:{type:"text-delta",delta:D};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let D=String(X.delta??"");if(!D)break;yield{type:"reasoning-delta",delta:D,id:X.item_id};break}case"response.output_item.added":{let D=X.item;if(!D)break;if(D.type==="function_call"){let z=String(D.id??X.item_id??D.call_id??"");$.set(z,{callId:String(D.call_id??z),name:String(D.name??""),namespace:typeof D.namespace==="string"&&D.namespace?D.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let D=$.get(String(X.item_id??""));if(!D)break;let z=String(X.delta??"");if(!z)break;yield{type:"tool-call-delta",toolCallId:D.callId,name:D.name,argsDelta:z,...D.namespace?{namespace:D.namespace}:{}};break}case"response.function_call_arguments.done":{let D=String(X.item_id??""),z=$.get(D);if(!z)break;z.done=!0,yield{type:"tool-call",toolCallId:z.callId,name:z.name,args:String(X.arguments??""),...z.namespace?{namespace:z.namespace}:{}};break}case"response.output_item.done":{let D=X.item;if(!D)break;if(D.type==="function_call"){let z=String(D.id??X.item_id??D.call_id??""),F=$.get(z);if(F?.done)break;let U=(typeof D.namespace==="string"?D.namespace:"")||F?.namespace;if(yield{type:"tool-call",toolCallId:String(D.call_id??z),name:String(D.name??F?.name??""),args:String(D.arguments??""),...U?{namespace:U}:{}},F)F.done=!0;break}if(D.type==="tool_search_call"||D.type==="tool_search_output"){if(D.type==="tool_search_call"&&D.arguments!==void 0)W=D.arguments;let z=z3(D);if(z.loaded.length===0&&z.namespaces.length===0)break;let F=String(D.tool_search_call_id??D.id??"");if(Z.has(F))break;Z.add(F);let U=W;W=void 0,yield{type:"tool-search",...z,...U!==void 0&&U!==null?{arguments:U}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(X.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{G=!0,yield K("stop",fJ(X.response?.usage));break}case"response.incomplete":{G=!0;let D=fJ(X.response?.usage),z=X.response?.incomplete_details?.reason;if(z==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:B3(X.response?.content_filters),retryable:!1}},yield K("error",D);break}yield K(z==="max_output_tokens"?"length":"stop",D);break}case"response.failed":case"error":{G=!0;let D=X.response?.error??X.error??X;yield{type:"error",error:U3(D)},yield K("error",fJ(X.response?.usage));break}}if(G)return}if(!G)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield K("error",y())}function z3(J){let Q=[],$=[];return iQ(J.results??J.tools??J.loaded??J.output,Q,$,0),{loaded:hJ(Q),namespaces:hJ($)}}function iQ(J,Q,$,Z){if(!Array.isArray(J)||Z>4)return;for(let W of J){if(typeof W==="string"){Q.push(W);continue}if(!W||typeof W!=="object")continue;let G=W,V=typeof G.name==="string"?G.name:typeof G.tool_name==="string"?G.tool_name:"",K=G.tools??G.functions;if(Array.isArray(K)){if(V)$.push(V);iQ(K,Q,$,Z+1);continue}if(V)Q.push(V)}}function hJ(J){return J.filter((Q,$)=>J.indexOf(Q)===$)}function B3(J){if(!Array.isArray(J))return"The provider's content filter blocked this request.";let $=[];for(let Z of J){if(!Z||typeof Z!=="object")continue;let W=Z,G=W.content_filter_results;if(!G||typeof G!=="object")continue;for(let[V,K]of Object.entries(G))if(K&&typeof K==="object"&&K.filtered===!0)$.push(`${V} (${String(W.source_type??"unknown")})`)}return $.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${hJ($).join(", ")}.`}function U3(J){let Q=typeof J?.message==="string"?J.message:"The provider stream failed.",$=String(J?.code??"").toLowerCase();if($==="rate_limit_exceeded")return{code:"rate_limited",message:Q,retryable:!0};if($==="context_length_exceeded")return{code:"context_length_exceeded",message:Q,retryable:!1};if($.includes("content_filter"))return{code:"content_filtered",message:Q,retryable:!1};return{code:"provider_error",message:Q,retryable:!0}}function y(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function fJ(J){if(!J)return y();let Q=Number(J.input_tokens??0),$=Number(J.output_tokens??0),Z={inputTokens:Q,outputTokens:$,totalTokens:Number(J.total_tokens??Q+$)},W=J.output_tokens_details?.reasoning_tokens;if(typeof W==="number")Z.reasoningTokens=W;let G=J.input_tokens_details?.cached_tokens;if(typeof G==="number")Z.cachedInputTokens=G;return Z}async function*nQ(J){if(!J)return;let Q=J.getReader(),$=new TextDecoder;try{while(!0){let{done:W,value:G}=await Q.read();if(W)break;if(G)yield $.decode(G,{stream:!0})}let Z=$.decode();if(Z)yield Z}finally{Q.releaseLock()}}function yJ(J){return{responsesUrl:`${J.base}/responses${J.query}`,filesUrl:`${J.base}/files${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,maxRetries:J.maxRetries}}async function*gJ(J,Q,$){let Z,W=Q,G=new Set;for(let V=0;Z===void 0;V++)try{Z=await o(J.responsesUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify(W)},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,signal:$.signal,fetchImpl:J.fetchImpl})}catch(K){let Y=V<mQ?pQ(W,K,$.files).filter((H)=>!G.has(H)):[];if(Y.length>0){let H=R(K).message;for(let B of Y)G.add(B),yield{type:"file-rejected",fileId:B,message:H,...g(K)};W=lQ(W,new Set(Y),$.files);continue}let X=R(K);if(X.code!=="aborted")yield{type:"error",error:X,...g(K)};yield{type:"finish",reason:X.code==="aborted"?"aborted":"error",usage:y()};return}try{yield*dQ(nQ(Z.body),{structuredOutput:$.structuredOutput})}catch(V){let K=R(V);if(K.code==="aborted"){yield{type:"finish",reason:"aborted",usage:y()};return}yield{type:"error",error:K},yield{type:"finish",reason:"error",usage:y()}}}async function uJ(J,Q,$="user_data"){let Z=new FormData;Z.set("purpose",$),Z.set("file",Q);let G=await(await o(J.filesUrl,{method:"POST",headers:await J.headers(),body:Z},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,fetchImpl:J.fetchImpl})).json();if(!G?.id)throw Error("The provider accepted the upload but returned no file id.");return G.id}function cJ(J){let Q=P3(J);if(Q.startsWith("gpt-3.5")||Q.startsWith("text-")||Q.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let $=F3(Q);if($?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:$.major>1,toolSearch:oQ($)};if($?.kind==="gpt")return{reasoning:$.major>=5,structuredOutput:$.major>4||Q.startsWith("gpt-4o")||Q.startsWith("gpt-4.1"),fileInput:$.major>4||Q.startsWith("gpt-4o")||Q.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:oQ($)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function oQ(J){if(J.kind==="o")return J.major>=5;return J.major>5||J.major===5&&J.minor>=2}function P3(J){return J.trim().toLowerCase()}function F3(J){let Q=/^gpt-(\d+)(?:\.(\d+))?/.exec(J);if(Q?.[1])return{kind:"gpt",major:Number(Q[1]),minor:Number(Q[2]??0)};let $=/^o(\d+)(?:[-.]|$)/.exec(J);if($?.[1])return{kind:"o",major:Number($[1]),minor:0};return null}function pJ(J,Q){let{capabilities:$}=Q,Z={model:Q.model,input:N3(J.messages,$,J.tools),stream:!0};if(J.systemPrompt)Z.instructions=J.systemPrompt;let W=j3(J.tools,$);if(W.length>0){if(Z.tools=W,!$.parallelToolCalls)Z.parallel_tool_calls=!1}if(J.output)Z.text={format:{type:"json_schema",name:J.output.name,schema:J.output.schema,strict:J.output.strict}};if(J.reasoning&&$.reasoning)Z.reasoning=J.reasoning==="none"?{effort:"none"}:{effort:J.reasoning,summary:"auto"};if(typeof J.temperature==="number")Z.temperature=J.temperature;if(typeof J.maxOutputTokens==="number")Z.max_output_tokens=J.maxOutputTokens;return Z}function N3(J,Q,$){let Z=[],W=new Map;if(Q.toolSearch){for(let G of $??[])if(VJ(G))W.set(G.name,G)}for(let G of J){let V=G.role,K=[],Y=()=>{if(K.length===0)return;Z.push({type:"message",role:V,content:K}),K=[]};for(let X of G.content??[])switch(X.type){case"text":{if(!X.text)break;K.push(u(V,X.text));break}case"output":{if(X.partial)break;K.push(u(V,JSON.stringify(X.value)));break}case"file":{if(V==="assistant")break;let H=O3(X);if(!Q.fileInput){if(H)K.push(u(V,mJ(X,!1)));break}if(X.fileId?.startsWith(b))throw Error(`FilePart.fileId holds a gemi attachment id (${X.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!X.fileId&&!H)throw Error("FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_\u2026`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.");if(X.providerRejected){if(H)K.push(u(V,mJ(X,!1)));K.push(u(V,bJ(X.name)));break}if(H)K.push(u(V,mJ(X,!!X.fileId)));if(X.fileId)K.push(_3(X));break}case"reasoning":{Y();let H=A3(X);if(H)Z.push(H);break}case"tool-call":{if(X.partial)break;if(Y(),Q.toolSearch&&Array.isArray(X.toolSearches))for(let B of X.toolSearches)Z.push(...T3(B,$??[]));let H={type:"function_call",call_id:X.toolCallId,name:String(X.name),arguments:JSON.stringify(X.input??{})};if(X.namespace&&W.has(X.namespace))H.namespace=X.namespace;Z.push(H);break}case"tool-result":{Y(),Z.push({type:"function_call_output",call_id:X.toolCallId,output:R3(X)});break}}Y()}return C3(Z)}var L3="No result was recorded for this tool call. Assume it did not complete.";function C3(J){let Q=new Set,$=new Set,Z=[];for(let G of J){if(G.type==="function_call"){let V=String(G.call_id);if(Q.has(V))continue;Q.add(V)}else if(G.type==="function_call_output"){let V=String(G.call_id);if(!Q.has(V)||$.has(V))continue;$.add(V)}Z.push(G)}if($.size===Q.size)return Z;let W=[];for(let G of Z){if(W.push(G),G.type!=="function_call")continue;let V=String(G.call_id);if($.has(V))continue;$.add(V),W.push({type:"function_call_output",call_id:V,output:L3})}return W}function u(J,Q){return{type:J==="assistant"?"output_text":"input_text",text:Q}}function O3(J){let Q=J.attachmentId;return typeof Q==="string"&&Q.startsWith(b)?Q:void 0}function mJ(J,Q){let $=[`id=${JSON.stringify(J.attachmentId)}`];if(J.name)$.push(`name=${JSON.stringify(J.name)}`);if(J.mimeType)$.push(`mimeType=${JSON.stringify(J.mimeType)}`);let Z=`attachment ${$.join(" ")}`;return Q?`[${Z}]`:`[${Z} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function _3(J){let Q=J.mimeType?.trim().toLowerCase()??"";return{type:(Q?Q.startsWith("image/")&&Q!=="image/svg+xml":S3(J.name))?"input_image":"input_file",file_id:J.fileId}}function S3(J){let Q=/\.([a-z0-9]+)$/.exec(J?.trim().toLowerCase()??"");return Q?.[1]!==void 0&&M3.has(Q[1])}var M3=new Set(["jpeg","jpg","png","gif","webp"]);function A3(J){if(!J.id)return null;let Q={type:"reasoning",id:J.id};return Q.summary=J.text?[{type:"summary_text",text:J.text}]:[],Q}function R3(J){if(J.status==="ok")return typeof J.output==="string"?J.output:JSON.stringify(J.output??null);if(J.status==="running"){let Q=J.job?.summary===void 0?"":` Started with: ${JSON.stringify(J.job.summary)}.`;return`Started background job ${J.job?.id??"(unknown)"}. It is still running, so there is no result yet: this message will be replaced by the result when it finishes. Do not start it again.${Q}`}if(J.status==="denied"){let Q=J.reason?` Reason given: ${J.reason}`:"";if(J.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${Q}`;if(J.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${Q}`;return`The user declined this tool call, so it did not run.${Q}`}return`The tool call failed and produced no result. Error (${J.error?.code??"unknown"}): ${J.error?.message??"no message"}`}function T3(J,Q){let $=new Set(sQ(J?.loaded)),Z=sQ(J?.namespaces),W=new Set(Z),G=[];for(let K of Q)if(VJ(K)){if(!W.has(K.name))continue;let Y=K.tools.filter((X)=>$.size===0||$.has(X.name));if(Y.length===0)continue;G.push({type:"namespace",name:K.name,description:K.description,tools:Y.map((X)=>c(X,!0))})}else if(K.deferred&&$.has(K.name))G.push(c(K,!0));if(G.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:J.arguments&&typeof J.arguments==="object"?J.arguments:{paths:Z.length>0?Z:[...$]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:G}]}function sQ(J){return Array.isArray(J)?J.filter((Q)=>typeof Q==="string"):[]}function VJ(J){return Array.isArray(J.tools)}function j3(J,Q){if(!J||J.length===0)return[];if(!Q.toolSearch){let W=[];for(let G of J)if(VJ(G))for(let V of G.tools)W.push(c(V,!1));else W.push(c(G,!1));return W}let $=[],Z=!1;for(let W of J)if(VJ(W)){let G=W.tools.map((V)=>{if(V.deferred)Z=!0;return c(V,!0)});$.push({type:"namespace",name:W.name,description:W.description,tools:G})}else{if(W.deferred)Z=!0;$.push(c(W,!0))}if(Z)$.push({type:"tool_search"});return $}function c(J,Q){let $={type:"function",name:J.name,description:J.description,parameters:J.parameters,strict:J.strict};if(Q&&J.deferred)$.defer_loading=!0;return $}class m{static models(){return[]}normalizeError(J){return R(J)}}var aQ=["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.4-nano","gpt-5.2","gpt-5.1","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini","o4-mini","o3","o3-mini"];class lJ extends m{model;capabilities;config;constructor(J,Q={}){super();this.model=J,this.capabilities=cJ(J),this.config=Q}static model(J,Q){return new lJ(J,Q)}static models(){return aQ}stream(J){let Q=pJ(J,{model:this.model,capabilities:this.capabilities});return gJ(this.endpoint(),Q,{signal:J.signal,structuredOutput:Boolean(J.output),files:IJ(J.messages)})}upload(J){return uJ(this.endpoint(),J)}endpoint(){return yJ($J(this.config))}}class dJ extends m{model;capabilities;config;constructor(J,Q={}){super();this.model=J,this.capabilities=cJ(J),this.config=Q}static model(J,Q){return new dJ(J,Q)}static models(){return aQ}stream(J){let Q=pJ(J,{model:this.deployment(),capabilities:this.capabilities});return gJ(this.endpoint(),Q,{signal:J.signal,structuredOutput:Boolean(J.output),files:IJ(J.messages)})}upload(J){return uJ(this.endpoint(),J,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return yJ(ZJ(this.config))}}class KJ{now;entries=new Map;constructor(J=Date.now){this.now=J}allow(J,Q){let $=this.entries.get(J);if($?.openUntil===void 0)return!0;let Z=this.now();if(Z<$.openUntil)return!1;if($.probeUntil!==void 0&&Z<$.probeUntil)return!1;return $.probeUntil=Z+Q.cooldownMs,!0}record(J,Q,$){let Z=this.entries.get(J)??{failures:0},W=Z.openUntil!==void 0;if(Q==="success")return this.entries.delete(J),W?"closed":void 0;if(Q==="none"){delete Z.probeUntil;return}if(Z.failures+=1,this.entries.set(J,Z),W||Z.failures>=$.failures)return Z.openUntil=this.now()+$.cooldownMs,delete Z.probeUntil,W?void 0:"open";return}state(J){let Q=this.entries.get(J);if(Q?.openUntil===void 0)return"closed";return this.now()<Q.openUntil?"open":"half-open"}}function k3(J){switch(J.type){case"text-delta":case"reasoning-delta":case"tool-call-delta":case"tool-call":case"tool-search":case"output-delta":return!0;default:return!1}}var tQ=Symbol("timed-out");class s extends m{model;capabilities;entries;options;circuit;constructor(J,Q={}){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($){let Z=$.failures??3,W=$.cooldownMs??30000;if(!Number.isInteger(Z)||Z<1)throw Error(`FallbackProvider: circuit.failures must be a positive integer, got ${Z}.`);if(!(W>0))throw Error(`FallbackProvider: circuit.cooldownMs must be a positive number, got ${W}.`);let G=new Set;for(let K of J){let Y=iJ(K);if(G.has(Y))throw Error(`FallbackProvider: two legs share the circuit key "${Y}". Give one of them a \`circuitKey\`.`);G.add(Y)}let V=$.store??new KJ;this.options={...Q,circuit:{...$,store:V}},this.circuit={policy:{failures:Z,cooldownMs:W},store:V,...$.onStateChange?{onStateChange:$.onStateChange}:{}}}else this.options=Q,this.circuit=void 0;this.model=J[0].provider.model,this.capabilities=E3(J.map((Z)=>Z.provider.capabilities))}static chain(J,Q){return new s(J,Q)}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 s(this.entries.slice(J),this.options)}leg(J){let Q=this.from(J).entries[0];return new s([Q],this.options)}upload(J){return this.entries[0].provider.upload(J)}normalizeError(J){return this.entries[0].provider.normalizeError(J)}stream(J){return this.run(J)}async*run(J){let Q,$=J.signal,Z=0;for(let W=0;W<this.entries.length;W++){let G=this.entries[W],V=W===this.entries.length-1,K=G.provider.model;if(this.circuit&&!V&&!await this.allow(G))continue;Z+=1;let Y=!1,X=async(C)=>{if(Y)return;Y=!0,await this.record(W,G,C)},H=new AbortController,B=()=>H.abort($?.reason);if($?.aborted)H.abort($.reason);else $?.addEventListener("abort",B,{once:!0});let D=[],z=!1,F=!1,U,N,P,_=!1,O,M=!1,T=(C)=>{let A=Q?p(p(q(),Q),C.usage):C.usage;return Q=void 0,{...C,usage:A}};try{O=G.provider.stream({...J,...G.reasoning!==void 0?{reasoning:G.reasoning}:{},signal:H.signal})[Symbol.asyncIterator]();let C=!0;for(;;){let A=C&&G.timeoutMs!==void 0?await q3(O.next(),G.timeoutMs):await O.next();if(A===tQ){_=!0,P={error:{code:"provider_error",message:`${K} sent nothing within ${G.timeoutMs}ms.`,retryable:!0}};break}if(C=!1,A.done){M=!0;break}let L=A.value;if(L.type==="finish"&&L.model)N=L.model;if(z){if(L.type==="finish")U=p(U??q(),L.usage),F=!0,yield T(L);else{if(L.type==="error")P={error:L.error};yield L}continue}if(k3(L)){z=!0,await X("success"),yield*D.splice(0),yield L;continue}if(L.type==="error")P={error:L.error,...L.status!==void 0?{status:L.status}:{},...L.requestId!==void 0?{requestId:L.requestId}:{}};else if(L.type==="finish"){if(U=p(U??q(),L.usage),L.reason==="error"&&!P)P={error:{code:"provider_error",message:`${K} ended the call with an error and did not say which.`,retryable:!1}}}D.push(L)}}catch(C){let A=G.provider.normalizeError(C);if(z){if(A.code!=="aborted")yield{type:"error",error:A,...g(C)};this.report({index:W,model:K,responseModel:N,attempt:Z,usage:U,outcome:nJ(A),error:A}),yield T({type:"finish",reason:A.code==="aborted"?"aborted":"error",usage:q(),...N?{model:N}:{}});return}P={error:A,...g(C)}}finally{if($?.removeEventListener("abort",B),!M)H.abort(),O?.return?.()?.catch(()=>{})}if(z){if(!F&&Q)yield{type:"finish",reason:P?"error":"stop",usage:Q},Q=void 0;this.report({index:W,model:K,responseModel:N,attempt:Z,usage:U,outcome:P?nJ(P.error):"ok",...P?{error:P.error}:{}});return}if($?.aborted){await X("none"),this.report({index:W,model:K,responseModel:N,attempt:Z,usage:U,outcome:"aborted"}),yield T({type:"finish",reason:"aborted",usage:U??q(),...N?{model:N}:{}});return}if(!P){await X("success"),this.report({index:W,model:K,responseModel:N,attempt:Z,usage:U,outcome:"ok"});for(let C of D)yield C.type==="finish"?T(C):C;return}let k=!V&&P.error.code!=="aborted"&&this.shouldFallBack(P.error,{index:W,model:K,timedOut:_,...P.status!==void 0?{status:P.status}:{},...P.requestId!==void 0?{requestId:P.requestId}:{}});if(await X(k?"failure":"none"),this.report({index:W,model:K,responseModel:N,attempt:Z,usage:U,outcome:k?"fallback":nJ(P.error),error:P.error}),k){if(U)Q=p(Q??q(),U);continue}let x=!1,E;for(let C of D){if(C.type==="finish"){E=C;continue}if(C.type==="error")x=!0;yield C}if(!x&&P.error.code!=="aborted")yield{type:"error",error:P.error,...P.status!==void 0?{status:P.status}:{},...P.requestId!==void 0?{requestId:P.requestId}:{}};yield T({type:"finish",reason:P.error.code==="aborted"?"aborted":E?.reason??"error",usage:U??q(),...N?{model:N}:{}});return}}async allow(J){if(!this.circuit)return!0;try{return await this.circuit.store.allow(iJ(J),this.circuit.policy)}catch{return!0}}async record(J,Q,$){if(!this.circuit)return;let Z=iJ(Q),W;try{W=await this.circuit.store.record(Z,$,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:J,model:Q.provider.model,key:Z,state:W})}catch{}}shouldFallBack(J,Q){let $=this.options.fallbackOn??((Z)=>Z.retryable);try{return $(J,Q)}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 iJ(J){return J.circuitKey??J.provider.model}function nJ(J){return J.code==="aborted"?"aborted":"failed"}function E3(J){return{reasoning:J.every((Q)=>Q.reasoning),structuredOutput:J.every((Q)=>Q.structuredOutput),fileInput:J.every((Q)=>Q.fileInput),parallelToolCalls:J.every((Q)=>Q.parallelToolCalls),toolSearch:J.every((Q)=>Q.toolSearch)}}function q3(J,Q){let $,Z=new Promise((W)=>{$=setTimeout(()=>W(tQ),Q)});return Promise.race([J,Z]).finally(()=>clearTimeout($))}async function x3(J,Q,$={}){let Z=$.samples??1;if(!Number.isInteger(Z)||Z<1)throw RangeError(`evalChain: samples must be a positive integer, got ${Z}.`);let W=[];for(let G=0;G<J.entries.length;G++){let V=J.leg(G),K={index:G,model:V.model,results:[],errors:[]};for(let Y=0;Y<Z;Y++)try{K.results.push(await Q(V,{index:G,sample:Y}))}catch(X){K.errors.push({sample:Y,error:X})}W.push(K)}return W}class l extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(J,Q,$){super(`Frame ${Q} of run ${J} has been evicted; the oldest frame still buffered is ${$}. Reload the thread instead of resuming.`);this.runId=J;this.requested=Q;this.oldest=$}}class a extends Error{runId;code="live_run_not_found";constructor(J){super(`No live run ${J} in this process.`);this.runId=J}}class XJ{ttlMs;maxFrames;maxAgeMs;runs=new Map;byThread=new Map;byClientRun=new Map;constructor(J={}){this.ttlMs=J.ttlMs??60000,this.maxFrames=J.maxFrames??4096,this.maxAgeMs=J.maxAgeMs===void 0?3600000:J.maxAgeMs}register(J,Q={}){let $={run:J,threadId:Q.threadId,owner:Q.owner??null,clientRunId:Q.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(Q.threadId,J.runId);if(Q.clientRunId)this.byClientRun.set(Q.clientRunId,J.runId);return this.scheduleExpiry($,Q.maxRunDurationMs),this.pump($,Q)}findByClientRunId(J){let Q=this.byClientRun.get(J);return Q&&this.runs.has(Q)?Q:null}async find(J){let Q=this.byThread.get(J.threadId);if(!Q)return null;let $=this.runs.get(Q);if(!$)return null;return{runId:Q,seq:$.lastSeq}}get(J){return this.runs.get(J)?.run??null}ownerOf(J){return this.runs.get(J)?.owner??null}mayAccess(J,Q){let $=this.ownerOf(J);return $===null||$===Q}isRunning(J){let Q=this.runs.get(J);return!!Q&&!Q.ended&&!Q.evicted}replay(J,Q){let $=this.runs.get(J);if(!$)throw new a(J);if(Q!==void 0&&Q<$.lostBefore)throw new l(J,Q,$.lostBefore);let Z=$.frames[0]?.seq;return this.drain($,J,Q??Z??$.lastSeq+1)}clear(){for(let J of this.runs.values()){if(J.evictAt)clearTimeout(J.evictAt);if(J.expireAt)clearTimeout(J.expireAt);J.ended=!0,this.notify(J)}this.runs.clear(),this.byThread.clear(),this.byClientRun.clear()}get size(){return this.runs.size}async pump(J,Q){let $=Promise.resolve();try{for await(let Z of J.run.frames()){if(J.evicted){let G=Q.onEvent;if(G)$=$.then(()=>G(Z.event)).catch((V)=>oJ(Q,V));continue}if(J.frames.push(Z),J.lastSeq=Z.seq,J.frames.length>this.maxFrames){let G=J.frames.shift();if(G)J.lostBefore=G.seq+1}this.notify(J);let W=Q.onEvent;if(W)$=$.then(()=>W(Z.event)).catch((G)=>oJ(Q,G))}}catch(Z){oJ(Q,Z)}finally{if(J.ended=!0,J.expireAt)clearTimeout(J.expireAt),J.expireAt=null;this.notify(J),this.scheduleEviction(J),await $}}async*drain(J,Q,$){let Z=$;while(!0){let W=J.version;for(;;){if(Z<J.lostBefore)throw new l(Q,Z,J.lostBefore);let G=J.frames,V=G[0]?.seq;if(V===void 0)break;let K=Math.max(0,Z-V);if(K>=G.length)break;let Y=G[K];yield Y,Z=Y.seq+1}if(J.ended&&Z>J.lastSeq||J.evicted)return;await this.wait(J,W)}}wait(J,Q){if(J.version!==Q)return Promise.resolve();return new Promise(($)=>J.wake.add($))}notify(J){J.version++;let Q=Array.from(J.wake);J.wake.clear();for(let $ of Q)$()}scheduleEviction(J){if(J.evictAt)return;let Q=setTimeout(()=>{let $=J.run.runId;if(!J.ended)J.evicted=!0,J.frames=[];if(this.runs.get($)===J)this.runs.delete($);if(J.threadId&&this.byThread.get(J.threadId)===$)this.byThread.delete(J.threadId);if(J.clientRunId&&this.byClientRun.get(J.clientRunId)===$)this.byClientRun.delete(J.clientRunId);this.notify(J)},this.ttlMs);Q.unref?.(),J.evictAt=Q}scheduleExpiry(J,Q){if(this.maxAgeMs===null||Q===null)return;let $=Q===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,Q+this.ttlMs);if(!Number.isFinite($)||$>2147483647)return;let Z=setTimeout(()=>{if(J.expireAt=null,J.ended)return;try{J.run.stop({reason:`The run was still going ${Math.round($/1000)}s after it started, past the live-run registry's age limit.`})}catch{}this.scheduleEviction(J)},$);Z.unref?.(),J.expireAt=Z}}var sJ=new XJ;function oJ(J,Q){try{J.onInternalError?.(Q)}catch{}}class YJ{maxEntries;records=new Map;constructor(J=1e5){this.maxEntries=J}async record(J,Q){if(this.records.has(J))return;this.records.set(J,{...Q});while(this.records.size>this.maxEntries){let $=this.records.keys().next().value;if($===void 0)break;this.records.delete($)}}async get(J){let Q=this.records.get(J);return Q?{...Q}:null}}var aJ=new YJ;class eJ{now;receipts=new Map;sweepAt=1024;constructor(J=Date.now){this.now=J}async claim(J,Q){let $=this.now();if(this.receipts.size>=this.sweepAt)this.sweep($);let Z=this.receipts.get(J);if(Z&&Z.expiresAt>$)return Z.result?{status:"replay",result:structuredClone(Z.result)}:{status:"blocked"};return this.receipts.set(J,{expiresAt:Q}),{status:"claimed"}}async complete(J,Q,$){this.receipts.set(J,{result:structuredClone(Q),expiresAt:$})}async release(J){let Q=this.receipts.get(J);if(Q&&!Q.result)this.receipts.delete(J)}get size(){return this.receipts.size}sweep(J){for(let[Q,$]of this.receipts)if($.expiresAt<=J)this.receipts.delete(Q);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var rQ="pending",tJ="done:",w3=`
|
|
75
|
+
)`,`CREATE INDEX IF NOT EXISTS "${Q}_thread_id_created_at_idx" ON "${Q}"("thread_id", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Q}_state_deadline_at_idx" ON "${Q}"("state", "deadline_at")`]}var F6=/^[A-Za-z0-9_-]{1,64}$/;function U6(J,Q){let $=N6(Q)?Q:{filter:Q},Z=$.deferred===!0,W=J.descriptors($.filter);if(!$.namespaces)return W.map((H)=>gJ(J,H,Z));let G=Object.entries($.namespaces),K=new Set(J.descriptors().flatMap((H)=>H.tags));for(let[H,D]of G){if(!F6.test(H))throw Error(`toAgentTools: "${H}" is not a valid namespace name. A namespace is named by its tag and sent to the provider as a tool name is \u2014 letters, digits, "_" and "-", at most 64.`);if(typeof D?.description!=="string"||D.description.trim()==="")throw Error(`toAgentTools: the namespace "${H}" needs a description. It is what the model reads to decide whether to look inside.`);if(!K.has(H))throw Error(`toAgentTools: no tool is tagged "${H}", so its namespace would be empty.`)}let X=new Map(G.map(([H])=>[H,[]])),V=[];for(let H of W){let D=G.find(([z])=>H.tags.includes(z))?.[0];if(D===void 0)V.push(gJ(J,H,Z));else X.get(D).push(gJ(J,H,!1))}let Y=[];for(let[H,D]of G){let z=X.get(H);if(z.length===0)continue;Y.push(uJ.create({name:H,description:D.description,tools:z,deferred:D.deferred??Z}))}return[...Y,...V]}function N6(J){return typeof J==="object"&&J!==null&&(("filter"in J)||("namespaces"in J)||("deferred"in J))}function gJ(J,Q,$){if(Q.kind==="tool")return O6(J,Q,$);return DJ.create({name:Q.name,description:Q.description,inputSchema:Q.inputSchema,...Q.outputSchema?{outputSchema:Q.outputSchema}:{},requiresApproval:Q.requiresApproval,deferred:$,execute:(Z,W)=>{let G=h.getStore()?.req;if(!G)throw new y(`"${Q.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:G},Q.name,Z,W)}})}function O6(J,Q,$){let Z=J.nativeTool(Q.name);return DJ.create({name:Q.name,description:Q.description,inputSchema:Q.inputSchema,...Q.outputSchema?{outputSchema:Q.outputSchema}:{},requiresApproval:Q.requiresApproval,deferred:$,...Z.timeoutMs!==void 0?{timeoutMs:Z.timeoutMs}:{},...Z.async?{async:Z.async}:{},execute:(W,G)=>{let K=h.getStore()?.req;return J.startNative(K?{kind:"local",req:K}:void 0,Q.name,W,G)}})}function L6(J){if(J==="auto")return;let Q=/^(\d+)x(\d+)$/.exec(J);if(!Q)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(J)}.`);let $=Number(Q[1]),Z=Number(Q[2]);if($%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($/Z,Z/$)>3)throw Error(`Image size ${J} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function dQ(J,Q){if(J.size!==void 0)try{L6(J.size)}catch($){throw Error(`${Q}: ${$.message}`)}if(J.background==="transparent"&&J.format==="jpeg")throw Error(`${Q}: a transparent background needs "png"; JPEG has no alpha channel.`);if(J.compression!==void 0){let $=J.compression;if(!Number.isInteger($)||$<0||$>100)throw Error(`${Q}: compression is an integer from 0 to 100; got ${$}.`)}}function iQ(J,Q){if(J instanceof File)return J;let $=J.type||"image/png",Z=$==="image/jpeg"?"jpg":$.split("/")[1]??"png";return new File([J],`${Q}.${Z}`,{type:$})}class cJ{name;provider;settings;constructor(J){let{name:Q,provider:$,...Z}=J;dQ(Z,`ImageModel "${Q}"`),this.name=Q,this.provider=$,this.settings=Z}static create(J){return new cJ(J)}async generate(J){let Q=this.merge(J);return nQ(await this.provider.generate({prompt:J.prompt,...Q,signal:J.signal}))}async edit(J){let Q=this.merge(J);return nQ(await this.provider.edit({prompt:J.prompt,...Q,images:J.images.map(($,Z)=>iQ($,`image-${Z}`)),...J.mask?{mask:iQ(J.mask,"mask")}:{},signal:J.signal}))}merge(J){let Q={...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 dQ(Q,`ImageModel "${this.name}"`),Q}}function nQ(J){return{image:new Blob([J.bytes],{type:J.mimeType}),mimeType:J.mimeType,size:J.size,usage:J.usage}}function g(J){return typeof process>"u"?void 0:process.env?.[J]}var C6="preview";function oQ(J){let Q=J.trim().replace(/\/+$/,"");if(!Q)return"";return`${Q.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function _6(J){return/^\d{4}-\d{2}-\d{2}/.test(J)?"":"/v1"}function e(J,Q={}){return{base:(J.baseURL??g("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=J.apiKey??g("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...J.headers}},timeoutMs:J.timeoutMs??Q.timeoutMs??120000,maxRetries:J.maxRetries??2}}function aQ(J){let Q=J.baseURL??J.endpoint??g("AZURE_OPENAI_ENDPOINT");if(Q)return oQ(Q);let $=J.resourceName??g("AZURE_OPENAI_RESOURCE_NAME")??g("AZURE_RESOURCE_NAME");return $?oQ(`https://${$.trim()}.cognitiveservices.azure.com`):""}function JJ(J,Q={}){let $=J.apiVersion??g("AZURE_OPENAI_API_VERSION")??C6;return{base:`${aQ(J)}${_6($)}`,query:`?api-version=${encodeURIComponent($)}`,headers:async()=>{if(J.getToken)return{authorization:`Bearer ${await J.getToken()}`,...J.headers};let Z=J.apiKey??g("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...J.headers}},timeoutMs:J.timeoutMs??Q.timeoutMs??120000,maxRetries:J.maxRetries??2}}function sQ(J,Q={}){return{...JJ(J,Q),base:`${aQ(J)}/v1`,query:""}}var S6=500,eQ=20000;function M6(J,Q){if(!J)return;let $=J.trim();if(/^\d+(\.\d+)?$/.test($))return Math.max(0,Number($)*1000);let Z=Date.parse($);if(Number.isNaN(Z))return;return Math.max(0,Z-Q)}function tQ(J,Q){let $=Math.min(eQ,S6*2**J);return Math.round($*(0.5+Q()*0.5))}function A6(J){return J===429||J===408||J===409||J>=500}function k6(J,Q){return A6(J)&&k(Q).retryable}function J$(J){return J.reason??new DOMException("The operation was aborted.","AbortError")}function R6(J,Q){return new Promise(($,Z)=>{let W=setTimeout($,J);Q?.addEventListener("abort",()=>{clearTimeout(W),Z(J$(Q))},{once:!0})})}async function u(J,Q,$){let Z=$.fetchImpl??((H,D)=>fetch(H,D)),W=$.sleep??R6,G=$.random??Math.random,K=$.now??Date.now,X=Math.max(0,$.maxRetries),V=async(H)=>{let D=$.signal;if(!D)return await W(H);D.throwIfAborted();let z;try{await Promise.race([W(H,D),new Promise((B,U)=>{z=()=>U(J$(D)),D.addEventListener("abort",z,{once:!0})})])}finally{if(z)D.removeEventListener("abort",z)}},Y;for(let H=0;H<=X;H++){$.signal?.throwIfAborted();let D=new AbortController,z=()=>D.abort($.signal?.reason);$.signal?.addEventListener("abort",z,{once:!0});let B=!1,U=$.timeoutMs>0?setTimeout(()=>{B=!0,D.abort()},$.timeoutMs):void 0,P;try{P=await Z(J,{...Q,signal:D.signal})}catch(L){if(U!==void 0)clearTimeout(U);if($.signal?.removeEventListener("abort",z),$.signal?.aborted)throw L;if(Y=B?new rQ($.timeoutMs):L,B&&$.retryTimeouts===!1)throw Y;if(H===X)throw Y;await V(tQ(H,G));continue}if(U!==void 0)clearTimeout(U);if(P.ok)return P;$.signal?.removeEventListener("abort",z);let N=await T6(P),F=new I(P.status,N,P.headers.get("x-request-id")??void 0);if(H===X||!k6(P.status,F))throw F;let O=M6(P.headers.get("retry-after"),K());await V(O===void 0?tQ(H,G):Math.min(O,eQ)),Y=F}throw Y??Error("Provider request failed with no response.")}async function T6(J){let Q;try{Q=await J.text()}catch{return null}try{return JSON.parse(Q)}catch{return Q}}var mJ=300000;function pJ(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 BJ extends Error{code;retryable;constructor(J,Q={}){super(J.message,Q);this.name="ImageRequestError",this.code=J.code,this.retryable=J.retryable}}var j6={png:"image/png",jpeg:"image/jpeg"};function q6(J){let Q=Number(J?.input_tokens??0),$=Number(J?.output_tokens??0),Z={inputTokens:Q,outputTokens:$,totalTokens:Number(J?.total_tokens??Q+$)},W=J?.input_tokens_details?.image_tokens;if(typeof W==="number")Z.imageInputTokens=W;let G=J?.output_tokens_details?.image_tokens;if(typeof G==="number")Z.imageOutputTokens=G;return Z}function E6(J){let Q=atob(J),$=new Uint8Array(Q.length);for(let Z=0;Z<Q.length;Z++)$[Z]=Q.charCodeAt(Z);return $}function x6(J){let $=J?.data?.[0]?.b64_json;if(typeof $!=="string"||$.length===0)throw new BJ({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:E6($),mimeType:j6[Z]??`image/${Z}`,size:typeof J.size==="string"?J.size:"",...typeof J.background==="string"?{background:J.background}:{},usage:q6(J.usage)}}async function Q$(J,Q,$,Z){let W;try{W=await u(J,Q,{maxRetries:$.maxRetries,timeoutMs:$.timeoutMs,retryTimeouts:!1,signal:Z.signal,fetchImpl:$.fetchImpl})}catch(G){if(Z.signal?.aborted)throw G;throw new BJ(k(G),{cause:G})}return x6(await W.json())}async function $$(J,Q,$={}){return await Q$(J.generationsUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify(Q)},J,$)}async function Z$(J,Q,$={}){return await Q$(J.editsUrl,{method:"POST",headers:await J.headers(),body:Q},J,$)}class PJ{static models(){return[]}modelName(){return this.model}async generate(J){return await $$(this.endpoint(),this.body(J),{signal:J.signal})}async edit(J){let Q=new FormData;for(let[$,Z]of Object.entries(this.body(J)))if(Z!==void 0)Q.set($,String(Z));for(let $ of J.images)Q.append("image[]",$,$.name);if(J.mask)Q.set("mask",J.mask,J.mask.name);return await Z$(this.endpoint(),Q,{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 k(J)}}var W$=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class lJ extends PJ{model;config;constructor(J,Q={}){super();this.model=J,this.config=Q}static model(J,Q){return new lJ(J,Q)}static models(){return W$}endpoint(){return pJ(e(this.config,{timeoutMs:mJ}))}}class dJ extends PJ{model;config;constructor(J,Q={}){super();this.model=J,this.config=Q}static model(J,Q){return new dJ(J,Q)}static models(){return W$}modelName(){return this.config.deployment??this.model}endpoint(){return pJ(JJ(this.config,{timeoutMs:mJ}))}}var X$=3;function iJ(J){let Q=new Map;for(let $ of J)for(let Z of $.content??[]){if(Z.type!=="file"||!Z.fileId||Q.has(Z.fileId))continue;Q.set(Z.fileId,{name:Z.name,mimeType:Z.mimeType})}return Q}function Y$(J,Q,$=new Map){if(!(Q instanceof I))return[];if(Q.status!==400&&Q.status!==404)return[];let Z=I6(Q.body);if(!Z)return[];let W=w6(J.input);if(W.length===0)return[];let G=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(G){let Y=J.input[Number(G[1])],H=oJ(Y)[Number(G[2])],D=H&&typeof H.file_id==="string"?H.file_id:void 0;if(D)return[D]}let K=Z.message??"",X=K$(W.map((Y)=>Y.fileId).filter((Y)=>b6(K,Y)));if(X.length>0)return X;let V=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(K);if(V){let Y=V[1].toLowerCase()==="image type"?"input_image":"input_file",H=V[2].toLowerCase(),D=K$(W.filter((B)=>B.type===Y).map((B)=>B.fileId)),z=D.filter((B)=>($.get(B)?.name??"").trim().toLowerCase().endsWith(`.${H}`));if(z.length===1)return z;if(z.length===0&&D.length===1)return D}return[]}function V$(J,Q,$=new Map){return{...J,input:J.input.map((Z)=>{let W=oJ(Z);if(!W.some((G)=>G$(G,Q)))return Z;return{...Z,content:W.map((G)=>G$(G,Q)?{type:"input_text",text:nJ($.get(String(G.file_id))?.name)}:G)}})}}function nJ(J){return`[${J?`attachment ${JSON.stringify(J)}`:"an attachment"} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`}function G$(J,Q){return typeof J.file_id==="string"&&Q.has(J.file_id)}function oJ(J){let Q=J?.content;return Array.isArray(Q)?Q:[]}function w6(J){let Q=[];for(let $ of J)for(let Z of oJ($))if(typeof Z.file_id==="string"&&Z.file_id)Q.push({type:String(Z.type),fileId:Z.file_id});return Q}function I6(J){if(!J||typeof J!=="object")return null;let Q=J,$=Q.error&&typeof Q.error==="object"?Q.error:J;return{message:typeof $.message==="string"?$.message:void 0,param:typeof $.param==="string"?$.param:void 0}}function b6(J,Q){let $=Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${$}($|[^A-Za-z0-9_-])`).test(J)}function K$(J){return[...new Set(J)]}async function*f6(J){let Q="",$="",Z=[],W,G=()=>{if(Z.length===0&&!$)return null;let V={event:$,data:Z.join(`
|
|
76
|
+
`),id:W};return $="",Z=[],W=void 0,V.data?V:null},K=(V)=>{let Y=V.endsWith("\r")?V.slice(0,-1):V;if(Y==="")return G();if(Y.startsWith(":"))return null;let H=Y.indexOf(":"),D=H===-1?Y:Y.slice(0,H),z=H===-1?"":Y.slice(H+1);if(z.startsWith(" "))z=z.slice(1);if(D==="event")$=z;else if(D==="data")Z.push(z);else if(D==="id")W=z;return null};for await(let V of J){Q+=V;let Y=Q.indexOf(`
|
|
77
|
+
`);while(Y!==-1){let H=Q.slice(0,Y);Q=Q.slice(Y+1);let D=K(H);if(D)yield D;Y=Q.indexOf(`
|
|
78
|
+
`)}}if(Q.length>0){let V=K(Q);if(V)yield V}let X=G();if(X)yield X}async function*H$(J,Q={}){let $=new Map,Z=new Set,W,G=!1,K,X=(V,Y)=>({type:"finish",reason:V,usage:Y,...K?{model:K}:{}});for await(let V of f6(J)){if(V.data==="[DONE]")break;let Y;try{Y=JSON.parse(V.data)}catch{continue}let H=typeof Y.type==="string"?Y.type:V.event,D=Y.response?.model;if(typeof D==="string"&&D)K=D;switch(H){case"response.output_text.delta":{let z=String(Y.delta??"");if(!z)break;yield Q.structuredOutput?{type:"output-delta",delta:z}:{type:"text-delta",delta:z};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let z=String(Y.delta??"");if(!z)break;yield{type:"reasoning-delta",delta:z,id:Y.item_id};break}case"response.output_item.added":{let z=Y.item;if(!z)break;if(z.type==="function_call"){let B=String(z.id??Y.item_id??z.call_id??"");$.set(B,{callId:String(z.call_id??B),name:String(z.name??""),namespace:typeof z.namespace==="string"&&z.namespace?z.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let z=$.get(String(Y.item_id??""));if(!z)break;let B=String(Y.delta??"");if(!B)break;yield{type:"tool-call-delta",toolCallId:z.callId,name:z.name,argsDelta:B,...z.namespace?{namespace:z.namespace}:{}};break}case"response.function_call_arguments.done":{let z=String(Y.item_id??""),B=$.get(z);if(!B)break;B.done=!0,yield{type:"tool-call",toolCallId:B.callId,name:B.name,args:String(Y.arguments??""),...B.namespace?{namespace:B.namespace}:{}};break}case"response.output_item.done":{let z=Y.item;if(!z)break;if(z.type==="function_call"){let B=String(z.id??Y.item_id??z.call_id??""),U=$.get(B);if(U?.done)break;let P=(typeof z.namespace==="string"?z.namespace:"")||U?.namespace;if(yield{type:"tool-call",toolCallId:String(z.call_id??B),name:String(z.name??U?.name??""),args:String(z.arguments??""),...P?{namespace:P}:{}},U)U.done=!0;break}if(z.type==="tool_search_call"||z.type==="tool_search_output"){if(z.type==="tool_search_call"&&z.arguments!==void 0)W=z.arguments;let B=v6(z);if(B.loaded.length===0&&B.namespaces.length===0)break;let U=String(z.tool_search_call_id??z.id??"");if(Z.has(U))break;Z.add(U);let P=W;W=void 0,yield{type:"tool-search",...B,...P!==void 0&&P!==null?{arguments:P}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(Y.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{G=!0,yield X("stop",aJ(Y.response?.usage));break}case"response.incomplete":{G=!0;let z=aJ(Y.response?.usage),B=Y.response?.incomplete_details?.reason;if(B==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:h6(Y.response?.content_filters),retryable:!1}},yield X("error",z);break}yield X(B==="max_output_tokens"?"length":"stop",z);break}case"response.failed":case"error":{G=!0;let z=Y.response?.error??Y.error??Y;yield{type:"error",error:y6(z)},yield X("error",aJ(Y.response?.usage));break}}if(G)return}if(!G)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield X("error",d())}function v6(J){let Q=[],$=[];return z$(J.results??J.tools??J.loaded??J.output,Q,$,0),{loaded:sJ(Q),namespaces:sJ($)}}function z$(J,Q,$,Z){if(!Array.isArray(J)||Z>4)return;for(let W of J){if(typeof W==="string"){Q.push(W);continue}if(!W||typeof W!=="object")continue;let G=W,K=typeof G.name==="string"?G.name:typeof G.tool_name==="string"?G.tool_name:"",X=G.tools??G.functions;if(Array.isArray(X)){if(K)$.push(K);z$(X,Q,$,Z+1);continue}if(K)Q.push(K)}}function sJ(J){return J.filter((Q,$)=>J.indexOf(Q)===$)}function h6(J){if(!Array.isArray(J))return"The provider's content filter blocked this request.";let $=[];for(let Z of J){if(!Z||typeof Z!=="object")continue;let W=Z,G=W.content_filter_results;if(!G||typeof G!=="object")continue;for(let[K,X]of Object.entries(G))if(X&&typeof X==="object"&&X.filtered===!0)$.push(`${K} (${String(W.source_type??"unknown")})`)}return $.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${sJ($).join(", ")}.`}function y6(J){let Q=typeof J?.message==="string"?J.message:"The provider stream failed.",$=String(J?.code??"").toLowerCase();if($==="rate_limit_exceeded")return{code:"rate_limited",message:Q,retryable:!0};if($==="context_length_exceeded")return{code:"context_length_exceeded",message:Q,retryable:!1};if($.includes("content_filter"))return{code:"content_filtered",message:Q,retryable:!1};return{code:"provider_error",message:Q,retryable:!0}}function d(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function aJ(J){if(!J)return d();let Q=Number(J.input_tokens??0),$=Number(J.output_tokens??0),Z={inputTokens:Q,outputTokens:$,totalTokens:Number(J.total_tokens??Q+$)},W=J.output_tokens_details?.reasoning_tokens;if(typeof W==="number")Z.reasoningTokens=W;let G=J.input_tokens_details?.cached_tokens;if(typeof G==="number")Z.cachedInputTokens=G;return Z}async function*D$(J){if(!J)return;let Q=J.getReader(),$=new TextDecoder;try{while(!0){let{done:W,value:G}=await Q.read();if(W)break;if(G)yield $.decode(G,{stream:!0})}let Z=$.decode();if(Z)yield Z}finally{Q.releaseLock()}}function tJ(J){return{responsesUrl:`${J.base}/responses${J.query}`,filesUrl:`${J.base}/files${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,maxRetries:J.maxRetries}}async function*rJ(J,Q,$){let Z,W=Q,G=new Set;for(let K=0;Z===void 0;K++)try{Z=await u(J.responsesUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify(W)},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,signal:$.signal,fetchImpl:J.fetchImpl})}catch(X){let V=K<X$?Y$(W,X,$.files).filter((H)=>!G.has(H)):[];if(V.length>0){let H=k(X).message;for(let D of V)G.add(D),yield{type:"file-rejected",fileId:D,message:H,...i(X)};W=V$(W,new Set(V),$.files);continue}let Y=k(X);if(Y.code!=="aborted")yield{type:"error",error:Y,...i(X)};yield{type:"finish",reason:Y.code==="aborted"?"aborted":"error",usage:d()};return}try{yield*H$(D$(Z.body),{structuredOutput:$.structuredOutput})}catch(K){let X=k(K);if(X.code==="aborted"){yield{type:"finish",reason:"aborted",usage:d()};return}yield{type:"error",error:X},yield{type:"finish",reason:"error",usage:d()}}}async function eJ(J,Q,$="user_data"){let Z=new FormData;Z.set("purpose",$),Z.set("file",Q);let G=await(await u(J.filesUrl,{method:"POST",headers:await J.headers(),body:Z},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,fetchImpl:J.fetchImpl})).json();if(!G?.id)throw Error("The provider accepted the upload but returned no file id.");return G.id}function JQ(J){let Q=g6(J);if(Q.startsWith("gpt-3.5")||Q.startsWith("text-")||Q.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let $=u6(Q);if($?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:$.major>1,toolSearch:B$($)};if($?.kind==="gpt")return{reasoning:$.major>=5,structuredOutput:$.major>4||Q.startsWith("gpt-4o")||Q.startsWith("gpt-4.1"),fileInput:$.major>4||Q.startsWith("gpt-4o")||Q.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:B$($)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function B$(J){if(J.kind==="o")return J.major>=5;return J.major>5||J.major===5&&J.minor>=2}function g6(J){return J.trim().toLowerCase()}function u6(J){let Q=/^gpt-(\d+)(?:\.(\d+))?/.exec(J);if(Q?.[1])return{kind:"gpt",major:Number(Q[1]),minor:Number(Q[2]??0)};let $=/^o(\d+)(?:[-.]|$)/.exec(J);if($?.[1])return{kind:"o",major:Number($[1]),minor:0};return null}var c6={"response.audio_transcript.delta":"response.output_audio_transcript.delta","response.audio_transcript.done":"response.output_audio_transcript.done","response.text.delta":"response.output_text.delta","response.text.done":"response.output_text.done","response.audio.delta":"response.output_audio.delta","response.audio.done":"response.output_audio.done"};function m6(J){if(typeof J!=="string")return;let Q;try{Q=JSON.parse(J)}catch{return}if(!Q||typeof Q!=="object"||typeof Q.type!=="string")return;let $=c6[Q.type];if($)Q.type=$;if(Q.type==="response.done"&&Q.response?.usage)Q.usage=FJ(Q.response.usage);if(Q.type==="conversation.item.input_audio_transcription.completed"&&Q.usage)if(Q.usage.type==="duration"){let Z=Number(Q.usage.seconds);if(Number.isFinite(Z))Q.transcriptionSeconds=Z}else Q.transcriptionUsage=FJ(Q.usage);return Q}var P$=1,p6=500;function l6(J,Q){let $=globalThis.WebSocket;if(!$)throw Error("No global WebSocket: the realtime sideband needs Bun or Node 22+.");return new $(J,{headers:Q.headers})}class UJ{callId;ready;closed;init;socket;finalEvent;outbox=[];subscribers=new Set;listeners=new Set;backlog=[];closing=!1;finished=!1;everOpened=!1;failures=0;resolveReady;rejectReady;resolveClosed;constructor(J){this.init=J,this.callId=J.callId,this.ready=new Promise((Q,$)=>{this.resolveReady=Q,this.rejectReady=$}),this.ready.catch(()=>{}),this.closed=new Promise((Q)=>this.resolveClosed=Q),this.open()}send(J){if(this.finished||this.closing)return;let Q=JSON.stringify(J);if(this.socket?.readyState===P$)this.socket.send(Q);else this.outbox.push(Q)}updateSession(J){this.send({type:"session.update",session:NJ(J)})}addItem(J){this.send({type:"conversation.item.create",item:J})}addNote(J){this.addItem({type:"message",role:"system",content:[{type:"input_text",text:J}]})}functionOutput(J,Q){this.addItem({type:"function_call_output",call_id:J,output:typeof Q==="string"?Q:JSON.stringify(Q)})}createResponse(J={}){let Q={};if(J.instructions!==void 0)Q.instructions=J.instructions;if(J.toolChoice!==void 0)Q.tool_choice=typeof J.toolChoice==="string"?J.toolChoice:{type:"function",name:J.toolChoice.name};if(J.outputModalities)Q.output_modalities=J.outputModalities;if(J.conversation)Q.conversation=J.conversation;if(J.metadata)Q.metadata=J.metadata;Object.assign(Q,J.vendor),this.send(Object.keys(Q).length?{type:"response.create",response:Q}:{type:"response.create"})}cancelResponse(J){this.send(J?{type:"response.cancel",response_id:J}:{type:"response.cancel"})}on(J){return this.listeners.add(J),()=>this.listeners.delete(J)}[Symbol.asyncIterator](){let J={queue:this.backlog??[],done:this.finished};return this.backlog=void 0,this.subscribers.add(J),{next:async()=>{for(;;){let $=J.queue.shift();if($)return{value:$,done:!1};if(J.done)return this.subscribers.delete(J),{value:void 0,done:!0};await new Promise((Z)=>J.wake=Z),J.wake=void 0}},return:async()=>{return J.done=!0,J.queue.length=0,this.subscribers.delete(J),{value:void 0,done:!0}}}}close(J=1000,Q="closed"){if(this.finished||this.closing)return;if(this.closing=!0,this.socket&&this.socket.readyState<=P$)this.socket.close(J,Q);else this.finish(J,Q,!0)}async hangup(){try{await this.init.hangup()}catch(J){if(this.finalEvent&&!this.finalEvent.byClient&&this.finalEvent.code===1000)return;throw J}this.close(1000,"hangup")}async open(){let J;try{let $=await this.init.headers();if(this.closing)return this.finish(1000,"closed",!0);J=(this.init.webSocket??l6)(this.init.url,{headers:$})}catch($){return this.dropped(1006,$ instanceof Error?$.message:String($),!1)}this.socket=J;let Q=!1;J.addEventListener("open",()=>{Q=!0;let $=this.everOpened;this.everOpened=!0;let Z=this.failures;this.failures=0;for(let W of this.outbox.splice(0))J.send(W);if(this.resolveReady(),$)this.emit({type:"sideband.reconnected",attempt:Z})}),J.addEventListener("message",($)=>{let Z=m6($.data);if(Z)this.emit(Z)}),J.addEventListener("close",($)=>{if(this.socket!==J)return;this.dropped($.code??1006,$.reason??"",Q)}),J.addEventListener("error",()=>{})}dropped(J,Q,$){if(this.socket=void 0,this.closing)return this.finish(J,Q,!0);let Z=this.init.reconnect?.attempts??3;if(!((J!==1000||!$)&&this.failures<Z))return this.finish(J,Q,!1);this.failures+=1;let G=(this.init.reconnect?.delayMs??500)*2**(this.failures-1);setTimeout(()=>void this.open(),G)}finish(J,Q,$){if(this.finished)return;this.finished=!0,this.outbox.length=0;let Z={type:"sideband.closed",code:J,reason:Q,byClient:$};this.finalEvent=Z,this.emit(Z);for(let W of this.subscribers)W.done=!0,W.wake?.();if(!this.everOpened)this.rejectReady(Error(`Realtime sideband did not open (${J} ${Q}).`));this.resolveClosed(Z)}emit(J){if(this.backlog){if(this.backlog.push(J),this.backlog.length>p6)this.backlog.shift()}for(let Q of this.subscribers){if(Q.done)continue;Q.queue.push(J),Q.wake?.()}for(let Q of this.listeners)try{Q(J)}catch{}}}var QQ=30000,F$=10,U$=7200,d6=600;function i6(J){if(!J)return{type:"object",properties:{}};return N$(J)?J.toJSONSchema():J}function NJ(J,Q){let $={type:"realtime"},Z=J.model??Q;if(Z)$.model=Z;if(J.instructions!==void 0)$.instructions=J.instructions;if(J.outputModalities)$.output_modalities=J.outputModalities;if(J.maxOutputTokens!==void 0)$.max_output_tokens=J.maxOutputTokens;if(J.truncation!==void 0)$.truncation=J.truncation;if(J.tools)$.tools=J.tools.map((K)=>({type:"function",name:K.name,...K.description?{description:K.description}:{},parameters:i6(K.parameters)}));if(J.toolChoice!==void 0)$.tool_choice=typeof J.toolChoice==="string"?J.toolChoice:{type:"function",name:J.toolChoice.name};let W={};if(J.turnDetection!==void 0)W.turn_detection=J.turnDetection&&n6(J.turnDetection);if(J.transcription!==void 0)W.transcription=J.transcription;if(J.noiseReduction!==void 0)W.noise_reduction=J.noiseReduction&&{type:J.noiseReduction};let G={};if(J.voice!==void 0)G.voice=J.voice;if(J.speed!==void 0)G.speed=J.speed;if(Object.keys(W).length||Object.keys(G).length)$.audio={...Object.keys(W).length?{input:W}:{},...Object.keys(G).length?{output:G}:{}};return{...$,...J.vendor}}function n6(J){let Q={type:J.type};if(J.createResponse!==void 0)Q.create_response=J.createResponse;if(J.interruptResponse!==void 0)Q.interrupt_response=J.interruptResponse;if(J.type==="semantic_vad"){if(J.eagerness!==void 0)Q.eagerness=J.eagerness}else{if(J.threshold!==void 0)Q.threshold=J.threshold;if(J.prefixPaddingMs!==void 0)Q.prefix_padding_ms=J.prefixPaddingMs;if(J.silenceDurationMs!==void 0)Q.silence_duration_ms=J.silenceDurationMs;if(J.idleTimeoutMs!==void 0)Q.idle_timeout_ms=J.idleTimeoutMs}return Q}function FJ(J){let Q=Number(J?.input_tokens??0),$=Number(J?.output_tokens??0),Z={inputTokens:Q,outputTokens:$,totalTokens:Number(J?.total_tokens??Q+$)},W=J?.input_token_details??J?.input_tokens_details,G=J?.output_token_details??J?.output_tokens_details;if(typeof W?.cached_tokens==="number")Z.cachedInputTokens=W.cached_tokens;if(typeof W?.audio_tokens==="number")Z.audioInputTokens=W.audio_tokens;let K=W?.cached_tokens_details?.audio_tokens;if(typeof K==="number")Z.cachedAudioInputTokens=K;if(typeof W?.image_tokens==="number"&&W.image_tokens>0)Z.imageInputTokens=W.image_tokens;if(typeof G?.audio_tokens==="number")Z.audioOutputTokens=G.audio_tokens;return Z}class f extends Error{code;retryable;status;constructor(J,Q={}){super(J.message,{cause:Q.cause});if(this.name="RealtimeRequestError",this.code=J.code,this.retryable=J.retryable,Q.status!==void 0)this.status=Q.status}}var o6=60;class QJ{model;target;options;constructor(J,Q){this.target=J,this.options=Q,this.model=Q.model}url(J){return`${this.target.base}/realtime${J}${this.target.query}`}sidebandUrl(J){let Q=this.target.base.replace(/^http(s?):/i,(Z,W)=>`ws${W}:`),$=this.target.query?`${this.target.query}&`:"?";return`${Q}/realtime${$}call_id=${encodeURIComponent(J)}`}async createCall(J){let Q=J.flow??this.options.callFlow??"unified",$,Z;if(Q==="ephemeral")$={authorization:`Bearer ${(await this.clientSecret({session:J.session,ttlSeconds:o6,signal:J.signal})).value}`,"content-type":"application/sdp"},Z=J.sdp;else{let V=new FormData;V.set("sdp",J.sdp),V.set("session",JSON.stringify(NJ(J.session??{},this.model))),$=await this.target.headers(),Z=V}if(J.safetyIdentifier)$["OpenAI-Safety-Identifier"]=J.safetyIdentifier;let W=this.url("/calls"),G=await this.request(J.webrtcFilter?`${W}${W.includes("?")?"&":"?"}webrtcfilter=on`:W,{method:"POST",headers:$,body:Z},J.signal),K=await G.text(),X=a6(G);if(!X)throw new f({code:"provider_error",message:"The provider started a realtime call but did not say which one (no Location).",retryable:!1});return{sdpAnswer:K,callId:X}}async clientSecret(J={}){let Q=J.ttlSeconds??d6;if(!Number.isInteger(Q)||Q<F$||Q>U$)throw RangeError(`ttlSeconds must be a whole number from ${F$} to ${U$}, got ${Q}.`);let $={...await this.target.headers(),"content-type":"application/json"},W=await(await this.request(this.url("/client_secrets"),{method:"POST",headers:$,body:JSON.stringify({expires_after:{anchor:"created_at",seconds:Q},session:NJ(J.session??{},this.model)})},J.signal)).json();if(typeof W?.value!=="string")throw new f({code:"provider_error",message:"The provider answered a client secret request with no secret.",retryable:!1});return{value:W.value,expiresAt:Number(W.expires_at??0),session:W.session}}async hangup(J,Q={}){try{await this.request(this.url(`/calls/${encodeURIComponent(J)}/hangup`),{method:"POST",headers:await this.target.headers()},Q.signal)}catch($){if(O$($,J))return;throw $}}sideband(J,Q={}){return new UJ({...Q,callId:J,url:this.sidebandUrl(J),headers:this.target.headers,webSocket:Q.webSocket??this.options.webSocket,hangup:()=>this.hangup(J)})}async request(J,Q,$){try{return await u(J,Q,{maxRetries:this.target.maxRetries,timeoutMs:this.target.timeoutMs,retryTimeouts:!1,signal:$,fetchImpl:this.options.fetchImpl})}catch(Z){if($?.aborted)throw Z;throw new f(k(Z),{cause:Z,...Z instanceof I?{status:Z.status}:{}})}}}function O$(J,Q){if(!(J instanceof f)||J.status!==404)return!1;let $=J.cause instanceof I?J.cause.body:void 0,Z=$?.error??$,W=String(Z?.code??"").toLowerCase(),G=String(Z?.message??"").toLowerCase();if(W.includes("call"))return!0;if(G.includes(Q.toLowerCase()))return!0;return/\bcall\b/.test(G)&&/not (be )?found|does not exist|no longer|ended/.test(G)}function a6(J){let Q=J.headers.get("location");if(!Q)return;let $=Q.split("?")[0].replace(/\/+$/,""),Z=$.slice($.lastIndexOf("/")+1);return Z?decodeURIComponent(Z):void 0}function ZQ(J,Q){let{capabilities:$}=Q,Z={model:Q.model,input:s6(J.messages,$,J.tools),stream:!0};if(J.systemPrompt)Z.instructions=J.systemPrompt;let W=K8(J.tools,$);if(W.length>0){if(Z.tools=W,!$.parallelToolCalls)Z.parallel_tool_calls=!1}if(J.output)Z.text={format:{type:"json_schema",name:J.output.name,schema:J.output.schema,strict:J.output.strict}};if(J.reasoning&&$.reasoning)Z.reasoning=J.reasoning==="none"?{effort:"none"}:{effort:J.reasoning,summary:"auto"};if(typeof J.temperature==="number")Z.temperature=J.temperature;if(typeof J.maxOutputTokens==="number")Z.max_output_tokens=J.maxOutputTokens;return Z}function s6(J,Q,$){let Z=[],W=new Map;if(Q.toolSearch){for(let G of $??[])if(OJ(G))W.set(G.name,G)}for(let G of J){let K=G.role,X=[],V=()=>{if(X.length===0)return;Z.push({type:"message",role:K,content:X}),X=[]};for(let Y of G.content??[])switch(Y.type){case"text":{if(!Y.text)break;X.push(n(K,Y.text));break}case"output":{if(Y.partial)break;X.push(n(K,JSON.stringify(Y.value)));break}case"file":{if(K==="assistant")break;let H=e6(Y);if(!Q.fileInput){if(H)X.push(n(K,$Q(Y,!1)));break}if(Y.fileId?.startsWith(c))throw Error(`FilePart.fileId holds a gemi attachment id (${Y.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!Y.fileId&&!H)throw Error("FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_\u2026`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.");if(Y.providerRejected){if(H)X.push(n(K,$Q(Y,!1)));X.push(n(K,nJ(Y.name)));break}if(H)X.push(n(K,$Q(Y,!!Y.fileId)));if(Y.fileId)X.push(J8(Y));break}case"reasoning":{V();let H=Z8(Y);if(H)Z.push(H);break}case"tool-call":{if(Y.partial)break;if(V(),Q.toolSearch&&Array.isArray(Y.toolSearches))for(let D of Y.toolSearches)Z.push(...G8(D,$??[]));let H={type:"function_call",call_id:Y.toolCallId,name:String(Y.name),arguments:JSON.stringify(Y.input??{})};if(Y.namespace&&W.has(Y.namespace))H.namespace=Y.namespace;Z.push(H);break}case"tool-result":{V(),Z.push({type:"function_call_output",call_id:Y.toolCallId,output:W8(Y)});break}}V()}return r6(Z)}var t6="No result was recorded for this tool call. Assume it did not complete.";function r6(J){let Q=new Set,$=new Set,Z=[];for(let G of J){if(G.type==="function_call"){let K=String(G.call_id);if(Q.has(K))continue;Q.add(K)}else if(G.type==="function_call_output"){let K=String(G.call_id);if(!Q.has(K)||$.has(K))continue;$.add(K)}Z.push(G)}if($.size===Q.size)return Z;let W=[];for(let G of Z){if(W.push(G),G.type!=="function_call")continue;let K=String(G.call_id);if($.has(K))continue;$.add(K),W.push({type:"function_call_output",call_id:K,output:t6})}return W}function n(J,Q){return{type:J==="assistant"?"output_text":"input_text",text:Q}}function e6(J){let Q=J.attachmentId;return typeof Q==="string"&&Q.startsWith(c)?Q:void 0}function $Q(J,Q){let $=[`id=${JSON.stringify(J.attachmentId)}`];if(J.name)$.push(`name=${JSON.stringify(J.name)}`);if(J.mimeType)$.push(`mimeType=${JSON.stringify(J.mimeType)}`);let Z=`attachment ${$.join(" ")}`;return Q?`[${Z}]`:`[${Z} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function J8(J){let Q=J.mimeType?.trim().toLowerCase()??"";return{type:(Q?Q.startsWith("image/")&&Q!=="image/svg+xml":Q8(J.name))?"input_image":"input_file",file_id:J.fileId}}function Q8(J){let Q=/\.([a-z0-9]+)$/.exec(J?.trim().toLowerCase()??"");return Q?.[1]!==void 0&&$8.has(Q[1])}var $8=new Set(["jpeg","jpg","png","gif","webp"]);function Z8(J){if(!J.id)return null;let Q={type:"reasoning",id:J.id};return Q.summary=J.text?[{type:"summary_text",text:J.text}]:[],Q}function W8(J){if(J.status==="ok")return typeof J.output==="string"?J.output:JSON.stringify(J.output??null);if(J.status==="running"){let Q=J.job?.summary===void 0?"":` Started with: ${JSON.stringify(J.job.summary)}.`;return`Started background job ${J.job?.id??"(unknown)"}. It is still running, so there is no result yet: this message will be replaced by the result when it finishes. Do not start it again.${Q}`}if(J.status==="denied"){let Q=J.reason?` Reason given: ${J.reason}`:"";if(J.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${Q}`;if(J.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${Q}`;return`The user declined this tool call, so it did not run.${Q}`}return`The tool call failed and produced no result. Error (${J.error?.code??"unknown"}): ${J.error?.message??"no message"}`}function G8(J,Q){let $=new Set(L$(J?.loaded)),Z=L$(J?.namespaces),W=new Set(Z),G=[];for(let X of Q)if(OJ(X)){if(!W.has(X.name))continue;let V=X.tools.filter((Y)=>$.size===0||$.has(Y.name));if(V.length===0)continue;G.push({type:"namespace",name:X.name,description:X.description,tools:V.map((Y)=>o(Y,!0))})}else if(X.deferred&&$.has(X.name))G.push(o(X,!0));if(G.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:J.arguments&&typeof J.arguments==="object"?J.arguments:{paths:Z.length>0?Z:[...$]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:G}]}function L$(J){return Array.isArray(J)?J.filter((Q)=>typeof Q==="string"):[]}function OJ(J){return Array.isArray(J.tools)}function K8(J,Q){if(!J||J.length===0)return[];if(!Q.toolSearch){let W=[];for(let G of J)if(OJ(G))for(let K of G.tools)W.push(o(K,!1));else W.push(o(G,!1));return W}let $=[],Z=!1;for(let W of J)if(OJ(W)){let G=W.tools.map((K)=>{if(K.deferred)Z=!0;return o(K,!0)});$.push({type:"namespace",name:W.name,description:W.description,tools:G})}else{if(W.deferred)Z=!0;$.push(o(W,!0))}if(Z)$.push({type:"tool_search"});return $}function o(J,Q){let $={type:"function",name:J.name,description:J.description,parameters:J.parameters,strict:J.strict};if(Q&&J.deferred)$.defer_loading=!0;return $}class a{static models(){return[]}normalizeError(J){return k(J)}}var C$=["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.4-nano","gpt-5.2","gpt-5.1","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini","o4-mini","o3","o3-mini"];class WQ extends a{model;capabilities;config;constructor(J,Q={}){super();this.model=J,this.capabilities=JQ(J),this.config=Q}static model(J,Q){return new WQ(J,Q)}static models(){return C$}stream(J){let Q=ZQ(J,{model:this.model,capabilities:this.capabilities});return rJ(this.endpoint(),Q,{signal:J.signal,structuredOutput:Boolean(J.output),files:iJ(J.messages)})}upload(J){return eJ(this.endpoint(),J)}endpoint(){return tJ(e(this.config))}get realtime(){return new QJ(e(this.config,{timeoutMs:QQ}),{model:this.model})}}class GQ extends a{model;capabilities;config;constructor(J,Q={}){super();this.model=J,this.capabilities=JQ(J),this.config=Q}static model(J,Q){return new GQ(J,Q)}static models(){return C$}stream(J){let Q=ZQ(J,{model:this.deployment(),capabilities:this.capabilities});return rJ(this.endpoint(),Q,{signal:J.signal,structuredOutput:Boolean(J.output),files:iJ(J.messages)})}upload(J){return eJ(this.endpoint(),J,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return tJ(JJ(this.config))}get realtime(){return new QJ(sQ(this.config,{timeoutMs:QQ}),{model:this.deployment(),callFlow:"ephemeral"})}}class LJ{now;entries=new Map;constructor(J=Date.now){this.now=J}allow(J,Q){let $=this.entries.get(J);if($?.openUntil===void 0)return!0;let Z=this.now();if(Z<$.openUntil)return!1;if($.probeUntil!==void 0&&Z<$.probeUntil)return!1;return $.probeUntil=Z+Q.cooldownMs,!0}record(J,Q,$){let Z=this.entries.get(J)??{failures:0},W=Z.openUntil!==void 0;if(Q==="success")return this.entries.delete(J),W?"closed":void 0;if(Q==="none"){delete Z.probeUntil;return}if(Z.failures+=1,this.entries.set(J,Z),W||Z.failures>=$.failures)return Z.openUntil=this.now()+$.cooldownMs,delete Z.probeUntil,W?void 0:"open";return}state(J){let Q=this.entries.get(J);if(Q?.openUntil===void 0)return"closed";return this.now()<Q.openUntil?"open":"half-open"}}function X8(J){switch(J.type){case"text-delta":case"reasoning-delta":case"tool-call-delta":case"tool-call":case"tool-search":case"output-delta":return!0;default:return!1}}var _$=Symbol("timed-out");class $J extends a{model;capabilities;entries;options;circuit;constructor(J,Q={}){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($){let Z=$.failures??3,W=$.cooldownMs??30000;if(!Number.isInteger(Z)||Z<1)throw Error(`FallbackProvider: circuit.failures must be a positive integer, got ${Z}.`);if(!(W>0))throw Error(`FallbackProvider: circuit.cooldownMs must be a positive number, got ${W}.`);let G=new Set;for(let X of J){let V=KQ(X);if(G.has(V))throw Error(`FallbackProvider: two legs share the circuit key "${V}". Give one of them a \`circuitKey\`.`);G.add(V)}let K=$.store??new LJ;this.options={...Q,circuit:{...$,store:K}},this.circuit={policy:{failures:Z,cooldownMs:W},store:K,...$.onStateChange?{onStateChange:$.onStateChange}:{}}}else this.options=Q,this.circuit=void 0;this.model=J[0].provider.model,this.capabilities=Y8(J.map((Z)=>Z.provider.capabilities))}static chain(J,Q){return new $J(J,Q)}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 $J(this.entries.slice(J),this.options)}leg(J){let Q=this.from(J).entries[0];return new $J([Q],this.options)}upload(J){return this.entries[0].provider.upload(J)}normalizeError(J){return this.entries[0].provider.normalizeError(J)}stream(J){return this.run(J)}async*run(J){let Q,$=J.signal,Z=0;for(let W=0;W<this.entries.length;W++){let G=this.entries[W],K=W===this.entries.length-1,X=G.provider.model;if(this.circuit&&!K&&!await this.allow(G))continue;Z+=1;let V=!1,Y=async(_)=>{if(V)return;V=!0,await this.record(W,G,_)},H=new AbortController,D=()=>H.abort($?.reason);if($?.aborted)H.abort($.reason);else $?.addEventListener("abort",D,{once:!0});let z=[],B=!1,U=!1,P,N,F,O=!1,L,A=!1,R=(_)=>{let T=Q?b(b(j(),Q),_.usage):_.usage;return Q=void 0,{..._,usage:T}};try{L=G.provider.stream({...J,...G.reasoning!==void 0?{reasoning:G.reasoning}:{},signal:H.signal})[Symbol.asyncIterator]();let _=!0;for(;;){let T=_&&G.timeoutMs!==void 0?await V8(L.next(),G.timeoutMs):await L.next();if(T===_$){O=!0,F={error:{code:"provider_error",message:`${X} sent nothing within ${G.timeoutMs}ms.`,retryable:!0}};break}if(_=!1,T.done){A=!0;break}let C=T.value;if(C.type==="finish"&&C.model)N=C.model;if(B){if(C.type==="finish")P=b(P??j(),C.usage),U=!0,yield R(C);else{if(C.type==="error")F={error:C.error};yield C}continue}if(X8(C)){B=!0,await Y("success"),yield*z.splice(0),yield C;continue}if(C.type==="error")F={error:C.error,...C.status!==void 0?{status:C.status}:{},...C.requestId!==void 0?{requestId:C.requestId}:{}};else if(C.type==="finish"){if(P=b(P??j(),C.usage),C.reason==="error"&&!F)F={error:{code:"provider_error",message:`${X} ended the call with an error and did not say which.`,retryable:!1}}}z.push(C)}}catch(_){let T=G.provider.normalizeError(_);if(B){if(T.code!=="aborted")yield{type:"error",error:T,...i(_)};this.report({index:W,model:X,responseModel:N,attempt:Z,usage:P,outcome:XQ(T),error:T}),yield R({type:"finish",reason:T.code==="aborted"?"aborted":"error",usage:j(),...N?{model:N}:{}});return}F={error:T,...i(_)}}finally{if($?.removeEventListener("abort",D),!A)H.abort(),L?.return?.()?.catch(()=>{})}if(B){if(!U&&Q)yield{type:"finish",reason:F?"error":"stop",usage:Q},Q=void 0;this.report({index:W,model:X,responseModel:N,attempt:Z,usage:P,outcome:F?XQ(F.error):"ok",...F?{error:F.error}:{}});return}if($?.aborted){await Y("none"),this.report({index:W,model:X,responseModel:N,attempt:Z,usage:P,outcome:"aborted"}),yield R({type:"finish",reason:"aborted",usage:P??j(),...N?{model:N}:{}});return}if(!F){await Y("success"),this.report({index:W,model:X,responseModel:N,attempt:Z,usage:P,outcome:"ok"});for(let _ of z)yield _.type==="finish"?R(_):_;return}let q=!K&&F.error.code!=="aborted"&&this.shouldFallBack(F.error,{index:W,model:X,timedOut:O,...F.status!==void 0?{status:F.status}:{},...F.requestId!==void 0?{requestId:F.requestId}:{}});if(await Y(q?"failure":"none"),this.report({index:W,model:X,responseModel:N,attempt:Z,usage:P,outcome:q?"fallback":XQ(F.error),error:F.error}),q){if(P)Q=b(Q??j(),P);continue}let w=!1,E;for(let _ of z){if(_.type==="finish"){E=_;continue}if(_.type==="error")w=!0;yield _}if(!w&&F.error.code!=="aborted")yield{type:"error",error:F.error,...F.status!==void 0?{status:F.status}:{},...F.requestId!==void 0?{requestId:F.requestId}:{}};yield R({type:"finish",reason:F.error.code==="aborted"?"aborted":E?.reason??"error",usage:P??j(),...N?{model:N}:{}});return}}async allow(J){if(!this.circuit)return!0;try{return await this.circuit.store.allow(KQ(J),this.circuit.policy)}catch{return!0}}async record(J,Q,$){if(!this.circuit)return;let Z=KQ(Q),W;try{W=await this.circuit.store.record(Z,$,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:J,model:Q.provider.model,key:Z,state:W})}catch{}}shouldFallBack(J,Q){let $=this.options.fallbackOn??((Z)=>Z.retryable);try{return $(J,Q)}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 KQ(J){return J.circuitKey??J.provider.model}function XQ(J){return J.code==="aborted"?"aborted":"failed"}function Y8(J){return{reasoning:J.every((Q)=>Q.reasoning),structuredOutput:J.every((Q)=>Q.structuredOutput),fileInput:J.every((Q)=>Q.fileInput),parallelToolCalls:J.every((Q)=>Q.parallelToolCalls),toolSearch:J.every((Q)=>Q.toolSearch)}}function V8(J,Q){let $,Z=new Promise((W)=>{$=setTimeout(()=>W(_$),Q)});return Promise.race([J,Z]).finally(()=>clearTimeout($))}async function H8(J,Q,$={}){let Z=$.samples??1;if(!Number.isInteger(Z)||Z<1)throw RangeError(`evalChain: samples must be a positive integer, got ${Z}.`);let W=[];for(let G=0;G<J.entries.length;G++){let K=J.leg(G),X={index:G,model:K.model,results:[],errors:[]};for(let V=0;V<Z;V++)try{X.results.push(await Q(K,{index:G,sample:V}))}catch(Y){X.errors.push({sample:V,error:Y})}W.push(X)}return W}class _J extends Error{line;constructor(J){super(J??"Voice session ended by the app.");this.name="VoiceHangup",this.line=J}}var WJ="ask_agent",z8={maxDurationMs:900000,idleTimeoutMs:120000,maxQueued:3,progressIntervalMs:4000,closingLineMs:1e4,tickMs:60000,hangupGraceMs:30000,toolTimeoutMs:60000,maxToolCallsPerMinute:20,toolOutputChars:8000},D8={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 ZJ(J={}){return[{name:J.name??WJ,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 CJ=new Map;class m{sessionId;threadId;callId;ended;params;sideband;hangupCall;limits;lines;delegateName;startedAt=Date.now();body;usage=j();transcription={usage:j(),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 m(J)}static get(J){return CJ.get(J)}static async endAll(J){await Promise.all([...CJ.values()].map((Q)=>Q.end("hangup",J)))}constructor(J){this.params=J,this.sessionId=J.sessionId??crypto.randomUUID(),this.threadId=J.threadId,this.body=J.body??{},this.limits={...z8,...S$(J.limits)},this.lines={...D8,...S$(J.lines)},this.delegateName=J.delegate?.name??WJ;let Q=new Set(ZJ(J.delegate).map(($)=>$.name));for(let $ of J.tools??[]){if(Q.has($.tool.name)||this.toolHandlers.has($.tool.name))throw Error(`VoiceBridge: two tools are named "${$.tool.name}".`);this.toolHandlers.set($.tool.name,$)}if("realtime"in J.call){let{realtime:$,callId:Z}=J.call;this.callId=Z,this.sideband=$.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(($)=>this.resolveEnded=$),CJ.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 Q=this.params.contextNote?.(J);if(Q)this.sideband.addNote(Q)}end(J="hangup",Q){return this.ending??=this.finish(J,Q??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 Q=J.usage;if(Q){this.usage=b(this.usage,Q);let $=this.info();this.hook(()=>this.params.onUsage?.(Q,$))}return}case"conversation.item.input_audio_transcription.completed":{let Q=J;if(this.say("user",String(Q.transcript??"")),Q.transcriptionUsage||Q.transcriptionSeconds!==void 0){this.transcription={usage:Q.transcriptionUsage?b(this.transcription.usage,Q.transcriptionUsage):this.transcription.usage,seconds:this.transcription.seconds+(Q.transcriptionSeconds??0)};let $=this.info(),Z={...Q.transcriptionUsage?{usage:Q.transcriptionUsage}:{},...Q.transcriptionSeconds!==void 0?{seconds:Q.transcriptionSeconds}:{}};this.hook(()=>this.params.onTranscriptionUsage?.(Z,$))}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 Q=J;if(this.touch(),!this.ending)this.call(Q.call_id,Q.name,Q.arguments);return}case"session.updated":if(this.tampered(J.session))this.end("session_tampered",null);return;case"error":{let Q=J.error;if(this.errors.push({code:Q?.code,message:String(Q?.message??"")}),this.pendingCreate&&Q?.event_id===this.pendingCreate)if(this.pendingCreate=void 0,Q.code==="conversation_already_has_active_response")this.responseActive=!0,this.responseWanted=!0;else this.responseActive=!1;return}case"sideband.closed":{let Q=J;if(!this.ending&&!Q.byClient)this.end(Q.code===1000?"call_ended":"sideband_lost",null);return}}}say(J,Q){if(Q.trim())this.transcript.push({role:J,text:Q,at:Date.now()})}call(J,Q,$){let Z=B8($);if(Q===this.delegateName){let G=typeof Z.request==="string"?Z.request.trim():"";if(!G)return this.answer(J,{status:"error",message:"The request was empty."});return this.enqueue({record:{request:G,status:"queued"},turn:{text:G},callId:J})}let W=this.toolHandlers.get(Q);if(W)return void this.runTool(J,W,Z);switch(Q){case"stop_work":{let G=this.running;if(G)G.stopRequested=!0,G.handle?.stop({reason:"Stopped by voice."});let K=this.dropQueue();return this.answer(J,{stopped:Boolean(G),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((G)=>G.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 G=typeof Z.answer==="string"?Z.answer:"",K=typeof Z.approve==="boolean"?Z.approve:void 0,X=this.pending.map((V)=>P8(V,G,K));return this.pending=[],this.enqueue({record:{request:`(answer) ${G}`,status:"queued"},turn:{toolResults:X},callId:J})}default:return this.answer(J,{status:"error",message:`There is no tool called ${Q}.`})}}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 Q=new Set;await this.waitForThread(Q);let $=await this.latestBody();while(!J.stopRequested&&await this.waitForThread(Q));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:$,turn:J.turn})}catch(G){J.record.status="refused",this.complete(J,{status:"refused",message:G instanceof Error?G.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(Q){J.record.status="done",this.complete(J,{status:"failed",message:Q instanceof Error?Q.message:"The work failed."})}finally{this.running=void 0,this.flushNote();let Q=this.queue.shift();if(Q&&!this.ending)this.run(Q);else this.touch()}}async runTool(J,Q,$){let Z=Q.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 G={name:Z,status:"running"};this.toolCalls.push(G),this.toolsRunning+=1,this.pauseIdle();let K=new AbortController,X=Q.timeoutMs??this.limits.toolTimeoutMs,V,Y;try{let D=await Promise.race([Q.run($,{sessionId:this.sessionId,signal:K.signal}),new Promise((z,B)=>{V=setTimeout(()=>{B(new y(`"${Z}" took longer than ${Math.round(X/1000)} s.`)),K.abort()},X)})]);G.status="done",Y={status:"done",output:this.clip(D)}}catch(D){if(D instanceof _J){G.status="refused",G.message=D.message,this.end("usage",D.line??null);return}let z=D instanceof y?D.message:"The tool failed.";if(!(D instanceof y))console.error(`[gemi/ai] the voice tool "${Z}" threw.`,D);G.status="failed",G.message=z,Y={status:"failed",message:z}}finally{clearTimeout(V),G.durationMs=Date.now()-W,this.toolsRunning-=1,this.touch()}let H=this.info();if(this.hook(()=>this.params.onToolCall?.({...G},H)),!this.ending)this.answer(J,Y)}clip(J){let Q;try{Q=JSON.stringify(J)}catch{return String(J)}if(Q===void 0||Q.length<=this.limits.toolOutputChars)return J;return`${Q.slice(0,this.limits.toolOutputChars)}\u2026 (cut: ${Q.length} characters in all)`}async waitForThread(J=new Set){let Q=this.params.liveRuns;if(!Q)return!1;let $=await Q.find({threadId:this.threadId}),Z=$&&!J.has($.runId)?Q.get($.runId):null;if(!$||!Z)return!1;return J.add($.runId),await Z.result().catch(()=>{return}),!0}async latestBody(){let J=this.params.store;if(!J)return this.body;let Q=await J.get(this.sessionId).catch(()=>null);if(Q)this.body=Q.body;return this.body}async follow(J){let Q=this.params.progress??F8();try{for await(let $ of J.run){let Z=Q($);if(Z)this.note(Z)}}catch{}}complete(J,Q){if(this.ending)return;if(J.callId)this.sideband.functionOutput(J.callId,Q),J.callId=void 0;else this.sideband.addNote(`Update on the earlier request "${J.record.request}": ${JSON.stringify(Q)}`);this.respond()}answer(J,Q){this.sideband.functionOutput(J,Q),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 Q of J)Q.record.status="dropped";return J.length}note(J){if(J===this.lastProgress)return;this.lastProgress=J;let Q=this.lastNoteAt+this.limits.progressIntervalMs-Date.now();if(Q<=0)return this.flushNote();this.noteTimer??=setTimeout(()=>this.flushNote(),Q)}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(Q){if(Q instanceof _J)this.end("usage",Q.line??null);else console.error("[gemi/ai] a voice hook threw; ending the call.",Q),this.end("error",this.lines.error)}})}tampered(J){let Q=this.params.session;if(!Q||!J)return!1;if(Q.instructions!==void 0&&J.instructions!==void 0&&J.instructions!==Q.instructions)return!0;if(Array.isArray(J.tools)){let $=new Set([...ZJ(this.params.delegate),...Q.tools??[]].map((W)=>W.name)),Z=new Set(J.tools.map((W)=>String(W?.name)));if($.size!==Z.size||[...$].some((W)=>!Z.has(W)))return!0}return!1}async finish(J,Q){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(),Q&&(J!=="call_ended"&&J!=="sideband_lost"))await this.closingLine(Q);if(J!=="call_ended")await this.hangUp();else this.sideband.close();await this.hooks;let Z=Date.now(),W=Z-this.startedAt,G={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};CJ.delete(this.sessionId),await this.params.store?.update(this.sessionId,{endedAt:Z,endReason:J}).catch(()=>{return});try{await this.params.onEnd?.(G)}catch(K){console.error("[gemi/ai] a voice session's onEnd threw.",K)}return this.resolveEnded(G),G}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 Q;await Promise.race([this.sideband.closed,new Promise(($)=>Q=setTimeout($,this.limits.hangupGraceMs))]),clearTimeout(Q),this.sideband.close()}}async closingLine(J){await new Promise((Q)=>{let $=`gemi_voice_closing_${crypto.randomUUID()}`,Z=`gemi_voice_cancel_${crypto.randomUUID()}`,W=this.responseActive?"cancelling":"asked",G,K=setTimeout(X,this.limits.closingLineMs);function X(){clearTimeout(K),Q()}let V=()=>{W="asked",this.sideband.send({type:"response.create",event_id:$,response:{instructions:`Say exactly this to the user, and nothing else: "${J}"`,tool_choice:"none"}})};if(this.closingWaiter=(Y)=>{let H=Y;if(H.type==="sideband.closed")return X();if(W==="cancelling"){if(H.type==="response.done"||H.type==="error"&&H.error?.event_id===Z)V();return}if(H.type==="error"&&H.error?.event_id===$)return X();if(H.type==="response.created"&&!G){G=H.response?.id;return}let D=(z)=>!G||!z||z===G;if(H.type==="response.done"&&D(H.response?.id))W="playing";else if(H.type==="output_audio_buffer.stopped"&&W==="playing"&&D(H.response_id))X()},W==="cancelling")this.sideband.send({type:"response.cancel",event_id:Z});else V()}),this.closingWaiter=void 0}}function S$(J){if(!J)return{};return Object.fromEntries(Object.entries(J).filter(([,Q])=>Q!==void 0))}function B8(J){try{let Q=JSON.parse(J);return Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{}}catch{return{}}}function P8(J,Q,$){let Z={toolCallId:J.toolCallId,signature:J.signature,...J.path?{path:J.path}:{}};if(J.kind==="question")return{...Z,output:Q};if(J.kind==="approval")return{...Z,approve:$===!0,...Q?{reason:Q}:{}};return{...Z,approve:!1,reason:"Not available in a voice call."}}function F8(){let J=new Set;return(Q)=>{if(Q.type==="tool-call"){if(Q.part.partial||Q.resent||J.has(Q.part.toolCallId))return;return J.add(Q.part.toolCallId),`running ${String(Q.part.name)}`}if(Q.type==="tool-progress"){let $=Q.data;if(typeof $==="string")return $;if($&&typeof $==="object")for(let Z of["message","label","title"]){let W=$[Z];if(typeof W==="string"&&W)return W}}return}}var M$="http://gemi.internal/__gemi__/voice/mcp";async function YQ(J,Q){if(!Q.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:$}=J,Z=J.scopes??$.scopes().map((K)=>K.name),W=(K)=>({kind:"remote",req:K,principal:{user:Q.user,via:"voice",id:`voice:${Q.sessionId}`,scopes:Z}});return(await $.available(W(A$()),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:(X,V)=>{let Y=A$();return h.run(Y,async()=>{return await J.authorize?.({name:K.name,input:X,sessionId:V.sessionId}),$.execute(W(Y),K.name,X,void 0,{signal:V.signal})},{user:Q.user})}}))}function A$(){return new x(new Request(M$,{method:"POST"}),{},"api",new URL(M$).pathname)}class VQ{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 Q=this.records.get(J);return Q?structuredClone(Q):null}async update(J,Q){let $=this.records.get(J);if(!$)return;this.records.set(J,{...$,...structuredClone(Q),id:J})}sweep(){let J=Date.now()-this.retainEndedMs;for(let[Q,$]of this.records)if($.endedAt!==void 0&&$.endedAt<J)this.records.delete(Q)}}var HQ=new VQ;class s extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(J,Q,$){super(`Frame ${Q} of run ${J} has been evicted; the oldest frame still buffered is ${$}. Reload the thread instead of resuming.`);this.runId=J;this.requested=Q;this.oldest=$}}class GJ extends Error{runId;code="live_run_not_found";constructor(J){super(`No live run ${J} in this process.`);this.runId=J}}class SJ{ttlMs;maxFrames;maxAgeMs;runs=new Map;byThread=new Map;byClientRun=new Map;constructor(J={}){this.ttlMs=J.ttlMs??60000,this.maxFrames=J.maxFrames??4096,this.maxAgeMs=J.maxAgeMs===void 0?3600000:J.maxAgeMs}register(J,Q={}){let $={run:J,threadId:Q.threadId,owner:Q.owner??null,clientRunId:Q.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(Q.threadId,J.runId);if(Q.clientRunId)this.byClientRun.set(Q.clientRunId,J.runId);return this.scheduleExpiry($,Q.maxRunDurationMs),this.pump($,Q)}findByClientRunId(J){let Q=this.byClientRun.get(J);return Q&&this.runs.has(Q)?Q:null}async find(J){let Q=this.byThread.get(J.threadId);if(!Q)return null;let $=this.runs.get(Q);if(!$)return null;return{runId:Q,seq:$.lastSeq}}get(J){return this.runs.get(J)?.run??null}ownerOf(J){return this.runs.get(J)?.owner??null}mayAccess(J,Q){let $=this.ownerOf(J);return $===null||$===Q}isRunning(J){let Q=this.runs.get(J);return!!Q&&!Q.ended&&!Q.evicted}replay(J,Q){let $=this.runs.get(J);if(!$)throw new GJ(J);if(Q!==void 0&&Q<$.lostBefore)throw new s(J,Q,$.lostBefore);let Z=$.frames[0]?.seq;return this.drain($,J,Q??Z??$.lastSeq+1)}clear(){for(let J of this.runs.values()){if(J.evictAt)clearTimeout(J.evictAt);if(J.expireAt)clearTimeout(J.expireAt);J.ended=!0,this.notify(J)}this.runs.clear(),this.byThread.clear(),this.byClientRun.clear()}get size(){return this.runs.size}async pump(J,Q){let $=Promise.resolve();try{for await(let Z of J.run.frames()){if(J.evicted){let G=Q.onEvent;if(G)$=$.then(()=>G(Z.event)).catch((K)=>zQ(Q,K));continue}if(J.frames.push(Z),J.lastSeq=Z.seq,J.frames.length>this.maxFrames){let G=J.frames.shift();if(G)J.lostBefore=G.seq+1}this.notify(J);let W=Q.onEvent;if(W)$=$.then(()=>W(Z.event)).catch((G)=>zQ(Q,G))}}catch(Z){zQ(Q,Z)}finally{if(J.ended=!0,J.expireAt)clearTimeout(J.expireAt),J.expireAt=null;this.notify(J),this.scheduleEviction(J),await $}}async*drain(J,Q,$){let Z=$;while(!0){let W=J.version;for(;;){if(Z<J.lostBefore)throw new s(Q,Z,J.lostBefore);let G=J.frames,K=G[0]?.seq;if(K===void 0)break;let X=Math.max(0,Z-K);if(X>=G.length)break;let V=G[X];yield V,Z=V.seq+1}if(J.ended&&Z>J.lastSeq||J.evicted)return;await this.wait(J,W)}}wait(J,Q){if(J.version!==Q)return Promise.resolve();return new Promise(($)=>J.wake.add($))}notify(J){J.version++;let Q=Array.from(J.wake);J.wake.clear();for(let $ of Q)$()}scheduleEviction(J){if(J.evictAt)return;let Q=setTimeout(()=>{let $=J.run.runId;if(!J.ended)J.evicted=!0,J.frames=[];if(this.runs.get($)===J)this.runs.delete($);if(J.threadId&&this.byThread.get(J.threadId)===$)this.byThread.delete(J.threadId);if(J.clientRunId&&this.byClientRun.get(J.clientRunId)===$)this.byClientRun.delete(J.clientRunId);this.notify(J)},this.ttlMs);Q.unref?.(),J.evictAt=Q}scheduleExpiry(J,Q){if(this.maxAgeMs===null||Q===null)return;let $=Q===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,Q+this.ttlMs);if(!Number.isFinite($)||$>2147483647)return;let Z=setTimeout(()=>{if(J.expireAt=null,J.ended)return;try{J.run.stop({reason:`The run was still going ${Math.round($/1000)}s after it started, past the live-run registry's age limit.`})}catch{}this.scheduleEviction(J)},$);Z.unref?.(),J.expireAt=Z}}var DQ=new SJ;function zQ(J,Q){try{J.onInternalError?.(Q)}catch{}}class MJ{maxEntries;records=new Map;constructor(J=1e5){this.maxEntries=J}async record(J,Q){if(this.records.has(J))return;this.records.set(J,{...Q});while(this.records.size>this.maxEntries){let $=this.records.keys().next().value;if($===void 0)break;this.records.delete($)}}async get(J){let Q=this.records.get(J);return Q?{...Q}:null}}var BQ=new MJ;class UQ{now;receipts=new Map;sweepAt=1024;constructor(J=Date.now){this.now=J}async claim(J,Q){let $=this.now();if(this.receipts.size>=this.sweepAt)this.sweep($);let Z=this.receipts.get(J);if(Z&&Z.expiresAt>$)return Z.result?{status:"replay",result:structuredClone(Z.result)}:{status:"blocked"};return this.receipts.set(J,{expiresAt:Q}),{status:"claimed"}}async complete(J,Q,$){this.receipts.set(J,{result:structuredClone(Q),expiresAt:$})}async release(J){let Q=this.receipts.get(J);if(Q&&!Q.result)this.receipts.delete(J)}get size(){return this.receipts.size}sweep(J){for(let[Q,$]of this.receipts)if($.expiresAt<=J)this.receipts.delete(Q);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var k$="pending",PQ="done:",U8=`
|
|
79
79
|
if redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2], 'NX') then return 'claimed' end
|
|
80
80
|
local held = redis.call('GET', KEYS[1])
|
|
81
81
|
if not held then return ARGV[1] end
|
|
82
|
-
return held`,
|
|
82
|
+
return held`,N8=`
|
|
83
83
|
if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end
|
|
84
|
-
return 0`;class JQ{injectedClient;prefix;constructor(J={}){this.injectedClient=J.client,this.prefix=J.prefix??"gemi:ai:receipt"}async claim(J,Q){let $=await this.client.send("EVAL",[w3,"1",this.key(J),rQ,eQ(Q)]);if($==="claimed")return{status:"claimed"};let Z=String($??"");if(Z.startsWith(tJ))return{status:"replay",result:JSON.parse(Z.slice(tJ.length))};return{status:"blocked"}}async complete(J,Q,$){await this.client.send("SET",[this.key(J),tJ+JSON.stringify(Q),"PX",eQ($)])}async release(J){await this.client.send("EVAL",[I3,"1",this.key(J),rQ])}key(J){return`${this.prefix}:${J}`}get client(){if(this.injectedClient)return this.injectedClient;let J=J$(),Q=J.bound(rJ)?J.make(rJ).client:void 0;if(!Q)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return Q}}function eQ(J){return String(Math.max(1,Math.ceil(J-Date.now())))}var b3=86400000,v3=60000;class HJ{ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor(J={}){this.ttlMs=J.ttlMs??b3,this.clientOwnedIds=J.clientOwnedIds??!1}async createThread(J){let Q=crypto.randomUUID();return this.threads.set(Q,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:Q}}async loadThread(J){this.sweep();let Q=this.threads.get(J);if(!Q)return this.clientOwnedIds?[]:null;return Q.touchedAt=Date.now(),Q.messages.slice()}async appendMessages(J,Q){this.sweep();let $=this.threads.get(J);if(!$){if(!this.clientOwnedIds)throw Error(`Thread ${J} does not exist here, or has expired.`);$={messages:[],touchedAt:Date.now()},this.threads.set(J,$)}for(let Z of Q){let W=$.messages.findIndex((G)=>G.id===Z.id);if(W===-1)$.messages.push(Z);else $.messages[W]=Z}$.touchedAt=Date.now()}async removeMessages(J,Q){this.sweep();let $=this.threads.get(J);if(!$)return;let Z=new Set(Q);$.messages=$.messages.filter((W)=>!Z.has(W.id)),$.touchedAt=Date.now()}async loadSummaries(J){return this.threads.get(J)?.summaries?.slice()??[]}async saveSummary(J,Q){let $=this.threads.get(J);if(!$)return;$.summaries=QQ($.summaries??[],Q)}delete(J){this.threads.delete(J)}get size(){return this.threads.size}sweep(J=Date.now()){if(J-this.lastSweep<v3)return;this.lastSweep=J;for(let[Q,$]of this.threads)if(J-$.touchedAt>this.ttlMs)this.threads.delete(Q)}}var $Q=new HJ;function W$(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 G$(J,Q,$=new Date().toISOString()){if(!(Q.event.type==="run-start"&&Q.event.runId!==J.cursorRunId)&&Q.seq<=J.seq)return J;return{...V$(J,Q.event,$),seq:Q.seq}}function V$(J,Q,$){switch(Q.type){case"run-start":return{...J,messages:f3(J.messages,Q.runId),runId:Q.runId,cursorRunId:Q.runId,threadId:Q.threadId??J.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return v(J,Q.messageId,$,(Z)=>({...Z,role:Q.role}));case"text-delta":if($$(J,Q.messageId))return J;return v(J,Q.messageId,$,(Z)=>({...Z,content:c3(Z.content,Q.delta)}));case"reasoning-delta":if($$(J,Q.messageId))return J;return v(J,Q.messageId,$,(Z)=>({...Z,content:m3(Z.content,Q.delta,Q.id)}));case"output-delta":return v(J,Q.messageId,$,(Z)=>({...Z,content:Z$(Z.content,{type:"output",value:Q.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return v(J,Q.messageId,$,(Z)=>{let W=Z.content.findIndex((B)=>B.type==="tool-call"&&B.toolCallId===Q.part.toolCallId),G=W===-1?void 0:Z.content[W],V=Q.part.progress??G?.progress,K=Q.part.nested??G?.nested,Y=Q.part.attachments??G?.attachments,X={...Q.part,...V?{progress:V}:{},...K?{nested:K}:{},...Y?{attachments:Y}:{}},H=Z.content.slice();if(W===-1)H.push(X);else H[W]=X;return{...Z,content:H}});case"tool-search":{let Z=Q.loaded.filter((W)=>!J.loadedTools.includes(W));if(Z.length===0)return J;return{...J,loadedTools:[...J.loadedTools,...Z]}}case"tool-progress":return Q$(J,Q.toolCallId,(Z)=>({...Z,progress:[...Z.progress??[],Q.data]}));case"nested-event":{let Z=Q;return Q$(J,Q.toolCallId,(W)=>{let G=W.nested??[],V=G.findIndex((H)=>H.runId===Z.runId),K=G[V]??{runId:Z.runId,agent:Z.agent,messages:[]},Y=g3(K,Z,$),X=V===-1?[...G,Y]:G.map((H,B)=>B===V?Y:H);return{...W,nested:X}})}case"tool-result":{let Z=v(J,Q.messageId,$,(W)=>({...W,content:Z$(W.content,Q.part,(G)=>G.type==="tool-result"&&G.toolCallId===Q.part.toolCallId)}));return{...Z,pending:Z.pending.filter((W)=>W.toolCallId!==Q.part.toolCallId)}}case"message":{let Z=J.messages.findIndex((V)=>V.id===Q.message.id),W=J.messages.slice();if(Z===-1)W.push(Q.message);else W[Z]=Q.message;let G=J.runMessageIds.includes(Q.message.id)?J.runMessageIds:[...J.runMessageIds,Q.message.id];return{...J,messages:W,runMessageIds:G}}case"message-id":{let Z=J.messages.findIndex((K)=>K.id===Q.localId);if(Z===-1){if(!Q.message||J.messages.some((K)=>K.id===Q.messageId))return J;return{...J,messages:[...J.messages,Q.message]}}let W=J.messages[Z],G={localId:W.localId??W.id,...W.metadata?{metadata:W.metadata}:{}},V=J.messages.some((K)=>K.id===Q.messageId)?J.messages.filter((K,Y)=>Y!==Z).map((K)=>K.id===Q.messageId?{...K,...G}:K):J.messages.map((K,Y)=>Y===Z?{...K,...G,id:Q.messageId}:K);return{...J,messages:V}}case"awaiting-input":return{...J,runId:Q.runId,pending:[...Q.pending]};case"message-end":return v(J,Q.messageId,$,(Z)=>({...Z,finishReason:Q.finishReason,...Q.outputTruncated?{outputTruncated:!0}:{},...Q.usage?{usage:Q.usage}:{},content:Q.outputTruncated||Q.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:Q.usage};case"error":return{...J,error:Q.error,pending:[]};case"run-end":return{...J,runId:void 0,finishReason:Q.finishReason,messages:K$(J,Q.finishReason)};default:return J}}function f3(J,Q){if(!J.some(($)=>$.runId===Q&&$.finishReason===void 0))return J;return J.map(($)=>{if($.runId!==Q||$.finishReason!==void 0)return $;let{runId:Z,...W}=$;return{...W,content:[]}})}function K$(J,Q){return J.messages.map(($)=>$.role==="assistant"&&J.runMessageIds.includes($.id)?h3($,Q):$)}function h3(J,Q){let $=J.content.map((W)=>W.type==="tool-call"&&W.nested?.some((G)=>G.finishReason===void 0)?{...W,nested:W.nested.map((G)=>G.finishReason===void 0?y3(G,Q):G)}:W);if(J.finishReason===void 0)return{...J,finishReason:Q,content:$};return $.some((W,G)=>W!==J.content[G])?{...J,content:$}:J}function y3(J,Q){let $={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((Z)=>Z.id),loadedTools:[]};return{...J,finishReason:Q,messages:K$($,Q)}}function Q$(J,Q,$){for(let Z=J.messages.length-1;Z>=0;Z--){let W=J.messages[Z],G=W.content.findIndex((X)=>X.type==="tool-call"&&X.toolCallId===Q);if(G===-1)continue;if(W.finishReason!==void 0&&!u3(J,W,Q))return J;let V=W.content.slice();V[G]=$(V[G]);let K=J.messages.slice();K[Z]={...W,content:V};let Y=J.runMessageIds.includes(W.id)?J.runMessageIds:[...J.runMessageIds,W.id];return{...J,runMessageIds:Y,messages:K}}return J}function g3(J,Q,$){let Z={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((G)=>G.id),loadedTools:[],finishReason:J.finishReason},W=V$(Z,Q.event,$);return{...J,...Q.label!==void 0?{label:Q.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function u3(J,Q,$){if(Q.finishReason!=="awaiting-input")return!1;return!J.messages.some((Z)=>Z.content.some((W)=>W.type==="tool-result"&&W.toolCallId===$))}function $$(J,Q){let $=J.messages.find((Z)=>Z.id===Q);return $!==void 0&&$.finishReason!==void 0}function v(J,Q,$,Z){let W=J.messages.findIndex((K)=>K.id===Q),G=J.runMessageIds.includes(Q)?J.runMessageIds:[...J.runMessageIds,Q];if(W===-1){let K={id:Q,role:"assistant",content:[],createdAt:$};return{...J,runMessageIds:G,messages:[...J.messages,Z(K)]}}let V=J.messages.slice();return V[W]=Z(V[W]),{...J,runMessageIds:G,messages:V}}function c3(J,Q){let $=J[J.length-1];if($&&$.type==="text")return[...J.slice(0,-1),{type:"text",text:$.text+Q}];return[...J,{type:"text",text:Q}]}function m3(J,Q,$){let Z=J[J.length-1];if(Z&&Z.type==="reasoning"&&Z.id===$)return[...J.slice(0,-1),{...Z,text:(Z.text??"")+Q}];return[...J,$?{type:"reasoning",id:$,text:Q}:{type:"reasoning",text:Q}]}function Z$(J,Q,$){let Z=J.findIndex($);if(Z===-1)return[...J,Q];let W=J.slice();return W[Z]=Q,W}class WQ{store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(J,Q,$,Z){this.store=J;this.threadId=Q;this.report=Z;this.state=W$({messages:$})}finish(J){if(this.closed)return;this.done.add(J.id),this.write(()=>[ZQ(J)])}frame(J){if(this.closed)return;let Q=J.event;if(Q.type==="run-start")this.runId=Q.runId;switch(this.state=G$(this.state,J),Q.type){case"message":this.write(()=>[ZQ(Q.message)]);return;case"tool-call":if(Q.part.partial)return;this.checkpoint(Q.messageId);return;case"message-start":case"tool-result":this.checkpoint(Q.messageId);return;default:return}}close(J=[]){this.closed=!0;for(let Q of J)this.done.add(Q.id)}settled(){return this.chain}checkpoint(J){if(this.done.has(J))return;let Q=this.state.messages.find((Z)=>Z.id===J);if(!Q)return;let $=this.runId;this.write(()=>{let Z=ZQ(Q);if(Z.finishReason===void 0&&$)Z.runId=$;return[Z]})}write(J){let Q;try{Q=J()}catch($){this.report($);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,Q)).catch(($)=>this.report($))}}function ZQ(J){return structuredClone(J)}async function X$(J,Q){let $=[],Z=null,W=J.slice();for(let G=0;G<W.length;G++){let V=W[G];if(V.role!=="assistant"||V.finishReason!==void 0)continue;if(V.runId&&await Q(V.runId))continue;Z??=new Set(J.flatMap((X)=>X.content.flatMap((H)=>H.type==="tool-result"?[H.toolCallId]:[])));let K=V.content.map((X)=>X.type==="tool-call"?Y$(X):X);for(let X of V.content){if(X.type!=="tool-call"||Z.has(X.toolCallId))continue;let H={type:"tool-result",toolCallId:X.toolCallId,name:X.name,status:"denied",cause:"interrupted"};K.push(H)}let Y={...V,content:K,finishReason:"interrupted"};W[G]=Y,$.push(Y)}return{messages:W,settled:$}}function Y$(J){let{partial:Q,...$}=J;if(!$.nested?.some((Z)=>Z.finishReason===void 0))return $;return{...$,nested:$.nested.map(p3)}}function p3(J){if(J.finishReason!==void 0)return J;return{...J,finishReason:"interrupted",messages:J.messages.map((Q)=>Q.role==="assistant"&&Q.finishReason===void 0?{...Q,finishReason:"interrupted",content:Q.content.map(($)=>$.type==="tool-call"?Y$($):$)}:Q)}}var l3=50,d3=["running","ok","error"];async function z$(J,Q){let{store:$,threadId:Z}=Q,W=Math.max(l3,Q.scan??0),G=await $.listForThread(Z,{limit:W}),V,K=async(z)=>{if(z.state!=="running")return z;if(V??=await H$($),z.deadlineAt>V)return z;return await D$($,z),await $.get(z.id)??z};for(let z=0;z<G.length;z++)G[z]=await K(G[z]);let Y=new Map(G.map((z)=>[z.id,z])),X=J.slice(),H=[],B=new Set;for(let z=0;z<X.length;z++){let F=X[z],U=null;for(let N=0;N<F.content.length;N++){let P=F.content[N];if(P.type==="tool-call")B.add(P.toolCallId);if(P.type!=="tool-result"||P.status!=="running")continue;let _=P.job?.id,O=_?Y.get(_):void 0;if(_&&O===void 0){let M=await $.get(_);if(O=M?await K(M):void 0,O)Y.set(_,O)}if(O?.state==="running")continue;U??=F.content.slice(),U[N]=i3(P,O,Q.outputSchemaFor)}if(U){let N={...F,content:U};X[z]=N,H.push(N)}}let D=[];for(let z of G){if(z.orphaned||B.has(z.toolCallId))continue;if(await Q.isRunLive(z.runId))continue;D.push(z)}return{messages:X,settled:H,orphans:D,jobs:G}}async function B$(J,Q,$){for(let Z of Q)try{await J.transition(Z.id,d3,{orphaned:!0})}catch(W){$(W)}}function i3(J,Q,$){let Z={type:"tool-result",toolCallId:J.toolCallId,name:J.name};if(!Q)return{...Z,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 W={id:Q.id,...Q.summary!==void 0?{summary:Q.summary}:{},...Q.usage?{usage:Q.usage}:{}};if(Q.state==="error")return{...Z,status:"error",job:W,error:Q.error??{code:"tool_error",message:`The background job for "${String(J.name)}" failed.`,toolCallId:J.toolCallId,retryable:!0}};let G=$?.(String(J.name));if(G){let V=G.safeParse(Q.output);if(V.ok===!1)return{...Z,status:"error",job:W,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{...Z,status:"ok",job:W,output:V.value}}return{...Z,status:"ok",job:W,output:Q.output}}class OJ extends Error{status;code;kind;constructor(J,Q){super(J);this.name="AgentTurnError",this.status=Q.status,this.code=Q.code,this.kind=Q.kind}static async from(J){let Q={};try{let Z=await J.json();if(Z?.error&&typeof Z.error==="object")Q=Z.error}catch{}let $=(Z)=>typeof Q[Z]==="string"?Q[Z]:void 0;return new OJ($("message")??`The agent turn was refused with status ${J.status}.`,{status:J.status,code:$("code"),kind:$("kind")})}}function n3(J){for(let Q=J.length-1;Q>=0;Q--){let $=J[Q];if($.role!=="assistant")continue;return $.content.map((Z)=>Z.type==="text"?Z.text:"").join("")}return""}var o3=R$,DJ=new Map,U$=new WeakMap,t=new WeakMap,P$="http://gemi.internal/__gemi/agent-turn",zJ=new Map,s3=4194304,a3=1000,t3=5,F$=65536,PJ=()=>{};class y${byKey=new Map;take(J,Q,$){let Z=this.byKey.get(J);if(!Z?.has(Q)&&(Z?.size??0)>=$)return null;if(!Z)Z=new Map,this.byKey.set(J,Z);Z.set(Q,(Z.get(Q)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let G=this.byKey.get(J),V=(G?.get(Q)??1)-1;if(!G)return;if(V>0)G.set(Q,V);else if(G.delete(Q),G.size===0)this.byKey.delete(J)}}}var N$=new WeakMap;function r3(J){let Q=N$.get(J);if(!Q)Q=new y$,N$.set(J,Q);return Q}class UQ extends o3{static kind="agent-controller";store=$Q;liveRuns=sJ;attachments=CJ;attachmentStorage=k$;fileOwners=aJ;nonces=DQ;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions(J,Q){}context(J,Q){return{}}requireThread=!1;maxBodyBytes=s3;maxHistoryMessages=a3;contextWindow=void 0;prepareStep(J,Q){}maxConcurrentRuns=t3;runLimitKey(J,Q){return Q.owner}authorizeRequest(J,Q){return this.resource?.authorize(J,Q)}resource;runOwner(J){let Q=J.ctx?.()?.user,$=Q?.id??Q?.publicId;if($!==void 0&&$!==null&&String($)!=="")return`user:${String($)}`;return null}static async startTurn(J){let{threadId:Q}=J;if(typeof Q!=="string"||Q==="")throw TypeError("AgentController.startTurn needs a `threadId`: a server turn is stored on a thread. Create one with the store's `createThread`.");let $={...J.turn,...J.text!==void 0?{text:J.text}:{}},Z={...J.body,threadId:Q,turn:$},W=new d(new Request(P$,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Z)}),{},"api",new URL(P$).pathname),G=new this;t.set(W,null);let V=await n.run(W,()=>G.stream(W),{user:J.user??null}),K=t.get(W);if(!K)throw await OJ.from(V);t.delete(W),V.body?.cancel().catch(PJ);let{run:Y,hooks:X}=K,H=[],B=(async()=>{for await(let z of Y)if(z.type==="awaiting-input")H=z.pending})().catch(PJ),D;return{runId:Y.runId,threadId:Q,run:Y,stop:(z)=>Y.stop(z),result:()=>D??=(async()=>{let z=await Y.result();await Promise.all([X,B]);let F=z.messages;return{...z,threadId:Q,text:n3(F),pending:z.finishReason==="awaiting-input"?H:[]}})()}}async stream(J=new d){let Q=await GQ(J,this.maxBodyBytes);if(Q.error)return BJ(Q);let $=Q.body,Z=typeof $.threadId==="string"?$.threadId:void 0,W=V9($);if(W.error)return BJ({body:{},error:W.error});let G=W.turn,V=Z!==void 0&&$.regenerate===!0,K=typeof $.clientRunId==="string"?$.clientRunId:void 0,Y=g$($);if(this.requireThread&&!Z)return j(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(V&&!this.store.removeMessages)return j(501,{code:"regenerate_unsupported",message:"This agent's store cannot remove messages, so a thread's answer cannot be regenerated. Implement `removeMessages` on the AgentStore."});if(!Z&&Array.isArray($.messages)&&$.messages.length>this.maxHistoryMessages)return YQ(413,"history_too_long",`The conversation has ${$.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let X=await this.runOwner(J),H=K?{cancelled:!1,owner:X}:null;if(H)zJ.set(K,H);let B=null,D=[],z=async()=>{try{return await F()}finally{if(Z&&D.length>0&&B===null)await this.store.appendMessages(Z,D).catch((U)=>this.reportHookFailure(U))}},F=async()=>{let U,N=null;if(Z){let S=await this.store.loadThread(Z);if(!S)return j(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let f=await this.settleThread(Z,S,{write:!0});if(U=f.messages,N=this.jobsBlock(f.jobs),V){let i=H9(U);if(!i)return j(409,{code:"nothing_to_regenerate",message:`Thread ${Z} has no user turn to answer again.`});D=U.slice(i.index),await this.store.removeMessages(Z,D.map((m$)=>m$.id)),U=U.slice(0,i.index),G=G?.localId?{...i.turn,localId:G.localId}:i.turn}}else U=Array.isArray($.messages)?$.messages:[],N9(this.nonces);let P=[await this.instructions(J,{body:Y})||void 0,N??void 0].filter(Boolean).join(`
|
|
84
|
+
return 0`;class NQ{injectedClient;prefix;constructor(J={}){this.injectedClient=J.client,this.prefix=J.prefix??"gemi:ai:receipt"}async claim(J,Q){let $=await this.client.send("EVAL",[U8,"1",this.key(J),k$,R$(Q)]);if($==="claimed")return{status:"claimed"};let Z=String($??"");if(Z.startsWith(PQ))return{status:"replay",result:JSON.parse(Z.slice(PQ.length))};return{status:"blocked"}}async complete(J,Q,$){await this.client.send("SET",[this.key(J),PQ+JSON.stringify(Q),"PX",R$($)])}async release(J){await this.client.send("EVAL",[N8,"1",this.key(J),k$])}key(J){return`${this.prefix}:${J}`}get client(){if(this.injectedClient)return this.injectedClient;let J=T$(),Q=J.bound(FQ)?J.make(FQ).client:void 0;if(!Q)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return Q}}function R$(J){return String(Math.max(1,Math.ceil(J-Date.now())))}var O8=86400000,L8=60000;class AJ{ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor(J={}){this.ttlMs=J.ttlMs??O8,this.clientOwnedIds=J.clientOwnedIds??!1}async createThread(J){let Q=crypto.randomUUID();return this.threads.set(Q,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:Q}}async loadThread(J){this.sweep();let Q=this.threads.get(J);if(!Q)return this.clientOwnedIds?[]:null;return Q.touchedAt=Date.now(),Q.messages.slice()}async appendMessages(J,Q){this.sweep();let $=this.threads.get(J);if(!$){if(!this.clientOwnedIds)throw Error(`Thread ${J} does not exist here, or has expired.`);$={messages:[],touchedAt:Date.now()},this.threads.set(J,$)}for(let Z of Q){let W=$.messages.findIndex((G)=>G.id===Z.id);if(W===-1)$.messages.push(Z);else $.messages[W]=Z}$.touchedAt=Date.now()}async removeMessages(J,Q){this.sweep();let $=this.threads.get(J);if(!$)return;let Z=new Set(Q);$.messages=$.messages.filter((W)=>!Z.has(W.id)),$.touchedAt=Date.now()}async loadSummaries(J){return this.threads.get(J)?.summaries?.slice()??[]}async saveSummary(J,Q){let $=this.threads.get(J);if(!$)return;$.summaries=OQ($.summaries??[],Q)}delete(J){this.threads.delete(J)}get size(){return this.threads.size}sweep(J=Date.now()){if(J-this.lastSweep<L8)return;this.lastSweep=J;for(let[Q,$]of this.threads)if(J-$.touchedAt>this.ttlMs)this.threads.delete(Q)}}var LQ=new AJ;function x$(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 w$(J,Q,$=new Date().toISOString()){if(!(Q.event.type==="run-start"&&Q.event.runId!==J.cursorRunId)&&Q.seq<=J.seq)return J;return{...I$(J,Q.event,$),seq:Q.seq}}function I$(J,Q,$){switch(Q.type){case"run-start":return{...J,messages:C8(J.messages,Q.runId),runId:Q.runId,cursorRunId:Q.runId,threadId:Q.threadId??J.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return p(J,Q.messageId,$,(Z)=>({...Z,role:Q.role}));case"text-delta":if(q$(J,Q.messageId))return J;return p(J,Q.messageId,$,(Z)=>({...Z,content:k8(Z.content,Q.delta)}));case"reasoning-delta":if(q$(J,Q.messageId))return J;return p(J,Q.messageId,$,(Z)=>({...Z,content:R8(Z.content,Q.delta,Q.id)}));case"output-delta":return p(J,Q.messageId,$,(Z)=>({...Z,content:E$(Z.content,{type:"output",value:Q.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return p(J,Q.messageId,$,(Z)=>{let W=Z.content.findIndex((D)=>D.type==="tool-call"&&D.toolCallId===Q.part.toolCallId),G=W===-1?void 0:Z.content[W],K=Q.part.progress??G?.progress,X=Q.part.nested??G?.nested,V=Q.part.attachments??G?.attachments,Y={...Q.part,...K?{progress:K}:{},...X?{nested:X}:{},...V?{attachments:V}:{}},H=Z.content.slice();if(W===-1)H.push(Y);else H[W]=Y;return{...Z,content:H}});case"tool-search":{let Z=Q.loaded.filter((W)=>!J.loadedTools.includes(W));if(Z.length===0)return J;return{...J,loadedTools:[...J.loadedTools,...Z]}}case"tool-progress":return j$(J,Q.toolCallId,(Z)=>({...Z,progress:[...Z.progress??[],Q.data]}));case"nested-event":{let Z=Q;return j$(J,Q.toolCallId,(W)=>{let G=W.nested??[],K=G.findIndex((H)=>H.runId===Z.runId),X=G[K]??{runId:Z.runId,agent:Z.agent,messages:[]},V=M8(X,Z,$),Y=K===-1?[...G,V]:G.map((H,D)=>D===K?V:H);return{...W,nested:Y}})}case"tool-result":{let Z=p(J,Q.messageId,$,(W)=>({...W,content:E$(W.content,Q.part,(G)=>G.type==="tool-result"&&G.toolCallId===Q.part.toolCallId)}));return{...Z,pending:Z.pending.filter((W)=>W.toolCallId!==Q.part.toolCallId)}}case"message":{let Z=J.messages.findIndex((K)=>K.id===Q.message.id),W=J.messages.slice();if(Z===-1)W.push(Q.message);else W[Z]=Q.message;let G=J.runMessageIds.includes(Q.message.id)?J.runMessageIds:[...J.runMessageIds,Q.message.id];return{...J,messages:W,runMessageIds:G}}case"message-id":{let Z=J.messages.findIndex((X)=>X.id===Q.localId);if(Z===-1){if(!Q.message||J.messages.some((X)=>X.id===Q.messageId))return J;return{...J,messages:[...J.messages,Q.message]}}let W=J.messages[Z],G={localId:W.localId??W.id,...W.metadata?{metadata:W.metadata}:{}},K=J.messages.some((X)=>X.id===Q.messageId)?J.messages.filter((X,V)=>V!==Z).map((X)=>X.id===Q.messageId?{...X,...G}:X):J.messages.map((X,V)=>V===Z?{...X,...G,id:Q.messageId}:X);return{...J,messages:K}}case"awaiting-input":return{...J,runId:Q.runId,pending:[...Q.pending]};case"message-end":return p(J,Q.messageId,$,(Z)=>({...Z,finishReason:Q.finishReason,...Q.outputTruncated?{outputTruncated:!0}:{},...Q.usage?{usage:Q.usage}:{},content:Q.outputTruncated||Q.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:Q.usage};case"error":return{...J,error:Q.error,pending:[]};case"run-end":return{...J,runId:void 0,finishReason:Q.finishReason,messages:b$(J,Q.finishReason)};default:return J}}function C8(J,Q){if(!J.some(($)=>$.runId===Q&&$.finishReason===void 0))return J;return J.map(($)=>{if($.runId!==Q||$.finishReason!==void 0)return $;let{runId:Z,...W}=$;return{...W,content:[]}})}function b$(J,Q){return J.messages.map(($)=>$.role==="assistant"&&J.runMessageIds.includes($.id)?_8($,Q):$)}function _8(J,Q){let $=J.content.map((W)=>W.type==="tool-call"&&W.nested?.some((G)=>G.finishReason===void 0)?{...W,nested:W.nested.map((G)=>G.finishReason===void 0?S8(G,Q):G)}:W);if(J.finishReason===void 0)return{...J,finishReason:Q,content:$};return $.some((W,G)=>W!==J.content[G])?{...J,content:$}:J}function S8(J,Q){let $={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((Z)=>Z.id),loadedTools:[]};return{...J,finishReason:Q,messages:b$($,Q)}}function j$(J,Q,$){for(let Z=J.messages.length-1;Z>=0;Z--){let W=J.messages[Z],G=W.content.findIndex((Y)=>Y.type==="tool-call"&&Y.toolCallId===Q);if(G===-1)continue;if(W.finishReason!==void 0&&!A8(J,W,Q))return J;let K=W.content.slice();K[G]=$(K[G]);let X=J.messages.slice();X[Z]={...W,content:K};let V=J.runMessageIds.includes(W.id)?J.runMessageIds:[...J.runMessageIds,W.id];return{...J,runMessageIds:V,messages:X}}return J}function M8(J,Q,$){let Z={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((G)=>G.id),loadedTools:[],finishReason:J.finishReason},W=I$(Z,Q.event,$);return{...J,...Q.label!==void 0?{label:Q.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function A8(J,Q,$){if(Q.finishReason!=="awaiting-input")return!1;return!J.messages.some((Z)=>Z.content.some((W)=>W.type==="tool-result"&&W.toolCallId===$))}function q$(J,Q){let $=J.messages.find((Z)=>Z.id===Q);return $!==void 0&&$.finishReason!==void 0}function p(J,Q,$,Z){let W=J.messages.findIndex((X)=>X.id===Q),G=J.runMessageIds.includes(Q)?J.runMessageIds:[...J.runMessageIds,Q];if(W===-1){let X={id:Q,role:"assistant",content:[],createdAt:$};return{...J,runMessageIds:G,messages:[...J.messages,Z(X)]}}let K=J.messages.slice();return K[W]=Z(K[W]),{...J,runMessageIds:G,messages:K}}function k8(J,Q){let $=J[J.length-1];if($&&$.type==="text")return[...J.slice(0,-1),{type:"text",text:$.text+Q}];return[...J,{type:"text",text:Q}]}function R8(J,Q,$){let Z=J[J.length-1];if(Z&&Z.type==="reasoning"&&Z.id===$)return[...J.slice(0,-1),{...Z,text:(Z.text??"")+Q}];return[...J,$?{type:"reasoning",id:$,text:Q}:{type:"reasoning",text:Q}]}function E$(J,Q,$){let Z=J.findIndex($);if(Z===-1)return[...J,Q];let W=J.slice();return W[Z]=Q,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=Q;this.report=Z;this.state=x$({messages:$})}finish(J){if(this.closed)return;this.done.add(J.id),this.write(()=>[CQ(J)])}frame(J){if(this.closed)return;let Q=J.event;if(Q.type==="run-start")this.runId=Q.runId;switch(this.state=w$(this.state,J),Q.type){case"message":this.write(()=>[CQ(Q.message)]);return;case"tool-call":if(Q.part.partial)return;this.checkpoint(Q.messageId);return;case"message-start":case"tool-result":this.checkpoint(Q.messageId);return;default:return}}close(J=[]){this.closed=!0;for(let Q of J)this.done.add(Q.id)}settled(){return this.chain}checkpoint(J){if(this.done.has(J))return;let Q=this.state.messages.find((Z)=>Z.id===J);if(!Q)return;let $=this.runId;this.write(()=>{let Z=CQ(Q);if(Z.finishReason===void 0&&$)Z.runId=$;return[Z]})}write(J){let Q;try{Q=J()}catch($){this.report($);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,Q)).catch(($)=>this.report($))}}function CQ(J){return structuredClone(J)}async function f$(J,Q){let $=[],Z=null,W=J.slice();for(let G=0;G<W.length;G++){let K=W[G];if(K.role!=="assistant"||K.finishReason!==void 0)continue;if(K.runId&&await Q(K.runId))continue;Z??=new Set(J.flatMap((Y)=>Y.content.flatMap((H)=>H.type==="tool-result"?[H.toolCallId]:[])));let X=K.content.map((Y)=>Y.type==="tool-call"?v$(Y):Y);for(let Y of K.content){if(Y.type!=="tool-call"||Z.has(Y.toolCallId))continue;let H={type:"tool-result",toolCallId:Y.toolCallId,name:Y.name,status:"denied",cause:"interrupted"};X.push(H)}let V={...K,content:X,finishReason:"interrupted"};W[G]=V,$.push(V)}return{messages:W,settled:$}}function v$(J){let{partial:Q,...$}=J;if(!$.nested?.some((Z)=>Z.finishReason===void 0))return $;return{...$,nested:$.nested.map(T8)}}function T8(J){if(J.finishReason!==void 0)return J;return{...J,finishReason:"interrupted",messages:J.messages.map((Q)=>Q.role==="assistant"&&Q.finishReason===void 0?{...Q,finishReason:"interrupted",content:Q.content.map(($)=>$.type==="tool-call"?v$($):$)}:Q)}}var j8=50,q8=["running","ok","error"];async function g$(J,Q){let{store:$,threadId:Z}=Q,W=Math.max(j8,Q.scan??0),G=await $.listForThread(Z,{limit:W}),K,X=async(B)=>{if(B.state!=="running")return B;if(K??=await h$($),B.deadlineAt>K)return B;return await y$($,B),await $.get(B.id)??B};for(let B=0;B<G.length;B++)G[B]=await X(G[B]);let V=new Map(G.map((B)=>[B.id,B])),Y=J.slice(),H=[],D=new Set;for(let B=0;B<Y.length;B++){let U=Y[B],P=null;for(let N=0;N<U.content.length;N++){let F=U.content[N];if(F.type==="tool-call")D.add(F.toolCallId);if(F.type!=="tool-result"||F.status!=="running")continue;let O=F.job?.id,L=O?V.get(O):void 0;if(O&&L===void 0){let A=await $.get(O);if(L=A?await X(A):void 0,L)V.set(O,L)}if(L?.state==="running")continue;P??=U.content.slice(),P[N]=E8(F,L,Q.outputSchemaFor)}if(P){let N={...U,content:P};Y[B]=N,H.push(N)}}let z=[];for(let B of G){if(B.orphaned||D.has(B.toolCallId))continue;if(await Q.isRunLive(B.runId))continue;z.push(B)}return{messages:Y,settled:H,orphans:z,jobs:G}}async function u$(J,Q,$){for(let Z of Q)try{await J.transition(Z.id,q8,{orphaned:!0})}catch(W){$(W)}}function E8(J,Q,$){let Z={type:"tool-result",toolCallId:J.toolCallId,name:J.name};if(!Q)return{...Z,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 W={id:Q.id,...Q.summary!==void 0?{summary:Q.summary}:{},...Q.usage?{usage:Q.usage}:{}};if(Q.state==="error")return{...Z,status:"error",job:W,error:Q.error??{code:"tool_error",message:`The background job for "${String(J.name)}" failed.`,toolCallId:J.toolCallId,retryable:!0}};let G=$?.(String(J.name));if(G){let K=G.safeParse(Q.output);if(K.ok===!1)return{...Z,status:"error",job:W,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: ${K.errors.join(", ")}`,toolCallId:J.toolCallId,retryable:!0}};return{...Z,status:"ok",job:W,output:K.value}}return{...Z,status:"ok",job:W,output:Q.output}}class bJ extends Error{status;code;kind;constructor(J,Q){super(J);this.name="AgentTurnError",this.status=Q.status,this.code=Q.code,this.kind=Q.kind}static async from(J){let Q={};try{let Z=await J.json();if(Z?.error&&typeof Z.error==="object")Q=Z.error}catch{}let $=(Z)=>typeof Q[Z]==="string"?Q[Z]:void 0;return new bJ($("message")??`The agent turn was refused with status ${J.status}.`,{status:J.status,code:$("code"),kind:$("kind")})}}function x8(J){for(let Q=J.length-1;Q>=0;Q--){let $=J[Q];if($.role!=="assistant")continue;return $.content.map((Z)=>Z.type==="text"?Z.text:"").join("")}return""}var w8=t$,kJ=new Map,c$=new WeakMap,KJ=new WeakMap,m$="http://gemi.internal/__gemi/agent-turn",RJ=new Map,I8=4194304,b8=1000,f8=5,TJ=65536,jJ=()=>{};class H6{byKey=new Map;take(J,Q,$){let Z=this.byKey.get(J);if(!Z?.has(Q)&&(Z?.size??0)>=$)return null;if(!Z)Z=new Map,this.byKey.set(J,Z);Z.set(Q,(Z.get(Q)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let G=this.byKey.get(J),K=(G?.get(Q)??1)-1;if(!G)return;if(K>0)G.set(Q,K);else if(G.delete(Q),G.size===0)this.byKey.delete(J)}}}var p$=new WeakMap;function v8(J){let Q=p$.get(J);if(!Q)Q=new H6,p$.set(J,Q);return Q}class xQ extends w8{static kind="agent-controller";store=LQ;liveRuns=DQ;voice;voiceStore=HQ;attachments=IJ;attachmentStorage=J6;fileOwners=BQ;nonces=jQ;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions(J,Q){}context(J,Q){return{}}requireThread=!1;maxBodyBytes=I8;maxHistoryMessages=b8;contextWindow=void 0;prepareStep(J,Q){}maxConcurrentRuns=f8;runLimitKey(J,Q){return Q.owner}authorizeRequest(J,Q){return this.resource?.authorize(J,Q)}resource;runOwner(J){let Q=J.ctx?.()?.user,$=Q?.id??Q?.publicId;if($!==void 0&&$!==null&&String($)!=="")return`user:${String($)}`;return null}static async startTurn(J){let{threadId:Q}=J;if(typeof Q!=="string"||Q==="")throw TypeError("AgentController.startTurn needs a `threadId`: a server turn is stored on a thread. Create one with the store's `createThread`.");let $={...J.turn,...J.text!==void 0?{text:J.text}:{}},Z={...J.body,threadId:Q,turn:$},W=new x(new Request(m$,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Z)}),{},"api",new URL(m$).pathname),G=new this;KJ.set(W,null);let K=await h.run(W,()=>G.stream(W),{user:J.user??null}),X=KJ.get(W);if(!X)throw await bJ.from(K);KJ.delete(W),K.body?.cancel().catch(jJ);let{run:V,hooks:Y}=X,H=[],D=(async()=>{for await(let B of V)if(B.type==="awaiting-input")H=B.pending})().catch(jJ),z;return{runId:V.runId,threadId:Q,run:V,stop:(B)=>V.stop(B),result:()=>z??=(async()=>{let B=await V.result();await Promise.all([Y,D]);let U=B.messages;return{...B,threadId:Q,text:x8(U),pending:B.finishReason==="awaiting-input"?H:[]}})()}}async stream(J=new x){let Q=await XJ(J,this.maxBodyBytes);if(Q.error)return t(Q);let $=Q.body,Z=typeof $.threadId==="string"?$.threadId:void 0,W=l8($);if(W.error)return t({body:{},error:W.error});let G=W.turn,K=Z!==void 0&&$.regenerate===!0,X=typeof $.clientRunId==="string"?$.clientRunId:void 0,V=qJ($);if(this.requireThread&&!Z)return S(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(K&&!this.store.removeMessages)return S(501,{code:"regenerate_unsupported",message:"This agent's store cannot remove messages, so a thread's answer cannot be regenerated. Implement `removeMessages` on the AgentStore."});if(!Z&&Array.isArray($.messages)&&$.messages.length>this.maxHistoryMessages)return RQ(413,"history_too_long",`The conversation has ${$.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let Y=await this.runOwner(J),H=X?{cancelled:!1,owner:Y}:null;if(H)RJ.set(X,H);let D=null,z=[],B=async()=>{try{return await U()}finally{if(Z&&z.length>0&&D===null)await this.store.appendMessages(Z,z).catch((P)=>this.reportHookFailure(P))}},U=async()=>{let P,N=null;if(Z){let M=await this.store.loadThread(Z);if(!M)return S(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let l=await this.settleThread(Z,M,{write:!0});if(P=l.messages,N=this.jobsBlock(l.jobs),K){let r=o8(P);if(!r)return S(409,{code:"nothing_to_regenerate",message:`Thread ${Z} has no user turn to answer again.`});z=P.slice(r.index),await this.store.removeMessages(Z,z.map((B6)=>B6.id)),P=P.slice(0,r.index),G=G?.localId?{...r.turn,localId:G.localId}:r.turn}}else P=Array.isArray($.messages)?$.messages:[],$9(this.nonces);let F=[await this.instructions(J,{body:V})||void 0,N??void 0].filter(Boolean).join(`
|
|
85
85
|
|
|
86
|
-
`)||void 0,_=await this.context(J,{body:Y}),O=await this.attachmentsFor(J,Z,{body:Y});if(H?.cancelled)return S$();let M=Z?new WQ(this.store,Z,U,(S)=>this.reportHookFailure(S)):null,T=`run_${crypto.randomUUID()}`,k={req:J,runId:T,threadId:Z},x={id:null,notified:Promise.resolve()},E=this.agent.stream({runId:T,messages:U,turn:G,threadId:Z,...M?{onMessage:(S)=>M.finish(S)}:{},onTurn:(S)=>{if(x.id!==null)return;x.id=S.id;let f=M?M.settled():Promise.resolve();x.notified=f.then(()=>this.safely(()=>this.onMessage(S,k)))},instructions:P,context:_,attachments:O,body:Y,redactError:(S,f)=>this.redactError(S,f,k),nonces:this.nonces,receipts:this.receipts,subject:X,...Z?{jobs:{owner:X}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...Z&&h$(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==UQ.prototype.prepareStep?{prepareStep:(S)=>this.prepareStep(S,k)}:{}}),C=this.liveRuns.register(E,{threadId:Z,owner:X,clientRunId:K,onEvent:(S)=>this.dispatchEvent(S,k),onInternalError:(S)=>this.reportHookFailure(S),maxRunDurationMs:this.agent.maxRunDurationMs});if(B=E,M)this.follow(E,M);let{stored:A,hooks:L}=this.persistRun(E,k,C,M,x);if(U$.set(E,A),t.has(J))t.set(J,{run:E,hooks:L});return J.ctx?.()?.waitUntil(L),E.toResponse()};try{await this.authorizeRequest(J,{route:"stream",threadId:Z,body:Y});let U=await this.foreignFile([...G?.files??[],...Z?[]:z9($.messages)],X);if(U)return U;if(H?.cancelled)return S$();let N=await this.runLimitKey(J,{owner:X,threadId:Z}),P=N===null?PJ:r3(this.liveRuns).take(N,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!P)return YQ(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,X,z):await z()}finally{let _=B;if(_)_.result().then(P,P);else P()}}finally{if(H&&zJ.get(K)===H)zJ.delete(K)}}async withThread(J,Q,$){let Z=DJ.get(J)??Promise.resolve(),W,G=new Promise((K)=>{W=K}),V=Z.then(()=>G);DJ.set(J,V),await Z;try{let K=await this.liveRuns.find({threadId:J});if(K&&this.liveRuns.isRunning(K.runId)&&!this.liveRuns.mayAccess(K.runId,Q))return UJ();let Y=K?this.liveRuns.get(K.runId):null;if(Y)Y.stop({reason:"superseded by a later turn on this thread"}),await U$.get(Y);return await $()}finally{if(W(),DJ.get(J)===V)DJ.delete(J)}}async attach(J=new d){let Q=await GQ(J,F$);if(Q.error)return BJ(Q);let $=Q.body,Z=typeof $.threadId==="string"?$.threadId:Y9(J,"threadId");if(!Z)return j(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(J,{route:"attach",threadId:Z});let W=await this.liveRuns.find({threadId:Z});if(W&&!this.liveRuns.mayAccess(W.runId,await this.runOwner(J)))return UJ();if(!W)return j(404,{code:"no_live_run",message:`No run in progress for thread ${Z} in this process.`});let G=typeof $.runId==="string"?$.runId:void 0,V=G&&G!==W.runId?void 0:X9(J,$);try{return E$(this.liveRuns.replay(W.runId,V))}catch(K){if(K instanceof l)return j(410,{code:K.code,message:K.message,oldestSeq:K.oldest});if(K instanceof a)return j(404,{code:K.code,message:K.message});throw K}}async stop(J=new d){let Q=await GQ(J,F$);if(Q.error)return BJ(Q);let $=Q.body;await this.authorizeRequest(J,{route:"stop",threadId:typeof $.threadId==="string"?$.threadId:void 0});let Z=await this.runOwner(J),W=typeof $.runId==="string"?$.runId:void 0;if(!W&&typeof $.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId($.clientRunId)??void 0,!W){let V=zJ.get($.clientRunId);if(V){if(V.owner!==null&&V.owner!==Z)return UJ();return V.cancelled=!0,{stopped:!0}}}}if(!W&&typeof $.threadId==="string")W=(await this.liveRuns.find({threadId:$.threadId}))?.runId;let G=W?this.liveRuns.get(W):null;if(!G)return{stopped:!1};if(!this.liveRuns.mayAccess(G.runId,Z))return UJ();return G.stop({reason:typeof $.reason==="string"?$.reason:void 0}),{stopped:!0}}attachmentScope(J,Q,$){let Z=J.ctx()?.user,W=Z?.id??Z?.publicId;if(W!==void 0&&W!==null&&String(W)!=="")return{key:`user:${String(W)}`};if(Q)return{key:`thread:${Q}`};return null}attachmentLimits(J){return null}checkUpload(J,Q,$){}attachmentDestination(J,Q,$){return"both"}async attachmentsFor(J,Q,$={body:{}}){let Z=await this.attachmentScope(J,Q,$);if(!Z)return null;return new LJ(this.attachments,this.attachmentStorage,Z)}async upload(J=new d){let Q=await J.rawRequest.formData(),$=Q.get("file");if(!($ instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let Z=$ instanceof File&&$.name?$.name:"upload",W=$.type||"application/octet-stream",G=J9(Q.get("body")),V=Q.get("threadId");await this.authorizeRequest(J,{route:"upload",threadId:typeof V==="string"&&V.length>0?V:void 0,body:G});let K=$9(await this.attachmentLimits(J),$,Z,W);if(K)throw new XQ(K.code,K.message);let Y=typeof V==="string"&&V.length>0&&await this.store.loadThread(V)!==null?V:void 0,X=await this.runOwner(J),H=(T)=>this.fileOwners.record(T,{owner:X,name:Z,mimeType:W,size:$.size,createdAt:new Date().toISOString()}),B={body:G,threadId:Y},D=await this.checkUpload({name:Z,size:$.size,mimeType:W},J,B);if(D)throw new XQ(D.code||"upload_refused",D.message);let z=await this.attachmentDestination($,J,B),F=B9(z,Q.get("destination")),U=await this.attachmentScope(J,Y,{body:G}),N=F!=="provider"&&!U;if(N){if(F==="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()`.');U9()}if(F==="provider"||!U){let T=await L$(this.agent.provider,$);await H(T);let k={fileId:T,name:Z,mimeType:W,size:$.size,destination:"provider"};if(N)k.downgraded="no_scope";return k}let P=b$(),_=await this.attachmentStorage.put({name:v$(P,Z),body:$,contentType:W}),O=F==="both"?await L$(this.agent.provider,$):void 0;if(O)await H(O);let M={id:P,scopeKey:U.key,fileId:O,objectName:_,name:Z,mimeType:W,size:$.size,createdAt:new Date().toISOString(),destination:F};return await this.attachments.put(U,M),{fileId:O,attachmentId:P,name:Z,mimeType:W,size:$.size,destination:F}}async foreignFile(J,Q){let $=new Set(J.map((Z)=>Z.fileId).filter((Z)=>typeof Z==="string"));for(let Z of $){let W=await this.fileOwners.get(Z);if(W?W.owner!==null&&W.owner!==Q:this.requireKnownFiles)return D9()}return null}onMessage(J,Q){}onToolCall(J,Q){}onAwaitingInput(J,Q){}redactError(J,Q,$){return zQ(J,Q)}onError(J,Q){}onStreamComplete(J,Q){}reportHookFailure(J){console.error("[gemi/ai] agent controller hook failed",J)}async dispatchEvent(J,Q){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},Q);return;case"awaiting-input":await this.onAwaitingInput(J.pending,Q);return;case"error":await this.onError(x$(J.error),Q);return;default:return}}async readThread(J){let Q=await this.store.loadThread(J);return Q?(await this.settleThread(J,Q,{write:!1})).messages:null}isRunLive(J,Q){return this.liveRuns.get(J)!==null}async settleThread(J,Q,{write:$}){let Z=(Y)=>this.isRunLive(Y,J),W=await X$(Q,Z),G=W.messages,V=[],K=new Map(W.settled.map((Y)=>[Y.id,Y]));if(L9(G)||$)try{let Y=await z$(G,{threadId:J,store:w.store,isRunLive:Z,outputSchemaFor:(X)=>this.toolOutputSchema(X),scan:this.jobsBlockMax()});G=Y.messages,V=Y.jobs;for(let X of Y.settled)K.set(X.id,X);if($&&Y.orphans.length>0){await B$(w.store,Y.orphans,(H)=>this.reportHookFailure(H));let X=new Set(Y.orphans.map((H)=>H.id));V=V.map((H)=>X.has(H.id)?{...H,orphaned:!0}:H)}}catch(Y){this.reportHookFailure(Y)}if($&&K.size>0)try{await this.store.appendMessages(J,[...K.values()])}catch(Y){this.reportHookFailure(Y)}return{messages:G,jobs:V}}jobsBlockMax(){let J=this.agent.jobs?.contextBlock;if(J===!1)return 0;return J?.max??r}jobsBlock(J){return NQ(J,this.jobsBlockMax())}toolOutputSchema(J){let Q=($)=>{for(let Z of $){let W=Z;if(Array.isArray(W.tools)){let G=Q(W.tools);if(G)return G}else if(W.name===J)return W.outputSchema}return};return Q(this.agent.tools??[])}follow(J,Q){(async()=>{try{for await(let $ of J.frames())Q.frame($)}catch($){this.reportHookFailure($)}})()}persistRun(J,Q,$,Z=null,W={id:null,notified:Promise.resolve()}){let G=Promise.resolve(),V=(async()=>{let Y;try{Y=await J.result()}catch(H){Z?.close(),await Z?.settled(),G=W.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:H instanceof Error?H.message:String(H),retryable:!1},Q)));return}let X=Y.messages;if(Z?.close(X),await Z?.settled(),Q.threadId&&X.length>0)try{await this.store.appendMessages(Q.threadId,X)}catch(H){this.reportHookFailure(H)}G=this.notifyRun(Y,X,Q,W)})(),K=V.then(()=>F9(Promise.all([G,$]).then(()=>{}),this.hookHoldMs));return{stored:V,hooks:K}}async notifyRun(J,Q,$,Z){await Z.notified;for(let W of Q){if(W.id===Z.id)continue;await this.safely(()=>this.onMessage(W,$))}await this.safely(()=>this.onStreamComplete(J,$))}async safely(J){try{await J()}catch(Q){this.reportHookFailure(Q)}}}var VQ=["turn","clientRunId","threadId","messages","regenerate"],e3=["text","files","toolResults"];function g$(J,Q=c$(J)?VQ:[...VQ,...e3]){let $={};for(let[Z,W]of Object.entries(J)){if(Q.includes(Z))continue;Object.defineProperty($,Z,{value:W,writable:!0,enumerable:!0,configurable:!0})}return $}function J9(J){if(J===null)return{};let Q;if(typeof J==="string")try{Q=JSON.parse(J)}catch{throw new KQ("The upload's `body` field is not valid JSON.")}if(Q===null||typeof Q!=="object"||Array.isArray(Q))throw new KQ("The upload's `body` field must be a JSON object.");return g$(Q,VQ)}class KQ extends FJ{constructor(J){super(J);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:J}}},view:{}}}}async function L$(J,Q){try{return await J.upload(Q)}catch($){if($ instanceof h&&Q9.has($.status))throw new u$(R($).message);throw $}}var Q9=new Set([400,413,415,422]);class XQ extends FJ{constructor(J,Q){super(Q);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:J,message:Q}}},view:{}}}}function $9(J,Q,$,Z){if(!J)return null;let{maxBytes:W,accept:G}=J;if(typeof W==="number"&&Q.size>W)return{code:"file_too_large",message:`${JSON.stringify($)} is ${C$(Q.size)}; the limit is ${C$(W)}.`};if(G&&G.length>0&&!G.some((V)=>Z9(V,$,Z)))return{code:"unsupported_file_type",message:`${JSON.stringify($)} is not a type this chat accepts. Accepted: ${G.join(", ")}.`};return null}function Z9(J,Q,$){let Z=J.trim().toLowerCase();if(!Z)return!1;if(Z.startsWith("."))return Q.toLowerCase().endsWith(Z);let W=$.toLowerCase().split(";")[0].trim();if(Z.endsWith("/*"))return W.startsWith(Z.slice(0,-1));return W===Z}function C$(J){if(J<1024)return`${J} B`;let Q=["KB","MB","GB"],$=J/1024,Z=0;while($>=1024&&Z<Q.length-1)$/=1024,Z++;return`${Math.round($*10)/10} ${Q[Z]}`}class u$ extends FJ{constructor(J){super(J);this.name="RejectedUploadError";let Q=/(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:Q,message:J}}},view:{}}}}async function GQ(J,Q){let $=J?.rawRequest;if(!$||$.method==="GET"||$.method==="HEAD"||!$.body)return{body:{}};if(!W9($.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let Z=Number($.headers.get("Content-Length"));if(Number.isFinite(Z)&&Z>Q)return O$(Q);let W;try{let V=await G9($,Q);if(V===null)return O$(Q);W=V}catch{return{body:{},error:"The request body could not be read."}}if(!W.trim())return{body:{}};let G;try{G=JSON.parse(W)}catch{return{body:{},error:"The request body is not valid JSON."}}if(G===null||typeof G!=="object"||Array.isArray(G))return{body:{},error:"The request body must be a JSON object."};return{body:G}}function W9(J){return j$(J)==="application/json"}async function G9(J,Q){if(!Number.isFinite(Q)||!J.body)return await J.text();let $=J.body.getReader(),Z=[],W=0;for(;;){let{done:K,value:Y}=await $.read();if(K)break;if(W+=Y.byteLength,W>Q)return await $.cancel().catch(PJ),null;Z.push(Y)}let G=new Uint8Array(W),V=0;for(let K of Z)G.set(K,V),V+=K.byteLength;return new TextDecoder().decode(G)}function O$(J){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${J} bytes).`}}function YQ(J,Q,$){return j(J,{...NJ(T$(J),$,J),code:Q})}function BJ(J){if(J.status===413)return YQ(413,J.code??"body_too_large",J.error??"");return j(J.status??400,{code:J.code??"invalid_request",message:J.error})}function c$(J){return Boolean(J.turn)&&typeof J.turn==="object"}function V9(J){let Q=c$(J)?J.turn:J,$={};if(typeof Q.text==="string")$.text=Q.text;if(Array.isArray(Q.files)){let Z=K9(Q.files);if(typeof Z==="string")return{error:Z};$.files=Z}if(Array.isArray(Q.toolResults))$.toolResults=Q.toolResults;if(Object.keys($).length===0)return{};if(Q===J.turn&&Q.localId!==void 0&&Q.localId!==null&&Q.localId!==""){let{localId:Z}=Q;if(typeof Z!=="string")return{error:"turn.localId must be a string."};if(Z.length>_$)return{error:`turn.localId is longer than ${_$} characters.`};$.localId=Z}return{turn:$}}var _$=200;function K9(J){let Q=[];for(let[$,Z]of J.entries()){let W=`turn.files[${$}]`;if(!Z||typeof Z!=="object"||Array.isArray(Z))return`${W} must be an object.`;let G={};for(let H of["fileId","attachmentId","name","mimeType"]){let B=Z[H];if(B===void 0||B===null||B==="")continue;if(typeof B!=="string")return`${W}.${H} must be a string.`;G[H]=B}let{fileId:V,attachmentId:K,name:Y,mimeType:X}=G;if(V?.startsWith(b))return`${W}.fileId holds a gemi attachment id (${V}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(K!==void 0&&!K.startsWith(b))return`${W}.attachmentId is not a gemi attachment id: it must start with "${b}".`;if(!V&&!K)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;Q.push({...V?{fileId:V}:{},...K?{attachmentId:K}:{},...Y!==void 0?{name:Y}:{},...X!==void 0?{mimeType:X}:{}})}return Q}function X9(J,Q){if(typeof Q.from==="number"&&Number.isFinite(Q.from))return Math.max(0,Math.floor(Q.from));if(typeof Q.cursor==="number"&&Number.isFinite(Q.cursor)){let Z=Math.floor(Q.cursor);if(Z>=0)return Z+1;return}let $=J?.rawRequest?.headers?.get("Last-Event-ID");if($){let Z=Number.parseInt($,10);if(Number.isFinite(Z))return Math.max(0,Z+1)}return}function Y9(J,Q){let $=J?.search?.get(Q);return typeof $==="string"?$:void 0}function H9(J){let Q=BQ(J);for(let $=J.length-1;$>=0;$--){let Z=J[$];if(Z.role!=="user"||Q.has(Z.id))continue;let W="",G=[];for(let V of Z.content){if(V.type==="text")W+=V.text;if(V.type==="file")G.push({...V.fileId?{fileId:V.fileId}:{},...V.attachmentId?{attachmentId:V.attachmentId}:{},...V.name?{name:V.name}:{},...V.mimeType?{mimeType:V.mimeType}:{}})}if(!W&&G.length===0)continue;return{index:$,turn:{...W?{text:W}:{},...G.length>0?{files:G}:{}}}}return null}function S$(){return j(409,{code:"stopped",message:"The turn was stopped before it started."})}function UJ(){return j(403,NJ("permission","This run belongs to someone else.",403))}function D9(){return j(403,NJ("permission","A file in this turn was uploaded by someone else.",403))}function z9(J){if(!Array.isArray(J))return[];let Q=[];for(let $ of J){let Z=$?.content;if(!Array.isArray(Z))continue;for(let W of Z)if(W&&typeof W==="object"&&typeof W.fileId==="string")Q.push({fileId:W.fileId})}return Q}function j(J,Q){return new Response(JSON.stringify({error:Q}),{status:J,headers:{"Content-Type":"application/json"}})}function B9(J,Q){if(typeof Q!=="string"||Q.length===0)return J;if(Q!=="both"&&Q!=="provider"&&Q!=="storage")throw Error(`Unknown attachment destination "${Q}". Expected "both", "provider" or "storage".`);if(Q===J||J==="both"&&Q==="storage")return Q;if(J==="both"&&Q==="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 "${Q}" 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 M$=!1;function U9(){if(M$)return;M$=!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 P9=2147483647;function F9(J,Q){let $=J.then(()=>{},()=>{});if(!(Q<=P9))return $;let Z,W=new Promise((G)=>{Z=setTimeout(G,Q)});return Promise.race([$,W]).finally(()=>clearTimeout(Z))}var A$=!1;function N9(J){if(A$||Bun.env.NODE_ENV!=="production")return;if(!(J instanceof HQ))return;A$=!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 L9(J){return J.some((Q)=>Q.content.some(($)=>$.type==="tool-result"&&$.status==="running"))}export{j9 as windowMessages,S9 as turnStarts,d$ as toAgentTools,_9 as supportsStrict,M9 as splitTurns,b9 as settleSummaries,O9 as s,zQ as redactError,A9 as messageSize,sJ as liveRuns,QQ as keepSummary,BQ as injectedMessageIds,c9 as generate,x3 as evalChain,I9 as defaultSummaryStore,DQ as defaultNonceStore,aJ as defaultFileOwners,CJ as defaultAttachmentStore,$Q as defaultAgentStore,jJ as ToolNamespace,TJ as ToolError,f9 as Skill,LJ as ScopedAttachments,h9 as SKILLS_NAMESPACE,JQ as RedisReceiptStore,q$ as RedisNonceStore,v9 as PendingEscalation,lJ as OpenAIProvider,xJ as OpenAIImageProvider,w9 as MemorySummaryStore,eJ as MemoryReceiptStore,HQ as MemoryNonceStore,XJ as MemoryLiveRuns,YJ as MemoryFileOwners,KJ as MemoryCircuitStore,f$ as MemoryAttachmentStore,HJ as MemoryAgentStore,MQ as MemoryAgentJobStore,a as LiveRunNotFoundError,RQ as JobsRequireThreadError,AQ as JobHandle,C9 as JSONSchemaError,I$ as InvalidAttachmentScopeError,WJ as ImageRequestError,GJ as ImageProvider,kJ as ImageModel,l as FrameCursorEvictedError,s as FallbackProvider,AJ as DatabaseAgentJobStore,k9 as DEFAULT_MAX_SUMMARY_TOKENS,y9 as DEFAULT_MAX_RUN_DURATION_MS,TQ as DEFAULT_JOB_DEADLINE_MS,r as DEFAULT_JOBS_CONTEXT_MAX,R9 as DEFAULT_CONTEXT_WINDOW_STEP,T9 as DEFAULT_CONTEXT_WINDOW_NOTE,E9 as DEFAULT_COMPACT_TRIGGER_TOKENS,q9 as DEFAULT_COMPACT_INSTRUCTIONS,x9 as COMPACT_SUMMARY_HEADER,dJ as AzureOpenAIProvider,wJ as AzureOpenAIImageProvider,w$ as AttachmentNotFoundError,OJ as AgentTurnError,QJ as AgentTool,g9 as AgentRunError,m as AgentProvider,w as AgentJobs,_J as AgentJobDeadlineSweep,jQ as AgentJob,UQ as AgentController,u9 as Agent};
|
|
86
|
+
`)||void 0,O=await this.context(J,{body:V}),L=await this.attachmentsFor(J,Z,{body:V});if(H?.cancelled)return o$();let A=Z?new _Q(this.store,Z,P,(M)=>this.reportHookFailure(M)):null,R=`run_${crypto.randomUUID()}`,q={req:J,runId:R,threadId:Z},w={id:null,notified:Promise.resolve()},E=this.agent.stream({runId:R,messages:P,turn:G,threadId:Z,...A?{onMessage:(M)=>A.finish(M)}:{},onTurn:(M)=>{if(w.id!==null)return;w.id=M.id;let l=A?A.settled():Promise.resolve();w.notified=l.then(()=>this.safely(()=>this.onMessage(M,q)))},instructions:F,context:O,attachments:L,body:V,redactError:(M,l)=>this.redactError(M,l,q),nonces:this.nonces,receipts:this.receipts,subject:Y,...Z?{jobs:{owner:Y}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...Z&&V6(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==xQ.prototype.prepareStep?{prepareStep:(M)=>this.prepareStep(M,q)}:{}}),_=this.liveRuns.register(E,{threadId:Z,owner:Y,clientRunId:X,onEvent:(M)=>this.dispatchEvent(M,q),onInternalError:(M)=>this.reportHookFailure(M),maxRunDurationMs:this.agent.maxRunDurationMs});if(D=E,A)this.follow(E,A);let{stored:T,hooks:C}=this.persistRun(E,q,_,A,w);if(c$.set(E,T),KJ.has(J))KJ.set(J,{run:E,hooks:C});return J.ctx?.()?.waitUntil(C),E.toResponse()};try{await this.authorizeRequest(J,{route:"stream",threadId:Z,body:V});let P=await this.foreignFile([...G?.files??[],...Z?[]:s8($.messages)],Y);if(P)return P;if(H?.cancelled)return o$();let N=await this.runLimitKey(J,{owner:Y,threadId:Z}),F=N===null?jJ:v8(this.liveRuns).take(N,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!F)return RQ(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);try{return Z?await this.withThread(Z,Y,B):await B()}finally{let O=D;if(O)O.result().then(F,F);else F()}}finally{if(H&&RJ.get(X)===H)RJ.delete(X)}}async withThread(J,Q,$){let Z=kJ.get(J)??Promise.resolve(),W,G=new Promise((X)=>{W=X}),K=Z.then(()=>G);kJ.set(J,K),await Z;try{let X=await this.liveRuns.find({threadId:J});if(X&&this.liveRuns.isRunning(X.runId)&&!this.liveRuns.mayAccess(X.runId,Q))return YJ();let V=X?this.liveRuns.get(X.runId):null;if(V)V.stop({reason:"superseded by a later turn on this thread"}),await c$.get(V);return await $()}finally{if(W(),kJ.get(J)===K)kJ.delete(J)}}async attach(J=new x){let Q=await XJ(J,TJ);if(Q.error)return t(Q);let $=Q.body,Z=typeof $.threadId==="string"?$.threadId:n8(J,"threadId");if(!Z)return S(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(J,{route:"attach",threadId:Z});let W=await this.liveRuns.find({threadId:Z});if(W&&!this.liveRuns.mayAccess(W.runId,await this.runOwner(J)))return YJ();if(!W)return S(404,{code:"no_live_run",message:`No run in progress for thread ${Z} in this process.`});let G=typeof $.runId==="string"?$.runId:void 0,K=G&&G!==W.runId?void 0:i8(J,$);try{return Q6(this.liveRuns.replay(W.runId,K))}catch(X){if(X instanceof s)return S(410,{code:X.code,message:X.message,oldestSeq:X.oldest});if(X instanceof GJ)return S(404,{code:X.code,message:X.message});throw X}}async stop(J=new x){let Q=await XJ(J,TJ);if(Q.error)return t(Q);let $=Q.body;await this.authorizeRequest(J,{route:"stop",threadId:typeof $.threadId==="string"?$.threadId:void 0});let Z=await this.runOwner(J),W=typeof $.runId==="string"?$.runId:void 0;if(!W&&typeof $.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId($.clientRunId)??void 0,!W){let K=RJ.get($.clientRunId);if(K){if(K.owner!==null&&K.owner!==Z)return YJ();return K.cancelled=!0,{stopped:!0}}}}if(!W&&typeof $.threadId==="string")W=(await this.liveRuns.find({threadId:$.threadId}))?.runId;let G=W?this.liveRuns.get(W):null;if(!G)return{stopped:!1};if(!this.liveRuns.mayAccess(G.runId,Z))return YJ();return G.stop({reason:typeof $.reason==="string"?$.reason:void 0}),{stopped:!0}}attachmentScope(J,Q,$){let Z=J.ctx()?.user,W=Z?.id??Z?.publicId;if(W!==void 0&&W!==null&&String(W)!=="")return{key:`user:${String(W)}`};if(Q)return{key:`thread:${Q}`};return null}attachmentLimits(J){return null}checkUpload(J,Q,$){}attachmentDestination(J,Q,$){return"both"}async attachmentsFor(J,Q,$={body:{}}){let Z=await this.attachmentScope(J,Q,$);if(!Z)return null;return new wJ(this.attachments,this.attachmentStorage,Z)}async voiceStart(J=new x){let Q=this.voice;if(!Q)return SQ();let $=await XJ(J,TJ);if($.error)return t($);let{sdp:Z,threadId:W,pushToTalk:G}=$.body;if(typeof Z!=="string"||!Z.trimStart().startsWith("v="))return S(400,{code:"invalid_request",message:"`sdp` must be the browser's SDP offer."});let K=qJ($.body,t8),X=typeof W==="string"&&W!==""?W:void 0;await this.authorizeRequest(J,{route:"stream",threadId:X,body:K});let V=J.ctx?.()?.user??null,Y=await Q.start({req:J,body:K,threadId:X,user:V,pushToTalk:G===!0}),H=Date.now(),D,z=async(O)=>{if(O!==void 0)console.error("[gemi/ai] a voice session could not start.",O);if(D)await Q.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??X??"",reason:"start_failed",startedAt:H,endedAt:Date.now(),durationMs:0,seconds:0,usage:j(),transcription:{usage:j(),seconds:0},transcript:[],requests:[],toolCalls:[],errors:[]})}catch(L){console.error("[gemi/ai] a voice session's onEnd threw.",L)}},B=Y.threadId??X;if(!B)return await z(void 0),S(400,{code:"invalid_request",message:"A voice session needs a thread: send `threadId`, or answer one from `voice.start`."});try{if(B!==X)await this.authorizeRequest(J,{route:"stream",threadId:B,body:K})}catch(O){throw await z(void 0),O}let U=crypto.randomUUID(),P=Y.tools??[];try{if(Y.mcp)P=[...P,...await YQ(Y.mcp,{user:V,sessionId:U})]}catch(O){return await z(O),S(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}let N={...Y.session,tools:[...ZJ(Q.delegate),...Y.session?.tools??[],...P.map((O)=>O.tool)],...G===!0?{turnDetection:null}:{}},F;try{F=await Q.realtime.createCall({sdp:Z,session:N,safetyIdentifier:Y.safetyIdentifier})}catch(O){await z(O);let L=O instanceof f&&O.code==="rate_limited";return S(L?429:502,{code:"voice_unavailable",message:"Voice isn't available right now."})}D=F.callId;try{await this.voiceStore.create({id:U,callId:F.callId,threadId:B,owner:await this.runOwner(J),body:K,startedAt:H});let{threadId:O,session:L,safetyIdentifier:A,mcp:R,tools:q,...w}=Y;return{sessionId:m.start({...w,tools:P,controller:this.constructor,threadId:B,user:V,body:K,call:{realtime:Q.realtime,callId:F.callId},sessionId:U,store:this.voiceStore,liveRuns:this.liveRuns,delegate:Q.delegate,session:N}).sessionId,sdp:F.sdpAnswer,threadId:B,delegate:Q.delegate?.name??WJ,endsAt:H+(Y.limits?.maxDurationMs??900000)}}catch(O){return await z(O),S(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}}async voiceUpdate(J=new x){if(!this.voice)return SQ();let Q=await this.voiceSession(J);if(Q instanceof Response)return Q;let $=await XJ(J,TJ);if($.error)return t($);let Z=qJ($.body,[]);if(await this.authorizeRequest(J,{route:"stream",threadId:Q.threadId,body:Z}),Q.endedAt!==void 0)return S(409,{code:"voice_ended",message:"This voice session has ended."});return await this.voiceStore.update(Q.id,{body:Z}),m.get(Q.id)?.setBody(Z),{updated:!0}}async voiceEnd(J=new x){let Q=this.voice;if(!Q)return SQ();let $=await this.voiceSession(J);if($ instanceof Response)return $;if(await this.authorizeRequest(J,{route:"stream",threadId:$.threadId,body:$.body}),$.endedAt!==void 0)return{ended:!1};let Z=m.get($.id);if(Z)await Z.end("hangup");else await Q.realtime.hangup($.callId),await this.voiceStore.update($.id,{endedAt:Date.now(),endReason:"hangup"});return{ended:!0}}async voiceSession(J){let Q=J.params?.sessionId,$=typeof Q==="string"&&Q?await this.voiceStore.get(Q):null;if(!$)return S(404,{code:"voice_not_found",message:"No such voice session."});if($.owner!==null&&$.owner!==await this.runOwner(J))return YJ();return $}async upload(J=new x){let Q=await J.rawRequest.formData(),$=Q.get("file");if(!($ instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let Z=$ instanceof File&&$.name?$.name:"upload",W=$.type||"application/octet-stream",G=y8(Q.get("body")),K=Q.get("threadId");await this.authorizeRequest(J,{route:"upload",threadId:typeof K==="string"&&K.length>0?K:void 0,body:G});let X=u8(await this.attachmentLimits(J),$,Z,W);if(X)throw new kQ(X.code,X.message);let V=typeof K==="string"&&K.length>0&&await this.store.loadThread(K)!==null?K:void 0,Y=await this.runOwner(J),H=(R)=>this.fileOwners.record(R,{owner:Y,name:Z,mimeType:W,size:$.size,createdAt:new Date().toISOString()}),D={body:G,threadId:V},z=await this.checkUpload({name:Z,size:$.size,mimeType:W},J,D);if(z)throw new kQ(z.code||"upload_refused",z.message);let B=await this.attachmentDestination($,J,D),U=r8(B,Q.get("destination")),P=await this.attachmentScope(J,V,{body:G}),N=U!=="provider"&&!P;if(N){if(U==="storage")throw Error('This upload was routed to storage, but `attachmentScope()` returned null for the request, so there is no subject to file the attachment under. Guard the route (`this.agent(Chat).middleware({ upload: "auth" })`), send a `threadId` with the upload, or override `attachmentScope()`.');e8()}if(U==="provider"||!P){let R=await l$(this.agent.provider,$);await H(R);let q={fileId:R,name:Z,mimeType:W,size:$.size,destination:"provider"};if(N)q.downgraded="no_scope";return q}let F=K6(),O=await this.attachmentStorage.put({name:X6(F,Z),body:$,contentType:W}),L=U==="both"?await l$(this.agent.provider,$):void 0;if(L)await H(L);let A={id:F,scopeKey:P.key,fileId:L,objectName:O,name:Z,mimeType:W,size:$.size,createdAt:new Date().toISOString(),destination:U};return await this.attachments.put(P,A),{fileId:L,attachmentId:F,name:Z,mimeType:W,size:$.size,destination:U}}async foreignFile(J,Q){let $=new Set(J.map((Z)=>Z.fileId).filter((Z)=>typeof Z==="string"));for(let Z of $){let W=await this.fileOwners.get(Z);if(W?W.owner!==null&&W.owner!==Q:this.requireKnownFiles)return a8()}return null}onMessage(J,Q){}onToolCall(J,Q){}onAwaitingInput(J,Q){}redactError(J,Q,$){return qQ(J,Q)}onError(J,Q){}onStreamComplete(J,Q){}reportHookFailure(J){console.error("[gemi/ai] agent controller hook failed",J)}async dispatchEvent(J,Q){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},Q);return;case"awaiting-input":await this.onAwaitingInput(J.pending,Q);return;case"error":await this.onError(Z6(J.error),Q);return;default:return}}async readThread(J){let Q=await this.store.loadThread(J);return Q?(await this.settleThread(J,Q,{write:!1})).messages:null}isRunLive(J,Q){return this.liveRuns.get(J)!==null}async settleThread(J,Q,{write:$}){let Z=(V)=>this.isRunLive(V,J),W=await f$(Q,Z),G=W.messages,K=[],X=new Map(W.settled.map((V)=>[V.id,V]));if(Z9(G)||$)try{let V=await g$(G,{threadId:J,store:v.store,isRunLive:Z,outputSchemaFor:(Y)=>this.toolOutputSchema(Y),scan:this.jobsBlockMax()});G=V.messages,K=V.jobs;for(let Y of V.settled)X.set(Y.id,Y);if($&&V.orphans.length>0){await u$(v.store,V.orphans,(H)=>this.reportHookFailure(H));let Y=new Set(V.orphans.map((H)=>H.id));K=K.map((H)=>Y.has(H.id)?{...H,orphaned:!0}:H)}}catch(V){this.reportHookFailure(V)}if($&&X.size>0)try{await this.store.appendMessages(J,[...X.values()])}catch(V){this.reportHookFailure(V)}return{messages:G,jobs:K}}jobsBlockMax(){let J=this.agent.jobs?.contextBlock;if(J===!1)return 0;return J?.max??VJ}jobsBlock(J){return bQ(J,this.jobsBlockMax())}toolOutputSchema(J){let Q=($)=>{for(let Z of $){let W=Z;if(Array.isArray(W.tools)){let G=Q(W.tools);if(G)return G}else if(W.name===J)return W.outputSchema}return};return Q(this.agent.tools??[])}follow(J,Q){(async()=>{try{for await(let $ of J.frames())Q.frame($)}catch($){this.reportHookFailure($)}})()}persistRun(J,Q,$,Z=null,W={id:null,notified:Promise.resolve()}){let G=Promise.resolve(),K=(async()=>{let V;try{V=await J.result()}catch(H){Z?.close(),await Z?.settled(),G=W.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:H instanceof Error?H.message:String(H),retryable:!1},Q)));return}let Y=V.messages;if(Z?.close(Y),await Z?.settled(),Q.threadId&&Y.length>0)try{await this.store.appendMessages(Q.threadId,Y)}catch(H){this.reportHookFailure(H)}G=this.notifyRun(V,Y,Q,W)})(),X=K.then(()=>Q9(Promise.all([G,$]).then(()=>{}),this.hookHoldMs));return{stored:K,hooks:X}}async notifyRun(J,Q,$,Z){await Z.notified;for(let W of Q){if(W.id===Z.id)continue;await this.safely(()=>this.onMessage(W,$))}await this.safely(()=>this.onStreamComplete(J,$))}async safely(J){try{await J()}catch(Q){this.reportHookFailure(Q)}}}var MQ=["turn","clientRunId","threadId","messages","regenerate"],h8=["text","files","toolResults"];function qJ(J,Q=D6(J)?MQ:[...MQ,...h8]){let $={};for(let[Z,W]of Object.entries(J)){if(Q.includes(Z))continue;Object.defineProperty($,Z,{value:W,writable:!0,enumerable:!0,configurable:!0})}return $}function y8(J){if(J===null)return{};let Q;if(typeof J==="string")try{Q=JSON.parse(J)}catch{throw new AQ("The upload's `body` field is not valid JSON.")}if(Q===null||typeof Q!=="object"||Array.isArray(Q))throw new AQ("The upload's `body` field must be a JSON object.");return qJ(Q,MQ)}class AQ extends EJ{constructor(J){super(J);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:J}}},view:{}}}}async function l$(J,Q){try{return await J.upload(Q)}catch($){if($ instanceof I&&g8.has($.status))throw new z6(k($).message);throw $}}var g8=new Set([400,413,415,422]);class kQ extends EJ{constructor(J,Q){super(Q);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:J,message:Q}}},view:{}}}}function u8(J,Q,$,Z){if(!J)return null;let{maxBytes:W,accept:G}=J;if(typeof W==="number"&&Q.size>W)return{code:"file_too_large",message:`${JSON.stringify($)} is ${d$(Q.size)}; the limit is ${d$(W)}.`};if(G&&G.length>0&&!G.some((K)=>c8(K,$,Z)))return{code:"unsupported_file_type",message:`${JSON.stringify($)} is not a type this chat accepts. Accepted: ${G.join(", ")}.`};return null}function c8(J,Q,$){let Z=J.trim().toLowerCase();if(!Z)return!1;if(Z.startsWith("."))return Q.toLowerCase().endsWith(Z);let W=$.toLowerCase().split(";")[0].trim();if(Z.endsWith("/*"))return W.startsWith(Z.slice(0,-1));return W===Z}function d$(J){if(J<1024)return`${J} B`;let Q=["KB","MB","GB"],$=J/1024,Z=0;while($>=1024&&Z<Q.length-1)$/=1024,Z++;return`${Math.round($*10)/10} ${Q[Z]}`}class z6 extends EJ{constructor(J){super(J);this.name="RejectedUploadError";let Q=/(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:Q,message:J}}},view:{}}}}async function XJ(J,Q){let $=J?.rawRequest;if(!$||$.method==="GET"||$.method==="HEAD"||!$.body)return{body:{}};if(!m8($.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let Z=Number($.headers.get("Content-Length"));if(Number.isFinite(Z)&&Z>Q)return i$(Q);let W;try{let K=await p8($,Q);if(K===null)return i$(Q);W=K}catch{return{body:{},error:"The request body could not be read."}}if(!W.trim())return{body:{}};let G;try{G=JSON.parse(W)}catch{return{body:{},error:"The request body is not valid JSON."}}if(G===null||typeof G!=="object"||Array.isArray(G))return{body:{},error:"The request body must be a JSON object."};return{body:G}}function m8(J){return e$(J)==="application/json"}async function p8(J,Q){if(!Number.isFinite(Q)||!J.body)return await J.text();let $=J.body.getReader(),Z=[],W=0;for(;;){let{done:X,value:V}=await $.read();if(X)break;if(W+=V.byteLength,W>Q)return await $.cancel().catch(jJ),null;Z.push(V)}let G=new Uint8Array(W),K=0;for(let X of Z)G.set(X,K),K+=X.byteLength;return new TextDecoder().decode(G)}function i$(J){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${J} bytes).`}}function RQ(J,Q,$){return S(J,{...xJ(r$(J),$,J),code:Q})}function t(J){if(J.status===413)return RQ(413,J.code??"body_too_large",J.error??"");return S(J.status??400,{code:J.code??"invalid_request",message:J.error})}function D6(J){return Boolean(J.turn)&&typeof J.turn==="object"}function l8(J){let Q=D6(J)?J.turn:J,$={};if(typeof Q.text==="string")$.text=Q.text;if(Array.isArray(Q.files)){let Z=d8(Q.files);if(typeof Z==="string")return{error:Z};$.files=Z}if(Array.isArray(Q.toolResults))$.toolResults=Q.toolResults;if(Object.keys($).length===0)return{};if(Q===J.turn&&Q.localId!==void 0&&Q.localId!==null&&Q.localId!==""){let{localId:Z}=Q;if(typeof Z!=="string")return{error:"turn.localId must be a string."};if(Z.length>n$)return{error:`turn.localId is longer than ${n$} characters.`};$.localId=Z}return{turn:$}}var n$=200;function d8(J){let Q=[];for(let[$,Z]of J.entries()){let W=`turn.files[${$}]`;if(!Z||typeof Z!=="object"||Array.isArray(Z))return`${W} must be an object.`;let G={};for(let H of["fileId","attachmentId","name","mimeType"]){let D=Z[H];if(D===void 0||D===null||D==="")continue;if(typeof D!=="string")return`${W}.${H} must be a string.`;G[H]=D}let{fileId:K,attachmentId:X,name:V,mimeType:Y}=G;if(K?.startsWith(c))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(X!==void 0&&!X.startsWith(c))return`${W}.attachmentId is not a gemi attachment id: it must start with "${c}".`;if(!K&&!X)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;Q.push({...K?{fileId:K}:{},...X?{attachmentId:X}:{},...V!==void 0?{name:V}:{},...Y!==void 0?{mimeType:Y}:{}})}return Q}function i8(J,Q){if(typeof Q.from==="number"&&Number.isFinite(Q.from))return Math.max(0,Math.floor(Q.from));if(typeof Q.cursor==="number"&&Number.isFinite(Q.cursor)){let Z=Math.floor(Q.cursor);if(Z>=0)return Z+1;return}let $=J?.rawRequest?.headers?.get("Last-Event-ID");if($){let Z=Number.parseInt($,10);if(Number.isFinite(Z))return Math.max(0,Z+1)}return}function n8(J,Q){let $=J?.search?.get(Q);return typeof $==="string"?$:void 0}function o8(J){let Q=EQ(J);for(let $=J.length-1;$>=0;$--){let Z=J[$];if(Z.role!=="user"||Q.has(Z.id))continue;let W="",G=[];for(let K of Z.content){if(K.type==="text")W+=K.text;if(K.type==="file")G.push({...K.fileId?{fileId:K.fileId}:{},...K.attachmentId?{attachmentId:K.attachmentId}:{},...K.name?{name:K.name}:{},...K.mimeType?{mimeType:K.mimeType}:{}})}if(!W&&G.length===0)continue;return{index:$,turn:{...W?{text:W}:{},...G.length>0?{files:G}:{}}}}return null}function o$(){return S(409,{code:"stopped",message:"The turn was stopped before it started."})}function YJ(){return S(403,xJ("permission","This run belongs to someone else.",403))}function a8(){return S(403,xJ("permission","A file in this turn was uploaded by someone else.",403))}function s8(J){if(!Array.isArray(J))return[];let Q=[];for(let $ of J){let Z=$?.content;if(!Array.isArray(Z))continue;for(let W of Z)if(W&&typeof W==="object"&&typeof W.fileId==="string")Q.push({fileId:W.fileId})}return Q}var t8=["sdp","threadId","pushToTalk"];function SQ(){return S(404,{code:"voice_not_enabled",message:"This agent has no voice: set `voice` on its controller."})}function S(J,Q){return new Response(JSON.stringify({error:Q}),{status:J,headers:{"Content-Type":"application/json"}})}function r8(J,Q){if(typeof Q!=="string"||Q.length===0)return J;if(Q!=="both"&&Q!=="provider"&&Q!=="storage")throw Error(`Unknown attachment destination "${Q}". Expected "both", "provider" or "storage".`);if(Q===J||J==="both"&&Q==="storage")return Q;if(J==="both"&&Q==="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 "${Q}" 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 a$=!1;function e8(){if(a$)return;a$=!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 J9=2147483647;function Q9(J,Q){let $=J.then(()=>{},()=>{});if(!(Q<=J9))return $;let Z,W=new Promise((G)=>{Z=setTimeout(G,Q)});return Promise.race([$,W]).finally(()=>clearTimeout(Z))}var s$=!1;function $9(J){if(s$||Bun.env.NODE_ENV!=="production")return;if(!(J instanceof TQ))return;s$=!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 Z9(J){return J.some((Q)=>Q.content.some(($)=>$.type==="tool-result"&&$.status==="running"))}export{D9 as windowMessages,ZJ as voiceTools,X9 as turnStarts,FJ as toRealtimeUsage,U6 as toAgentTools,K9 as supportsStrict,Y9 as splitTurns,L9 as settleSummaries,G9 as s,qQ as redactError,V9 as messageSize,YQ as mcpVoiceTools,DQ as liveRuns,OQ as keepSummary,O$ as isCallNotFound,EQ as injectedMessageIds,R9 as generate,H8 as evalChain,HQ as defaultVoiceStore,O9 as defaultSummaryStore,jQ as defaultNonceStore,BQ as defaultFileOwners,IJ as defaultAttachmentStore,LQ as defaultAgentStore,_J as VoiceHangup,m as VoiceBridge,uJ as ToolNamespace,y as ToolError,_9 as Skill,wJ as ScopedAttachments,S9 as SKILLS_NAMESPACE,NQ as RedisReceiptStore,$6 as RedisNonceStore,UJ as RealtimeSideband,f as RealtimeRequestError,QJ as RealtimeClient,C9 as PendingEscalation,WQ as OpenAIProvider,lJ as OpenAIImageProvider,VQ as MemoryVoiceSessionStore,N9 as MemorySummaryStore,UQ as MemoryReceiptStore,TQ as MemoryNonceStore,SJ as MemoryLiveRuns,MJ as MemoryFileOwners,LJ as MemoryCircuitStore,Y6 as MemoryAttachmentStore,AJ as MemoryAgentStore,uQ as MemoryAgentJobStore,GJ as LiveRunNotFoundError,mQ as JobsRequireThreadError,cQ as JobHandle,W9 as JSONSchemaError,G6 as InvalidAttachmentScopeError,BJ as ImageRequestError,PJ as ImageProvider,cJ as ImageModel,s as FrameCursorEvictedError,$J as FallbackProvider,yJ as DatabaseAgentJobStore,B9 as DEFAULT_MAX_SUMMARY_TOKENS,M9 as DEFAULT_MAX_RUN_DURATION_MS,pQ as DEFAULT_JOB_DEADLINE_MS,VJ as DEFAULT_JOBS_CONTEXT_MAX,WJ as DEFAULT_DELEGATE_NAME,H9 as DEFAULT_CONTEXT_WINDOW_STEP,z9 as DEFAULT_CONTEXT_WINDOW_NOTE,P9 as DEFAULT_COMPACT_TRIGGER_TOKENS,F9 as DEFAULT_COMPACT_INSTRUCTIONS,U9 as COMPACT_SUMMARY_HEADER,GQ as AzureOpenAIProvider,dJ as AzureOpenAIImageProvider,W6 as AttachmentNotFoundError,bJ as AgentTurnError,DJ as AgentTool,A9 as AgentRunError,a as AgentProvider,v as AgentJobs,fJ as AgentJobDeadlineSweep,lQ as AgentJob,xQ as AgentController,k9 as Agent};
|
|
87
87
|
|
|
88
|
-
//# debugId=
|
|
88
|
+
//# debugId=98C735A23323E71C64756E2164756E21
|