gemi 0.63.0 → 0.65.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/Agent.d.ts +73 -0
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/AgentController.d.ts +75 -6
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/AgentProvider.d.ts +5 -1
- package/dist/ai/AgentProvider.d.ts.map +1 -1
- package/dist/ai/Schema.d.ts +62 -0
- package/dist/ai/Schema.d.ts.map +1 -1
- package/dist/ai/client/index.js +10 -4
- package/dist/ai/client/index.js.map +1 -1
- package/dist/ai/client/reducer.d.ts.map +1 -1
- package/dist/ai/index.d.ts +2 -1
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +12 -12
- package/dist/ai/index.js.map +6 -6
- package/dist/ai/live/harness.d.ts +5 -3
- package/dist/ai/live/harness.d.ts.map +1 -1
- package/dist/ai/types.d.ts +29 -1
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/useChat.d.ts +60 -4
- package/dist/ai/useChat.d.ts.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/auth/AuthController.d.ts.map +1 -1
- package/dist/auth/AuthManager.d.ts +38 -4
- package/dist/auth/AuthManager.d.ts.map +1 -1
- package/dist/auth/UserProvider.d.ts.map +1 -1
- package/dist/auth/config.d.ts.map +1 -1
- package/dist/auth/sessionToken.d.ts +38 -0
- package/dist/auth/sessionToken.d.ts.map +1 -0
- package/dist/auth/types.d.ts +1 -1
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/bin/gemi.js +9 -1
- package/dist/bin/gemi.js.map +3 -3
- package/dist/broadcasting/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-jv9k1qfr.js → chunk-2bb3rdqq.js} +3 -3
- package/dist/{chunk-jv9k1qfr.js.map → chunk-2bb3rdqq.js.map} +1 -1
- package/dist/{chunk-e785380d.js → chunk-2dvjj3ad.js} +2 -2
- package/dist/{chunk-e785380d.js.map → chunk-2dvjj3ad.js.map} +1 -1
- package/dist/{chunk-rj3fnc4h.js → chunk-2ghpxrw1.js} +1 -1
- package/dist/{chunk-dqbm9vd0.js → chunk-3mp9p38x.js} +2 -2
- package/dist/{chunk-dqbm9vd0.js.map → chunk-3mp9p38x.js.map} +1 -1
- package/dist/{chunk-cdpeh7tt.js → chunk-3pwn2r6s.js} +2 -2
- package/dist/{chunk-cdpeh7tt.js.map → chunk-3pwn2r6s.js.map} +1 -1
- package/dist/{chunk-7qfzrkab.js → chunk-45g3hd0e.js} +2 -2
- package/dist/{chunk-7qfzrkab.js.map → chunk-45g3hd0e.js.map} +1 -1
- package/dist/{chunk-wqmzad46.js → chunk-5g1j29p2.js} +2 -2
- package/dist/{chunk-wqmzad46.js.map → chunk-5g1j29p2.js.map} +1 -1
- package/dist/{chunk-bxtx4y4w.js → chunk-5pm9zvtp.js} +2 -2
- package/dist/{chunk-bxtx4y4w.js.map → chunk-5pm9zvtp.js.map} +1 -1
- package/dist/{chunk-pbx9p6g0.js → chunk-6waph5k8.js} +1 -1
- package/dist/{chunk-nnc40mf3.js → chunk-70y8wajy.js} +2 -2
- package/dist/{chunk-nnc40mf3.js.map → chunk-70y8wajy.js.map} +1 -1
- package/dist/{chunk-71yhw8aw.js → chunk-731etrh2.js} +2 -2
- package/dist/{chunk-71yhw8aw.js.map → chunk-731etrh2.js.map} +1 -1
- package/dist/{chunk-1s1cd1e8.js → chunk-7438nrkm.js} +3 -3
- package/dist/{chunk-1s1cd1e8.js.map → chunk-7438nrkm.js.map} +1 -1
- package/dist/{chunk-ssg20z9s.js → chunk-7wgk7q33.js} +3 -3
- package/dist/{chunk-ssg20z9s.js.map → chunk-7wgk7q33.js.map} +1 -1
- package/dist/chunk-7xc64j6p.js +5 -0
- package/dist/chunk-7xc64j6p.js.map +14 -0
- package/dist/{chunk-jmse5hec.js → chunk-7zg1mt1g.js} +2 -2
- package/dist/{chunk-jmse5hec.js.map → chunk-7zg1mt1g.js.map} +1 -1
- package/dist/{chunk-0qchadp1.js → chunk-87c0cy5v.js} +2 -2
- package/dist/{chunk-0qchadp1.js.map → chunk-87c0cy5v.js.map} +1 -1
- package/dist/{chunk-773qa4av.js → chunk-8bjxk57p.js} +2 -2
- package/dist/{chunk-773qa4av.js.map → chunk-8bjxk57p.js.map} +1 -1
- package/dist/{chunk-81yzec62.js → chunk-8jpvj3cj.js} +2 -2
- package/dist/{chunk-81yzec62.js.map → chunk-8jpvj3cj.js.map} +1 -1
- package/dist/{chunk-9e5c5e15.js → chunk-9ch1q7nd.js} +2 -2
- package/dist/{chunk-9e5c5e15.js.map → chunk-9ch1q7nd.js.map} +1 -1
- package/dist/{chunk-9e5v1t73.js → chunk-9x5eefh0.js} +2 -2
- package/dist/{chunk-9e5v1t73.js.map → chunk-9x5eefh0.js.map} +1 -1
- package/dist/{chunk-62xjrz5e.js → chunk-9zmcz7yq.js} +2 -2
- package/dist/{chunk-62xjrz5e.js.map → chunk-9zmcz7yq.js.map} +1 -1
- package/dist/{chunk-0amv13g6.js → chunk-a85fn4zf.js} +3 -3
- package/dist/{chunk-0amv13g6.js.map → chunk-a85fn4zf.js.map} +1 -1
- package/dist/chunk-adj6dnvj.js +5 -0
- package/dist/{chunk-dq2hgzje.js.map → chunk-adj6dnvj.js.map} +1 -1
- package/dist/{chunk-exwbtfe9.js → chunk-aq09ta7k.js} +2 -2
- package/dist/{chunk-exwbtfe9.js.map → chunk-aq09ta7k.js.map} +1 -1
- package/dist/{chunk-43xw9n4f.js → chunk-dmr7yzyr.js} +2 -2
- package/dist/{chunk-43xw9n4f.js.map → chunk-dmr7yzyr.js.map} +1 -1
- package/dist/{chunk-q4wdg0y3.js → chunk-e0v4byjp.js} +2 -2
- package/dist/{chunk-ptjexzn1.js.map → chunk-e0v4byjp.js.map} +1 -1
- package/dist/{chunk-8wpccvbt.js → chunk-e1fkxt82.js} +2 -2
- package/dist/{chunk-8wpccvbt.js.map → chunk-e1fkxt82.js.map} +1 -1
- package/dist/{chunk-xadk41cs.js → chunk-ex9ns7pf.js} +4 -4
- package/dist/{chunk-xadk41cs.js.map → chunk-ex9ns7pf.js.map} +1 -1
- package/dist/{chunk-95d8jj11.js → chunk-fd7wfcft.js} +2 -2
- package/dist/{chunk-95d8jj11.js.map → chunk-fd7wfcft.js.map} +1 -1
- package/dist/{chunk-maxd55a0.js → chunk-fk127cwf.js} +2 -2
- package/dist/{chunk-maxd55a0.js.map → chunk-fk127cwf.js.map} +2 -2
- package/dist/{chunk-kx7vgcjp.js → chunk-fmcq21hg.js} +3 -3
- package/dist/{chunk-kx7vgcjp.js.map → chunk-fmcq21hg.js.map} +1 -1
- package/dist/{chunk-k1wkvrj0.js → chunk-ftaxfq7p.js} +3 -3
- package/dist/{chunk-k1wkvrj0.js.map → chunk-ftaxfq7p.js.map} +1 -1
- package/dist/{chunk-zdj2wmbj.js → chunk-fxkh2rfd.js} +2 -2
- package/dist/{chunk-zdj2wmbj.js.map → chunk-fxkh2rfd.js.map} +1 -1
- package/dist/{chunk-9k5daets.js → chunk-g2ywq30n.js} +2 -2
- package/dist/{chunk-9k5daets.js.map → chunk-g2ywq30n.js.map} +1 -1
- package/dist/chunk-hq496pa4.js +5 -0
- package/dist/chunk-hq496pa4.js.map +10 -0
- package/dist/{chunk-4sv5zpb4.js → chunk-hrtkjv41.js} +2 -2
- package/dist/{chunk-4sv5zpb4.js.map → chunk-hrtkjv41.js.map} +1 -1
- package/dist/{chunk-tq92xqkk.js → chunk-j3b3qerv.js} +2 -2
- package/dist/{chunk-tq92xqkk.js.map → chunk-j3b3qerv.js.map} +1 -1
- package/dist/{chunk-dhe1hsyz.js → chunk-jkjt3e06.js} +2 -2
- package/dist/{chunk-dhe1hsyz.js.map → chunk-jkjt3e06.js.map} +1 -1
- package/dist/{chunk-5wzyx4ts.js → chunk-ks94h71z.js} +2 -2
- package/dist/{chunk-5wzyx4ts.js.map → chunk-ks94h71z.js.map} +1 -1
- package/dist/{chunk-rhr8qavq.js → chunk-m44ar4he.js} +2 -2
- package/dist/{chunk-rhr8qavq.js.map → chunk-m44ar4he.js.map} +1 -1
- package/dist/{chunk-0081bz9c.js → chunk-nxg51m0q.js} +2 -2
- package/dist/{chunk-0081bz9c.js.map → chunk-nxg51m0q.js.map} +1 -1
- package/dist/{chunk-qrfp7pg2.js → chunk-nxh5a3eb.js} +3 -3
- package/dist/{chunk-qrfp7pg2.js.map → chunk-nxh5a3eb.js.map} +1 -1
- package/dist/{chunk-qcbtr7hm.js → chunk-p0m3qgs5.js} +2 -2
- package/dist/{chunk-qcbtr7hm.js.map → chunk-p0m3qgs5.js.map} +1 -1
- package/dist/{chunk-jk8mn861.js → chunk-p5m0da00.js} +2 -2
- package/dist/{chunk-jk8mn861.js.map → chunk-p5m0da00.js.map} +1 -1
- package/dist/{chunk-fv223805.js → chunk-pb0m0ryf.js} +3 -3
- package/dist/{chunk-fv223805.js.map → chunk-pb0m0ryf.js.map} +1 -1
- package/dist/{chunk-7hbhbht2.js → chunk-pcxxnnad.js} +3 -3
- package/dist/{chunk-7hbhbht2.js.map → chunk-pcxxnnad.js.map} +1 -1
- package/dist/{chunk-2d92pev2.js → chunk-pxc51549.js} +2 -2
- package/dist/{chunk-2d92pev2.js.map → chunk-pxc51549.js.map} +1 -1
- package/dist/{chunk-454c7vn3.js → chunk-q1nq7n6y.js} +2 -2
- package/dist/{chunk-454c7vn3.js.map → chunk-q1nq7n6y.js.map} +1 -1
- package/dist/{chunk-48qybp63.js → chunk-qqchc40s.js} +2 -2
- package/dist/{chunk-48qybp63.js.map → chunk-qqchc40s.js.map} +1 -1
- package/dist/{chunk-feyr4851.js → chunk-r069158p.js} +2 -2
- package/dist/{chunk-feyr4851.js.map → chunk-r069158p.js.map} +1 -1
- package/dist/{chunk-ptjexzn1.js → chunk-r6v21jn6.js} +2 -2
- package/dist/{chunk-q4wdg0y3.js.map → chunk-r6v21jn6.js.map} +1 -1
- package/dist/{chunk-6j129573.js → chunk-r77f1482.js} +2 -2
- package/dist/{chunk-6j129573.js.map → chunk-r77f1482.js.map} +1 -1
- package/dist/{chunk-jmbdr550.js → chunk-rnjbja88.js} +2 -2
- package/dist/{chunk-jmbdr550.js.map → chunk-rnjbja88.js.map} +1 -1
- package/dist/{chunk-q8msf1gf.js → chunk-rq2k9frr.js} +2 -2
- package/dist/{chunk-q8msf1gf.js.map → chunk-rq2k9frr.js.map} +1 -1
- package/dist/chunk-se5ekvgb.js +19 -0
- package/dist/{chunk-anfs5mwm.js.map → chunk-se5ekvgb.js.map} +12 -11
- package/dist/{chunk-v6v03hy7.js → chunk-sqc6fkqt.js} +2 -2
- package/dist/{chunk-v6v03hy7.js.map → chunk-sqc6fkqt.js.map} +1 -1
- package/dist/{chunk-78cvy4je.js → chunk-tn71d46d.js} +2 -2
- package/dist/{chunk-78cvy4je.js.map → chunk-tn71d46d.js.map} +1 -1
- package/dist/{chunk-hkhxkeeb.js → chunk-v6q4990x.js} +3 -3
- package/dist/{chunk-hkhxkeeb.js.map → chunk-v6q4990x.js.map} +1 -1
- package/dist/{chunk-e41vdprh.js → chunk-w34j3cd3.js} +3 -3
- package/dist/{chunk-e41vdprh.js.map → chunk-w34j3cd3.js.map} +1 -1
- package/dist/{chunk-35fbxgjh.js → chunk-wzqxtrpt.js} +2 -2
- package/dist/{chunk-35fbxgjh.js.map → chunk-wzqxtrpt.js.map} +1 -1
- package/dist/{chunk-39p7ge47.js → chunk-x917yccy.js} +2 -2
- package/dist/{chunk-39p7ge47.js.map → chunk-x917yccy.js.map} +1 -1
- package/dist/{chunk-z2fnf49p.js → chunk-xzexftx1.js} +1 -1
- package/dist/{chunk-dfv5eqma.js → chunk-z4k18gnp.js} +2 -2
- package/dist/{chunk-dfv5eqma.js.map → chunk-z4k18gnp.js.map} +1 -1
- package/dist/{chunk-b6948dnh.js → chunk-z6gzasra.js} +2 -2
- package/dist/{chunk-b6948dnh.js.map → chunk-z6gzasra.js.map} +1 -1
- package/dist/{chunk-p57x55qd.js → chunk-zqpskwk9.js} +2 -2
- package/dist/{chunk-p57x55qd.js.map → chunk-zqpskwk9.js.map} +1 -1
- package/dist/chunks/ThemeProvider-Bz-y1g2i.js.map +1 -1
- package/dist/client/ClientRouter.d.ts.map +1 -1
- package/dist/client/Link.d.ts +3 -2
- package/dist/client/Link.d.ts.map +1 -1
- package/dist/client/Redirect.d.ts +3 -3
- package/dist/client/Redirect.d.ts.map +1 -1
- package/dist/client/index.d.ts +2 -2
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +5 -7
- package/dist/client/index.js.map +1 -1
- package/dist/client/types.d.ts +72 -2
- package/dist/client/types.d.ts.map +1 -1
- package/dist/client/useNavigate.d.ts +29 -6
- package/dist/client/useNavigate.d.ts.map +1 -1
- package/dist/client/usePrefetch.d.ts +13 -3
- package/dist/client/usePrefetch.d.ts.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/Connection.d.ts.map +1 -1
- package/dist/database/index.d.ts +1 -0
- package/dist/database/index.d.ts.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/database/sqlitePath.d.ts +46 -0
- package/dist/database/sqlitePath.d.ts.map +1 -0
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/Auth.d.ts.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/ApiRouter.d.ts +1 -1
- 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/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/ai/Agent.test-d.d.ts +0 -2
- package/dist/ai/Agent.test-d.d.ts.map +0 -1
- package/dist/ai/Schema.test-d.d.ts +0 -2
- package/dist/ai/Schema.test-d.d.ts.map +0 -1
- package/dist/ai/client/reducer.test-d.d.ts +0 -2
- package/dist/ai/client/reducer.test-d.d.ts.map +0 -1
- package/dist/ai/example.d.ts +0 -129
- package/dist/ai/example.d.ts.map +0 -1
- package/dist/chunk-4728yrmt.js +0 -5
- package/dist/chunk-4728yrmt.js.map +0 -10
- package/dist/chunk-anfs5mwm.js +0 -19
- package/dist/chunk-dq2hgzje.js +0 -5
- package/dist/chunk-f9ccncar.js +0 -5
- package/dist/chunk-f9ccncar.js.map +0 -13
- package/dist/client/useDictionary.test-d.d.ts +0 -2
- package/dist/client/useDictionary.test-d.d.ts.map +0 -1
- package/dist/console/builder.test-d.d.ts +0 -2
- package/dist/console/builder.test-d.d.ts.map +0 -1
- package/dist/http/ApiRouter.test-d.d.ts +0 -2
- package/dist/http/ApiRouter.test-d.d.ts.map +0 -1
- package/dist/http/McpRouter.test-d.d.ts +0 -2
- package/dist/http/McpRouter.test-d.d.ts.map +0 -1
- package/dist/services/events/FakeEventManager.test-d.d.ts +0 -2
- package/dist/services/events/FakeEventManager.test-d.d.ts.map +0 -1
- package/dist/services/events/Listener.test-d.d.ts +0 -2
- package/dist/services/events/Listener.test-d.d.ts.map +0 -1
- /package/dist/{chunk-rj3fnc4h.js.map → chunk-2ghpxrw1.js.map} +0 -0
- /package/dist/{chunk-pbx9p6g0.js.map → chunk-6waph5k8.js.map} +0 -0
- /package/dist/{chunk-z2fnf49p.js.map → chunk-xzexftx1.js.map} +0 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ib as
|
|
2
|
+
import{Ib as u5,Jb as t}from"../chunk-hq496pa4.js";import{Ce as k2,Te as g,ef as T2}from"../chunk-a85fn4zf.js";import"../chunk-g2ywq30n.js";import"../chunk-pcxxnnad.js";import"../chunk-p5m0da00.js";import"../chunk-5g1j29p2.js";import"../chunk-r6v21jn6.js";import{createHmac as A2,randomBytes as bQ,timingSafeEqual as vQ}from"crypto";var VQ="agt1",fQ=86400000;function c(Q){let $=Q??process.env.SECRET;if(!$)throw Error("Signing a pending tool call needs an app secret. Set SECRET in the environment.");return $}function M(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(M).join(",")}]`;let $=Q;return`{${Object.keys($).filter((G)=>$[G]!==void 0).sort().map((G)=>`${JSON.stringify(G)}:${M($[G])}`).join(",")}}`}function I2(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function m(Q,$){return A2("sha256",Q).update(I2($)).digest()}function hQ(Q,$,Z){let G=[VQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),M(Q.input)];if(Q.path&&Q.path.length>0)G.push(M(Q.path));return G}var yQ=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),w2=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function gQ(Q,$={}){let Z=c($.secret),J=($.now??Date.now())+($.ttlMs??fQ),W=bQ(12).toString("base64url"),Y=m(Z,hQ(Q,W,J)).toString("base64url");return[VQ,yQ(Q.runId),W,J.toString(36),Y].join(".")}function p(Q){return BQ(Q,VQ)}function BQ(Q,$){let Z=Q.split(".");if(Z.length!==5||Z[0]!==$)return null;let G=Number.parseInt(Z[3],36);if(!Number.isFinite(G))return null;try{return{runId:w2(Z[1]),nonce:Z[2],expiresAt:G}}catch{return null}}function uQ(Q,$,Z={}){let G=c(Z.secret),J=p(Q);if(!J)return{ok:!1,reason:"malformed"};let W=Buffer.from(Q.split(".")[4],"base64url"),Y=m(G,hQ($,J.nonce,J.expiresAt));if(W.length!==Y.length||!vQ(W,Y))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>J.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:J.runId,nonce:J.nonce,expiresAt:J.expiresAt}}var i="agn1";function cQ(Q,$,Z){return[i,Q.runId,M(Q.path),Q.nestedRunId,$,String(Z),M([...Q.open].sort()),M(Q.input)]}function mQ(Q,$={}){let Z=c($.secret),J=($.now??Date.now())+($.ttlMs??fQ),W=bQ(12).toString("base64url"),Y=m(Z,cQ(Q,W,J)).toString("base64url");return[i,yQ(Q.runId),W,J.toString(36),Y].join(".")}function pQ(Q,$,Z={}){let G=c(Z.secret),J=BQ(Q,i);if(!J)return{ok:!1,reason:"malformed"};let W=Buffer.from(Q.split(".")[4],"base64url"),Y=m(G,cQ({...$,runId:J.runId},J.nonce,J.expiresAt));if(W.length!==Y.length||!vQ(W,Y))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>J.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:J.runId,nonce:J.nonce,expiresAt:J.expiresAt}}var E=new Map,iQ=1024;function b2(Q){for(let[$,Z]of E)if(Z<=Q)E.delete($);iQ=Math.max(1024,E.size*2)}function lQ(Q,$={}){return nQ(p(Q),$)}function dQ(Q,$={}){return nQ(BQ(Q,i),$)}function nQ(Q,$){if(!Q)return!1;let Z=$.now??Date.now();if(E.size>=iQ)b2(Z);let G=E.get(Q.nonce);if(G!==void 0&&G>Z)return!1;return E.set(Q.nonce,Q.expiresAt),!0}class v extends Error{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class A extends Error{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function KQ(Q){if(!Q||typeof Q.key!=="string"||Q.key.length===0)throw new A("An attachment scope needs a non-empty key. Return `null` from `attachmentScope()` for a request that has no subject \u2014 an empty key is a bucket every caller shares.");return Q}var C="gemi_att_";function HQ(){return`${C}${crypto.randomUUID()}`}class f{store;storage;scope;constructor(Q,$,Z){this.store=Q;this.storage=$;this.scope=Z;KQ(Z)}async get(Q){let $=await this.store.find(this.scope,Q);if(!$||$.scopeKey!==this.scope.key)throw new v(Q);return $}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,$){if(!$.objectName)throw new v(Q);return await this.storage.read({name:$.objectName})}async file(Q){let $=await this.get(Q),G=(await this.readRecord(Q,$)).body,J=G instanceof Blob?G:G?await new Response(G).blob():new Blob([]);return new File([J],$.name,{type:$.mimeType})}async put(Q,$={}){let Z=HQ(),G=$.mimeType??Q.type??"",J=$.name??(Q instanceof File?Q.name:Z),W=await this.storage.put({name:zQ(Z,J),body:Q,contentType:G||void 0}),Y={id:Z,scopeKey:this.scope.key,objectName:W,name:J,mimeType:G||"application/octet-stream",size:Q.size,createdAt:new Date().toISOString(),destination:$.fileId?"both":"storage",...$.fileId?{fileId:$.fileId}:{}};return await this.store.put(this.scope,Y),Y}}function zQ(Q,$){let Z=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Q}${Z?`.${Z[1].toLowerCase()}`:""}`}class l{rows=new Map;async put(Q,$){KQ(Q),this.rows.set($.id,{...$,scopeKey:Q.key})}async find(Q,$){KQ(Q);let Z=this.rows.get($);if(!Z||Z.scopeKey!==Q.key)return null;return Z}get size(){return this.rows.size}}var d=new l;var UQ=new TextEncoder;function oQ(Q){return`id: ${Q.seq}
|
|
3
3
|
data: ${JSON.stringify(Q.event)}
|
|
4
4
|
|
|
5
|
-
`}var
|
|
5
|
+
`}var v2=5000,f2=`: keepalive
|
|
6
6
|
|
|
7
|
-
`;function
|
|
8
|
-
${await
|
|
7
|
+
`;function DQ(Q,$=v2){let Z=null,G=!1,J=()=>{if(G)return;if(Z!==null)clearTimeout(Z);Z=setTimeout(()=>{if(Z=null,G)return;try{Q.enqueue(UQ.encode(f2))}catch{W();return}J()},$)},W=()=>{if(G=!0,Z!==null)clearTimeout(Z);Z=null};return J(),{touch:J,stop:W}}function h2(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function sQ(Q,$=200){let Z=Q[Symbol.asyncIterator](),G=-1,J,W=new ReadableStream({start(Y){J=DQ(Y)},async pull(Y){try{let X=await Z.next();if(X.done){J.stop(),Y.close();return}G=X.value.seq,Y.enqueue(UQ.encode(oQ(X.value))),J.touch()}catch(X){let V={type:"error",error:y2(X)};J.stop(),Y.enqueue(UQ.encode(oQ({seq:G+1,event:V}))),Y.close()}},cancel(Y){J.stop(),Z.return?.(Y)}});return new Response(W,{status:$,headers:h2()})}function y2(Q){return{code:"unknown",message:Q instanceof Error?Q.message:String(Q),retryable:!1}}class q extends Error{pending;path;nested;constructor(Q){super(`A nested agent run is waiting on the user for ${Q.pending.length} tool call(s).`);this.name="PendingEscalation",this.pending=Q.pending,this.path=Q.path,this.nested=Q.nested}}class R{name;description;inputSchema;outputSchema;requiresApproval;deferred;answeredBy;execute;constructor(Q){this.name=Q.name,this.description=Q.description,this.inputSchema=Q.inputSchema,this.outputSchema=Q.outputSchema,this.requiresApproval=Q.requiresApproval===!0,this.deferred=Q.deferred===!0,this.answeredBy=Q.answeredBy==="client"?"client":"server",this.execute=Q.execute??void 0}static create(Q){return new R(Q)}static ask(Q){return R.create({name:Q.name,description:Q.description,inputSchema:LQ,outputSchema:Q.outputSchema,answeredBy:"client"})}}var LQ={toJSONSchema:()=>({type:"object",properties:{question:{type:"string",description:"What to ask the user"}},required:["question"],additionalProperties:!1}),parse(Q){let $=LQ.safeParse(Q);if($.ok===!1)throw Error($.errors.join(", "));return $.value},safeParse(Q){if(typeof Q!=="object"||Q===null||typeof Q.question!=="string")return{ok:!1,errors:["question: expected a string"]};return{ok:!0,value:{question:Q.question}}}};class a{name;description;tools;deferred;constructor(Q){this.name=Q.name,this.description=Q.description,this.tools=Q.tools,this.deferred=Q.deferred===!0}static create(Q){return new a(Q)}}class CQ{name;description;instructions;files;constructor(Q){this.name=Q.name,this.description=Q.description,this.instructions=Q.instructions,this.files=Q.files}static create(Q){return new CQ(Q)}}var h="skills",g2="Instructions this agent can load on demand. Load the relevant one before acting in the area it covers.",W2={type:"object",properties:{},required:[],additionalProperties:!1},u2=8,c2=3;class NQ{name;tools;skills;provider;output;instructions;maxSteps;maxDepth;reasoning;config;constructor(Q){this.name=Q.name,this.instructions=Q.instructions,this.provider=Q.provider,this.tools=Q.tools??[],this.skills=Q.skills??[],this.output=Q.output,this.maxSteps=Q.maxSteps??u2,this.maxDepth=Q.maxDepth??c2,this.reasoning=Q.reasoning;let{registry:$,providerTools:Z}=m2(this.tools,this.skills);this.config={name:this.name,instructions:this.instructions,provider:this.provider,registry:$,providerTools:Z,output:Q.output,maxSteps:this.maxSteps,maxDepth:this.maxDepth,reasoning:this.reasoning,maxOutputTokens:Q.maxOutputTokens,temperature:Q.temperature}}static create(Q){return new NQ(Q)}stream(Q){let $={...this.config,provider:Q.provider??this.config.provider,maxSteps:Q.maxSteps??this.config.maxSteps,reasoning:Q.reasoning??this.config.reasoning,maxOutputTokens:Q.maxOutputTokens??this.config.maxOutputTokens,temperature:Q.temperature??this.config.temperature};return new X2($,Q)}}function tQ(Q){return{name:Q.tool.name,description:Q.tool.description,parameters:Q.tool.inputSchema.toJSONSchema(),strict:t(Q.tool.inputSchema),deferred:Q.deferred}}function m2(Q,$){let Z=new Map,G=[],J=(W)=>{if(Z.has(W.tool.name))throw Error(`Two tools are named "${W.tool.name}". Tool names are global within an agent \u2014 the client discriminates a tool part by name alone.`);Z.set(W.tool.name,W)};for(let W of Q){if(W instanceof a){if(W.name===h)throw Error(`"${h}" is reserved for the namespace skills are lowered into. Rename the namespace \u2014 silently shadowing it would make every skill unreachable with no error to read.`);let X=[];for(let V of W.tools){let B={tool:V,namespace:W.name,deferred:W.deferred||V.deferred};J(B),X.push(tQ(B))}G.push({name:W.name,description:W.description,tools:X});continue}let Y={tool:W,deferred:W.deferred};J(Y),G.push(tQ(Y))}if($.length>0){let W=[];for(let Y of $){let X=p2(Y);J({tool:X,namespace:h,deferred:!1}),W.push({name:Y.name,description:Y.description,parameters:W2,strict:!0,deferred:!1})}G.push({name:h,description:g2,tools:W})}return{registry:Z,providerTools:G}}function p2(Q){return R.create({name:Q.name,description:Q.description,inputSchema:{toJSONSchema:()=>W2,parse:()=>({}),safeParse:()=>({ok:!0,value:{}})},execute:async()=>{let Z=[typeof Q.instructions==="function"?await Q.instructions():Q.instructions];for(let G of Q.files??[])Z.push(`--- ${G} ---
|
|
8
|
+
${await i2(G)}`);return Z.join(`
|
|
9
9
|
|
|
10
|
-
`)}})}async function
|
|
11
|
-
data: ${JSON.stringify(
|
|
10
|
+
`)}})}async function i2(Q){try{return await Bun.file(Q).text()}catch($){return`(could not be read: ${$.message})`}}class S extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function n(Q,$){if($.aborted)return Promise.reject(new S);return new Promise((Z,G)=>{let J=()=>G(new S);$.addEventListener("abort",J,{once:!0}),Q.then(Z,G).finally(()=>$.removeEventListener("abort",J))})}function o(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function OQ(Q,$){if(!$)return Q;let Z={inputTokens:Q.inputTokens+($.inputTokens??0),outputTokens:Q.outputTokens+($.outputTokens??0),totalTokens:Q.totalTokens+($.totalTokens??0)};if($.reasoningTokens!==void 0||Q.reasoningTokens!==void 0)Z.reasoningTokens=(Q.reasoningTokens??0)+($.reasoningTokens??0);if($.cachedInputTokens!==void 0||Q.cachedInputTokens!==void 0)Z.cachedInputTokens=(Q.cachedInputTokens??0)+($.cachedInputTokens??0);return Z}function l2(Q){return typeof Q==="object"&&Q!==null&&typeof Q.next==="function"&&Symbol.asyncIterator in Q}function jQ(Q){if(!Q.trim())return{};try{return JSON.parse(Q)}catch{}let $=[],Z=!1,G=!1;for(let Y of Q){if(Z){if(G)G=!1;else if(Y==="\\")G=!0;else if(Y==='"')Z=!1;continue}if(Y==='"')Z=!0;else if(Y==="{")$.push("}");else if(Y==="[")$.push("]");else if(Y==="}"||Y==="]")$.pop()}let J=Q;if(Z)J+='"';J=J.replace(/[,:]\s*$/,"");let W=$.reverse().join("");try{return JSON.parse(J+W)}catch{try{return JSON.parse(J.replace(/,?\s*"[^"]*"\s*$/,"")+W)}catch{return{}}}}function aQ(Q,$){let Z=[...Q],G=new Map(Z.map((J,W)=>[J.id,W]));for(let J of $){let W=G.get(J.id);if(W===void 0)G.set(J.id,Z.length),Z.push(J);else Z[W]=J}return Z}function s(Q){let $=new Set;for(let G of Q)for(let J of G.content)if(J.type==="tool-result")$.add(J.toolCallId);let Z=new Set;for(let G of Q)for(let J of G.content)if(J.type==="tool-call"&&!$.has(J.toolCallId))Z.add(J.toolCallId);return Z}function rQ(Q){for(let $=Q.length-1;$>=0;$--){let Z=Q[$].content;for(let G=Z.length-1;G>=0;G--){let J=Z[G];if(J.type==="output"&&J.partial!==!0)return J.value}}return}function eQ(Q,$){return $===void 0?`"${Q}"`:`"${Q}" labelled "${$}"`}function Y2(Q){return Q.content.map(($)=>$.type==="text"?$.text:`<${$.type}>`).join("")}function d2(Q){if(Q.prompt!==void 0)return`user:${Q.prompt}`;let $=Q.messages?.[0];return $?`${$.role}:${Y2($)}`:null}function Q2(Q){let $=new Set;for(let Z of Q)for(let G of Z.content){if(G.type!=="tool-call")continue;for(let J of G.attachments??[])if("shown"in J&&J.shown)$.add(J.shown.messageId)}return $}var $2=1;function n2(Q,$,Z){let G=Z.mimeType||$.type||"";if(G&&Q.attachment.mimeType!==G)return`was ${JSON.stringify(Q.attachment.mimeType)} on the turn that escalated and is ${JSON.stringify(G)} on the replay`;let J=Boolean(Z.showModel);if(J!==Boolean(Q.shown))return J?"was stored without showModel on the turn that escalated and asks for showModel on the replay":"was stored with showModel on the turn that escalated and asks for a plain put on the replay";return null}function o2(Q,$,Z){if(Q.agent!==$.name||Q.label!==Z.label)return`was ${eQ(Q.agent,Q.label)} on the turn that escalated and is ${eQ($.name,Z.label)} on the replay`;let G=d2(Z),J=Q.messages[0],W=J?`${J.role}:${Y2(J)}`:null;if(G!==null&&W!==null&&G!==W)return`was started with ${JSON.stringify(W)} on the turn that escalated and with ${JSON.stringify(G)} on the replay`;return null}function Z2(Q,$){let Z=Q??[];if(Z.length<$.length)return null;for(let G=0;G<$.length;G++)if(Z[G]!==$[G])return null;return Z.slice($.length)}class FQ{read;create;fill;index=0;replayable;constructor(Q,$,Z){this.read=Q;this.create=$;this.fill=Z;this.replayable=Q()?.length??0}next(){let Q=this.index++;return{at:Q,recorded:Q<this.replayable?this.read()?.[Q]:void 0,write:($)=>{let Z=this.read()??this.create();if(this.fill)for(let G=Z.length;G<Q;G++)Z[G]=this.fill();Z[Q]=$}}}}class X2{runId;config;params;controller=new AbortController;buffer=[];waiters=new Set;seq=0;ended=!1;history=[];produced=[];current=null;outputTruncated=!1;amended=new Map;unreported=new Set;usage=o();finishReason="stop";output;stopReason;settled;depth;maxDepth;chain;signingRunId;pathPrefix;onPending;nestedSettling=new Set;shownQueue=new Map;constructor(Q,$){this.config=Q,this.params=$,this.runId=$.runId??`run_${crypto.randomUUID()}`,this.history=[...$.messages];let Z=$.nesting;if(this.depth=Z?.depth??0,this.maxDepth=Z?.maxDepth??Q.maxDepth,this.chain=Z?.chain??[Q.name],this.signingRunId=Z?.signingRunId??this.runId,this.pathPrefix=Z?.signingPath??[],this.onPending=Z?.onPending??"escalate",$.signal)if($.signal.aborted)this.controller.abort();else $.signal.addEventListener("abort",()=>this.stop(),{once:!0});this.settled=this.execute(),$.req?.ctx?.()?.waitUntil(this.settled)}emit(Q){if(this.ended)return;this.buffer.push({seq:++this.seq,event:Q}),this.wake()}wake(){let Q=[...this.waiters];this.waiters.clear();for(let $ of Q)$()}nextFrame(){return new Promise((Q)=>this.waiters.add(Q))}async*frames(Q=0){let $=Q>0?Q-1:0;for(;;){while($<this.buffer.length)yield this.buffer[$++];if(this.ended)return;await this.nextFrame()}}async*[Symbol.asyncIterator](){for await(let Q of this.frames())yield Q.event}toResponse(Q){let $=this.frames(Q?.from),Z=new TextEncoder,G=!1,J,W=new ReadableStream({start:async(Y)=>{J=DQ(Y);try{for await(let X of $){if(G)break;Y.enqueue(Z.encode(`id: ${X.seq}
|
|
11
|
+
data: ${JSON.stringify(X.event)}
|
|
12
12
|
|
|
13
|
-
`)),J.touch()}}catch{}J.stop();try{
|
|
13
|
+
`)),J.touch()}}catch{}J.stop();try{Y.close()}catch{}},cancel:()=>{G=!0,J.stop()}});return new Response(W,{headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}result(){return this.settled}stop(Q){if(this.ended||this.controller.signal.aborted)return;this.stopReason=Q?.reason,this.controller.abort()}async execute(){this.emit({type:"run-start",runId:this.runId,threadId:this.params.threadId});try{let Q=await this.ingestTurn();if(Q.length>0)this.finishReason="awaiting-input",this.emit({type:"awaiting-input",runId:this.runId,pending:Q});else await this.loop()}catch(Q){if(Q instanceof S||this.controller.signal.aborted)await this.finalizeAborted();else{let $=this.config.provider.normalizeError(Q);this.emit({type:"error",error:$}),await this.finalizeMessage("error"),this.finishReason="error"}}return this.emit({type:"usage",usage:this.usage}),this.emit({type:"run-end",runId:this.runId,finishReason:this.finishReason}),this.ended=!0,this.wake(),{runId:this.runId,messages:this.produced,finishReason:this.finishReason,usage:this.usage,output:this.output}}async loop(){let Q=Math.max(1,this.config.maxSteps);for(let $=1;$<=Q;$++){let Z=this.startMessage(),G=await this.runStep(Z);if(G.error){this.emit({type:"error",error:G.error}),await this.finalizeMessage("error"),this.finishReason="error";return}let J=Z.content.filter((Y)=>Y.type==="tool-call");if(J.length===0){this.finishReason=G.reason,await this.finalizeMessage(G.reason);return}let W=await this.runTools(Z,J,$);if(W.length>0){this.finishReason="awaiting-input",await this.finalizeMessage("awaiting-input"),this.emit({type:"awaiting-input",runId:this.runId,pending:W});return}if($===Q){this.finishReason="max-steps",await this.finalizeMessage("max-steps");return}await this.finalizeMessage(G.reason)}}startMessage(){let Q={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()};return this.current=Q,this.history.push(Q),this.produced.push(Q),this.emit({type:"message-start",messageId:Q.id,role:"assistant"}),Q}async finalizeMessage(Q){let $=this.current;if(!$)return;this.current=null;let Z=this.outputTruncated;if(this.outputTruncated=!1,$.finishReason=Q,Z)$.outputTruncated=!0;for(let G of $.content)if(G.type==="text"||G.type==="reasoning"){if(typeof G.text==="string")G.text=s2(G.text)}this.emit({type:"message-end",messageId:$.id,finishReason:Q,...Z?{outputTruncated:!0}:{}}),await this.report($),await this.reportDeferred()}async report(Q){if(!this.params.onMessage)return;try{await this.params.onMessage(Q)}catch{}}async runStep(Q){let $=this.controller.signal,Z=this.config.provider,G={reason:"stop"},J=new Map,W="",X=Z.stream({messages:this.historyForProvider(Q),systemPrompt:await this.systemPrompt(),tools:this.config.providerTools.length>0?this.config.providerTools:void 0,output:this.config.output?{name:"output",schema:this.config.output.toJSONSchema(),strict:t(this.config.output)}:void 0,reasoning:this.config.reasoning,maxOutputTokens:this.config.maxOutputTokens,temperature:this.config.temperature,signal:$})[Symbol.asyncIterator]();for(;;){let B=await n(Promise.resolve(X.next()),$);if(B.done)break;let K=B.value;switch(K.type){case"text-delta":{t2(Q,"text",K.delta),this.emit({type:"text-delta",messageId:Q.id,delta:K.delta});break}case"reasoning-delta":{a2(Q,K.id,K.delta),this.emit({type:"reasoning-delta",messageId:Q.id,delta:K.delta,id:K.id});break}case"output-delta":{W+=K.delta,this.emit({type:"output-delta",messageId:Q.id,delta:K.delta,snapshot:jQ(W)});break}case"tool-search":{this.emit({type:"tool-search",loaded:K.loaded});break}case"tool-call-delta":{let H=J.get(K.toolCallId)??{name:K.name,args:""};H.args+=K.argsDelta,H.name=K.name||H.name,J.set(K.toolCallId,H),this.emit({type:"tool-call",messageId:Q.id,part:{type:"tool-call",toolCallId:K.toolCallId,name:H.name,input:jQ(H.args),partial:!0}});break}case"tool-call":{J.delete(K.toolCallId);let H={type:"tool-call",toolCallId:K.toolCallId,name:K.name,input:J2(K.args)};Q.content.push(H),this.emit({type:"tool-call",messageId:Q.id,part:H});break}case"finish":{if(this.usage=OQ(this.usage,K.usage),!G.error)G={reason:K.reason};break}case"error":{G={reason:"error",error:K.error};break}}}for(let[B,K]of J){let H={type:"tool-call",toolCallId:B,name:K.name,input:J2(K.args)};Q.content.push(H),this.emit({type:"tool-call",messageId:Q.id,part:H})}let V=G.reason==="length";if(V)this.outputTruncated=!0;if(this.config.output&&W&&!G.error&&!V){let B=this.config.output.safeParse(jQ(W));if(B.ok===!0)this.output=B.value,Q.content.push({type:"output",value:B.value});else this.emit({type:"error",error:{code:"unknown",message:`The model's structured answer did not match the output schema: ${B.errors.join(", ")}`,retryable:!0}})}return G}async systemPrompt(){let Q=[this.config.instructions,this.params.instructions].filter(($)=>Boolean($&&$.trim()));return Q.length>0?Q.join(`
|
|
14
14
|
|
|
15
|
-
`):void 0}async runTools(Q,$,Z){let G=[],J=[];for(let Y of $){let W=this.config.registry.get(String(Y.name));if(!W){this.addResult(Q,{type:"tool-result",toolCallId:Y.toolCallId,name:Y.name,status:"error",error:{code:"tool_error",message:`There is no tool named "${String(Y.name)}".`,toolCallId:Y.toolCallId,retryable:!0}});continue}let V=W.tool.inputSchema.safeParse(Y.input);if(V.ok===!1){this.addResult(Q,{type:"tool-result",toolCallId:Y.toolCallId,name:Y.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${String(Y.name)}": ${V.errors.join(", ")}`,toolCallId:Y.toolCallId,retryable:!0}});continue}Y.input=V.value;let X=Z2(W.tool);if(X){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(Y));continue}G.push({toolCallId:Y.toolCallId,name:Y.name,input:V.value,kind:X,signature:yQ(this.claimsFor(Y.toolCallId,String(Y.name),X,V.value)),...this.pathPrefix.length>0?{path:[...this.pathPrefix]}:{}});continue}J.push(this.executeTool(W,Q.id,Y,V.value,Z).then(async(B)=>{this.addResult(Q,B),await this.settleShown(Y.toolCallId)}).catch((B)=>{if(B instanceof M){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(Y));return}G.push(...B.pending);return}}))}return await n(Promise.all(J).then(()=>{return}),this.controller.signal),G}claimsFor(Q,$,Z,G){return{runId:this.signingRunId,toolCallId:Q,name:$,kind:Z,input:G,path:this.pathPrefix.length>0?[...this.pathPrefix]:void 0}}deniedByPolicy(Q){return{type:"tool-result",toolCallId:Q.toolCallId,name:Q.name,status:"denied",cause:"refused",reason:`"${String(Q.name)}" needs the user, and this run was started with onPending: "deny". Answer from what you already have.`}}async executeTool(Q,$,Z,G,J,Y){let W={req:this.params.req,runId:this.runId,threadId:this.params.threadId,toolCallId:Z.toolCallId,signal:this.controller.signal,step:J,depth:this.depth,resumed:Y!==void 0,attachments:this.toolAttachments(Z),turn:this.toolTurn($),runAgent:this.nestedRunner($,Z,Y)};try{let V=Q.tool.execute(G,W),X;if(m2(V)){let B=await V.next();while(!B.done)this.emit({type:"tool-progress",toolCallId:Z.toolCallId,data:B.value}),B=await V.next();X=B.value}else X=await V;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"ok",output:X}}catch(V){if(V instanceof q||this.controller.signal.aborted)throw new q;if(V instanceof M)throw V;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:{code:"tool_error",message:V instanceof Error?V.message:String(V),toolCallId:Z.toolCallId,retryable:!0}}}}nestedRunner(Q,$,Z){let G=new jQ(()=>$.nested,()=>$.nested=[]);return async(J,Y={})=>{let{at:W,recorded:V,write:X}=G.next();if(V){let B=l2(V,J,Y);if(B)throw Error(`Nested run ${W} of "${String($.name)}" ${B}. `+"runAgent is memoized by call index, so a body whose runAgent calls depend on a condition that changed between turns cannot be resumed \u2014 the answer would be paired with a different sub-run. "+"Make the sequence of runAgent calls, and what each one is asked, the same every time this tool runs, or branch on ctx.resumed.");if(V.finishReason!=="awaiting-input")return{runId:V.runId,agent:V.agent,messages:V.messages,finishReason:V.finishReason??"stop",usage:V.usage??o(),output:aQ(V.messages),nested:V}}return this.runNested(Q,$,J,Y,X,V,Z?.answers??[])}}async runNested(Q,$,Z,G,J,Y,W){let V=[...this.chain,Z.name];if(this.chain.includes(Z.name))throw Error(`"${Z.name}" is already running further up this chain: ${V.join(" -> ")}. An agent cannot run itself, directly or through another agent.`);let X=this.depth+1;if(X>this.maxDepth)throw Error(`Nested agent runs are ${this.maxDepth} deep at most and this one would be ${X}: ${V.join(" -> ")}. Raise maxDepth on the agent at the root of the run if the tree is meant to be this deep.`);let B=G.label,K=[...this.pathPrefix,$.toolCallId],H=this.onPending==="deny"?"deny":G.onPending??"escalate",z=Y!==void 0,O=z?s(Y.messages):new Set,D=z?W.filter((L)=>{let k=$2(L.path,K);if(k===null)return!1;return O.has(k.length>0?k[0]:L.toolCallId)}):[],U=Z.stream({messages:z?Y.messages:G.messages??[],turn:z?{toolResults:D}:G.prompt?{text:G.prompt}:void 0,req:this.params.req,attachments:this.params.attachments,signal:this.controller.signal,threadId:this.params.threadId,instructions:G.instructions,runId:z?Y.runId:void 0,nesting:{depth:X,maxDepth:this.maxDepth,chain:V,signingRunId:this.signingRunId,signingPath:K,onPending:H}}),j=[],F=(async()=>{for await(let L of U){if(L.type==="awaiting-input")j=L.pending;this.emit({type:"nested-event",toolCallId:$.toolCallId,runId:U.runId,agent:Z.name,label:B,event:L})}})(),w=(async()=>{let L=await U.result();await F;let k=z?tQ(Y.messages,L.messages):tQ(G.messages??[],L.messages),IQ={runId:U.runId,agent:Z.name,label:B,messages:k,finishReason:L.finishReason,usage:z?DQ(Y.usage??o(),L.usage):L.usage,...L.finishReason==="awaiting-input"?{signature:cQ({runId:this.signingRunId,path:K,nestedRunId:U.runId,open:[...s(k)],input:$.input})}:{}};return J(IQ),this.usage=DQ(this.usage,L.usage),{result:L,record:IQ}})(),b=w.then(()=>{return},()=>{return});this.nestedSettling.add(b);let u,_;try{({result:u,record:_}=await w)}finally{this.nestedSettling.delete(b)}if(this.controller.signal.aborted)throw new q;if(u.finishReason==="awaiting-input"){if(j.length===0)throw Error(`"${Z.name}" ended awaiting input but asked nothing, so there is no question to escalate.`);throw this.emit({type:"tool-call",messageId:Q,part:$,resent:!0}),new M({pending:j,path:K,nested:_})}return{runId:_.runId,agent:Z.name,messages:_.messages,finishReason:u.finishReason,usage:_.usage??o(),output:u.output??aQ(_.messages),nested:_}}addResult(Q,$){Q.content.push($),this.emit({type:"tool-result",messageId:Q.id,part:$})}toolAttachments(Q){let $=this.params.attachments??null,Z=new jQ(()=>Q.attachments,()=>Q.attachments=[],()=>({failed:!0})),G=()=>{if(!$)throw new x("This request has no attachment scope, so a tool cannot store or read files on it. `attachmentScope()` returned null \u2014 put the chat route behind authentication, send a `threadId`, or override `attachmentScope()` on the controller.");return $};return{get:(J)=>G().get(J),read:(J)=>G().read(J),file:(J)=>G().file(J),put:async(J,Y={})=>{let{at:W,recorded:V,write:X}=Z.next();if(V&&"attachment"in V){let U=i2(V,J,Y);if(U)throw Error(`Attachment ${W} of "${String(Q.name)}" ${U}. `+"ctx.attachments.put is memoized by call index within a tool call, so a body whose put calls depend on a condition that changed between turns cannot be replayed \u2014 the model would be shown a file under an id that names different bytes. "+"Make the sequence of put calls the same every time this tool runs, or branch on ctx.resumed.");if(V.shown)this.queueShown(Q.toolCallId,V);return V.attachment}let B=G(),K=Y.mimeType||J.type||"",H=Y.name??(J instanceof File?J.name:"attachment"),z;if(Y.showModel){let U=this.config.provider;if(!U.capabilities.fileInput)throw Error(`"${String(Q.name)}" asked to show a file to ${U.model}, which does not accept file input. Drop \`showModel\` for this provider, or run this agent on a model that takes files \u2014 \`capabilities.fileInput\` is what says which do.`);z=await U.upload(new File([J],H,{type:K||void 0}))}let O=await B.put(J,{name:H,mimeType:K,fileId:z}),D={attachment:O,...z?{shown:{fileId:z,messageId:`msg_${crypto.randomUUID()}`,createdAt:new Date().toISOString()}}:{}};if(X(D),D.shown)this.queueShown(Q.toolCallId,D);return O}}}toolTurn(Q){let $=this.history.findIndex((Y)=>Y.id===Q),Z=eQ(this.history),G;for(let Y=$-1;Y>=0;Y--){let W=this.history[Y];if(W.role!=="user"||Z.has(W.id))continue;G=W;break}let J=[];for(let Y of G?.content??[]){if(Y.type!=="file")continue;let W=Y.attachmentId;if(typeof W!=="string"||!W.startsWith(C))continue;if(!J.includes(W))J.push(W)}return Object.freeze({attachments:Object.freeze(J)})}queueShown(Q,$){let Z=$.shown;if(!Z)return;let G=this.shownQueue.get(Q)??[];if(G.some((J)=>J.id===Z.messageId))return;G.push({id:Z.messageId,role:"user",content:[{type:"file",fileId:Z.fileId,name:$.attachment.name,mimeType:$.attachment.mimeType,attachmentId:$.attachment.id}],createdAt:Z.createdAt,finishReason:"stop"}),this.shownQueue.set(Q,G)}async settleShown(Q){let $=this.shownQueue.get(Q);if(!$||$.length===0)return;if(this.shownQueue.delete(Q),this.ended||this.controller.signal.aborted)return;for(let Z of $){if(this.history.some((G)=>G.id===Z.id))continue;this.history.push(Z),this.produced.push(Z),this.emit({type:"message",message:Z}),this.unreported.add(Z)}}historyForProvider(Q){let $=this.history.filter((Y)=>Y!==Q),Z=eQ($),G=[];for(let Y of $){if(!Z.has(Y.id))continue;for(let W of Y.content)if(W.type==="file")G.push(W)}if(G.length<=Q2)return $;let J=new Set(G.slice(0,G.length-Q2));return $.map((Y)=>{if(!Y.content.some((W)=>W.type==="file"&&J.has(W)))return Y;return{...Y,content:Y.content.map((W)=>W.type==="file"&&J.has(W)?{type:"text",text:`[A ${W.mimeType||"file"} produced by a tool (attachment ${W.attachmentId}) was attached here and has been dropped from this request: only the most recent tool-produced file is kept attached, to keep the context bounded. Call the tool again if you need to look at it.]`}:W)}})}async ingestTurn(){let Q=this.params.turn,$=this.openCalls(),Z=[];if($.length>0){let G=new Set,J=new Set,Y=new Map;for(let W of Q?.toolResults??[]){let V=`${(W.path??[]).join("/")}#${W.toolCallId}`;if(J.has(V))continue;J.add(V);let X=(z)=>this.emit({type:"error",error:{code:"invalid_tool_result",message:z,toolCallId:W.toolCallId,retryable:!1}}),B=$2(W.path,this.pathPrefix);if(B===null){X(`The answer for "${W.toolCallId}" is addressed to a tool call this run is not inside.`);continue}if(B.length>0){let z=B[0],O=$.find((j)=>j.call.toolCallId===z);if(!O){X(`No pending tool call with id "${z}" to deliver a nested answer to.`);continue}let D=this.parkedBelow(O.call,B,W.toolCallId);if(D.ok===!1){let j=`The answer for "${W.toolCallId}" is addressed under "${z}", which`;X(D.reason==="unparked"?`${j} has no sub-agent run waiting on that question.`:D.reason==="expired"?`${j} parked a sub-agent run that has since expired. Ask again.`:`${j} carries a record of a parked sub-agent run the server did not sign.`);continue}let U=Y.get(z);if(!U){if(!lQ(D.signature)){X(`The answer for "${W.toolCallId}" is addressed under "${z}", which has already been re-entered on that record. Ask again.`);continue}U=[],Y.set(z,U),G.add(z)}U.push(W);continue}let K=$.find((z)=>z.call.toolCallId===W.toolCallId);if(!K){X(`No pending tool call with id "${W.toolCallId}".`);continue}let H=await this.resolveAnswer(K,W,Z);if(H===null)continue;if(G.add(W.toolCallId),H!=="open")this.attachToHistory(K,H),await this.settleShown(W.toolCallId)}for(let[W,V]of Y){let X=$.find((K)=>K.call.toolCallId===W),B=await this.reenter(X,V,Z);if(B)this.attachToHistory(X,B),await this.settleShown(W)}for(let W of $){if(G.has(W.call.toolCallId))continue;this.attachToHistory(W,{type:"tool-result",toolCallId:W.call.toolCallId,name:W.call.name,status:"denied",cause:"refused"})}await this.reportDeferred()}if(Q&&(Q.text||Q.files&&Q.files.length>0)){let G={id:`msg_${crypto.randomUUID()}`,role:"user",content:[...Q.text?[{type:"text",text:Q.text}]:[],...(Q.files??[]).map((J)=>({type:"file",...J.fileId?{fileId:J.fileId}:{},name:J.name,mimeType:J.mimeType,...J.attachmentId?{attachmentId:J.attachmentId}:{}}))],createdAt:new Date().toISOString(),finishReason:"stop"};this.history.push(G),this.produced.push(G),await this.report(G)}return Z}parkedBelow(Q,$,Z){let G=$.length>1?$[1]:Z,J=[...this.pathPrefix,Q.toolCallId],Y=(Q.nested??[]).find((V)=>V.finishReason==="awaiting-input"&&s(V.messages).has(G));if(!Y)return{ok:!1,reason:"unparked"};if(typeof Y.signature!=="string")return{ok:!1,reason:"unsigned"};let W=mQ(Y.signature,{path:J,nestedRunId:Y.runId,open:[...s(Y.messages)],input:Q.input});if(W.ok===!1)return{ok:!1,reason:W.reason==="expired"?"expired":"unsigned"};return{ok:!0,signature:Y.signature}}async reenter(Q,$,Z){let G=String(Q.call.name),J=this.config.registry.get(G);if(!J||!J.tool.execute)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_result",message:`The tool "${G}" no longer exists, so the sub-agent's question cannot be delivered.`,toolCallId:Q.call.toolCallId,retryable:!1}};let Y=J.tool.inputSchema.safeParse(Q.call.input);if(Y.ok===!1)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${G}": ${Y.errors.join(", ")}`,toolCallId:Q.call.toolCallId,retryable:!0}};let W=this.amendCall(Q);W.input=Y.value;try{return await n(this.executeTool(J,Q.message.id,W,Y.value,0,{answers:$}),this.controller.signal)}catch(V){if(V instanceof M)return Z.push(...V.pending),null;throw V}}amendCall(Q){let $=this.amend(Q.message),Z=$.content.indexOf(Q.call),G={...Q.call,nested:(Q.call.nested??[]).map((J)=>({...J})),...Q.call.attachments?{attachments:Q.call.attachments.map((J)=>({...J}))}:{}};if(Z>=0)$.content[Z]=G;return this.unreported.add($),G}openCalls(){let Q=new Set;for(let Z of this.history)for(let G of Z.content)if(G.type==="tool-result")Q.add(G.toolCallId);let $=[];for(let Z of this.history)for(let G of Z.content)if(G.type==="tool-call"&&!Q.has(G.toolCallId))$.push({message:Z,call:G});return $}async resolveAnswer(Q,$,Z){let G=Q.call,J=String(G.name),Y=this.config.registry.get(J),W=(K)=>{return this.emit({type:"error",error:{code:"invalid_tool_result",message:K,toolCallId:G.toolCallId,retryable:!1}}),null};if(!Y)return W(`The tool "${J}" no longer exists, so its answer cannot be checked.`);let V=Z2(Y.tool);if(!V)return W(`"${J}" is a server tool with no pending question.`);if(typeof $.signature!=="string"||$.signature.length===0)return W(`The answer for "${J}" carried no signature.`);let X=p($.signature);if(!X)return W(`The signature for "${J}" is malformed.`);let B=gQ($.signature,{...this.claimsFor(G.toolCallId,J,V,G.input),runId:X.runId});if(B.ok===!1)return W(B.reason==="expired"?`The approval for "${J}" has expired. Ask again.`:`The answer for "${J}" does not match the call the server made.`);if(!iQ($.signature))return W(`The answer for "${J}" has already been used. Ask again.`);if("approve"in $){if(V!=="approval")return W(`"${J}" is answered by the client, not approved.`);if($.approve===!0){let K=this.amendCall(Q);try{return await n(this.executeTool(Y,Q.message.id,K,K.input,0),this.controller.signal)}catch(H){if(H instanceof M)return Z.push(...H.pending),"open";throw H}}return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"denied",cause:"refused",reason:$.reason}}if("output"in $){if(V==="approval")return W(`"${J}" is approved, not answered: the server produces its result.`);let K=Y.tool.outputSchema,H=K?K.safeParse($.output):{ok:!0,value:$.output};if(H.ok===!1)return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"error",error:{code:"invalid_tool_result",message:`The answer for "${J}" did not match its output schema: ${H.errors.join(", ")}`,toolCallId:G.toolCallId,retryable:!0}};return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"ok",output:H.value}}return W(`The answer for "${J}" carried neither an approval nor an output.`)}attachToHistory(Q,$){let Z=this.amend(Q.message);Z.content.push($),this.unreported.add(Z),this.emit({type:"tool-result",messageId:Z.id,part:$})}amend(Q){let $=this.amended.get(Q.id);if($)return $;let Z={...Q,content:[...Q.content]},G=this.history.indexOf(Q);if(G>=0)this.history[G]=Z;return this.produced.push(Z),this.amended.set(Q.id,Z),Z}async reportDeferred(){let Q=[...this.unreported];this.unreported.clear();for(let $ of Q)await this.report($)}async finalizeAborted(){if(this.nestedSettling.size>0)await Promise.all([...this.nestedSettling]);for(let $ of this.openCalls()){if($.message===this.current)continue;this.attachToHistory($,{type:"tool-result",toolCallId:$.call.toolCallId,name:$.call.name,status:"denied",cause:"stopped",reason:this.stopReason})}await this.reportDeferred();let Q=this.current;if(Q){let $=new Set(Q.content.filter((Z)=>Z.type==="tool-result").map((Z)=>Z.toolCallId));for(let Z of[...Q.content]){if(Z.type!=="tool-call"||$.has(Z.toolCallId))continue;delete Z.partial,this.addResult(Q,{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"denied",cause:"stopped",reason:this.stopReason})}}this.finishReason="aborted",await this.finalizeMessage("aborted")}}function Z2(Q){if(Q.answeredBy==="client")return Q.inputSchema===LQ?"question":"client";return Q.requiresApproval?"approval":null}function G2(Q){if(!Q||!Q.trim())return{};try{return JSON.parse(Q)}catch{return Q}}function d2(Q){if(Q.length>0)Q[0];return Q}function n2(Q,$,Z){let G=Q.content[Q.content.length-1];if(G&&G.type===$){G.text=(G.text??"")+Z;return}Q.content.push($==="text"?{type:"text",text:Z}:{type:"reasoning",text:Z})}function o2(Q,$,Z){let G=Q.content[Q.content.length-1];if(G&&G.type==="reasoning"&&G.id===$){G.text=(G.text??"")+Z;return}Q.content.push($?{type:"reasoning",id:$,text:Z}:{type:"reasoning",text:Z})}function s2(Q,$){return Q.descriptors($).map((Z)=>S.create({name:Z.name,description:Z.description,inputSchema:Z.inputSchema,requiresApproval:Z.requiresApproval,execute:(G,J)=>Q.execute({kind:"local",req:J.req},Z.name,G,J)}))}class a extends Error{status;body;requestId;constructor(Q,$,Z){super(`Provider request failed with status ${Q}: ${t2($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=Z}}class r extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function t2(Q){let $=V2(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function V2(Q){if(!Q||typeof Q!=="object")return null;let $=Q,G=$.error&&typeof $.error==="object"?$.error:Q;if(typeof G.message!=="string"&&typeof G.code!=="string"&&typeof G.type!=="string")return null;let J=G.innererror?.code??G.code;return{message:G.message,type:G.type,code:J,param:G.param}}function R(Q){if(Q instanceof r)return{code:"provider_error",message:Q.message,retryable:!0};if(Q5(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof a)return a2(Q.status,V2(Q.body),Q.message);if(Q instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${Q.message}`,retryable:!0};if(Q instanceof Error)return{code:"provider_error",message:Q.message,retryable:!1};return{code:"unknown",message:String(Q),retryable:!1}}function a2(Q,$,Z){let G=$?.message??Z,J=($?.code??"").toLowerCase(),Y=($?.type??"").toLowerCase(),W=`${J} ${Y} ${G}`.toLowerCase();if(Q===429){let V=J==="insufficient_quota"||W.includes("quota");return{code:"rate_limited",message:G,retryable:!V}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:G,retryable:!0};if(r2(W))return{code:"context_length_exceeded",message:G,retryable:!1};if(e2(W))return{code:"content_filtered",message:G,retryable:!1};if($?.param?.startsWith("tools")||W.includes("invalid schema for function"))return{code:"invalid_tool_input",message:G,retryable:!1};return{code:"provider_error",message:G,retryable:!1}}function r2(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function e2(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function Q5(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}var $5=500,B2=20000;function Z5(Q,$){if(!Q)return;let Z=Q.trim();if(/^\d+(\.\d+)?$/.test(Z))return Math.max(0,Number(Z)*1000);let G=Date.parse(Z);if(Number.isNaN(G))return;return Math.max(0,G-$)}function X2(Q,$){let Z=Math.min(B2,$5*2**Q);return Math.round(Z*(0.5+$()*0.5))}function G5(Q){return Q===429||Q===408||Q===409||Q>=500}function J5(Q,$){return G5(Q)&&R($).retryable}function K2(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function Y5(Q,$){return new Promise((Z,G)=>{let J=setTimeout(Z,Q);$?.addEventListener("abort",()=>{clearTimeout(J),G(K2($))},{once:!0})})}async function NQ(Q,$,Z){let G=Z.fetchImpl??((K,H)=>fetch(K,H)),J=Z.sleep??Y5,Y=Z.random??Math.random,W=Z.now??Date.now,V=Math.max(0,Z.maxRetries),X=async(K)=>{let H=Z.signal;if(!H)return await J(K);H.throwIfAborted();let z;try{await Promise.race([J(K,H),new Promise((O,D)=>{z=()=>D(K2(H)),H.addEventListener("abort",z,{once:!0})})])}finally{if(z)H.removeEventListener("abort",z)}},B;for(let K=0;K<=V;K++){Z.signal?.throwIfAborted();let H=new AbortController,z=()=>H.abort(Z.signal?.reason);Z.signal?.addEventListener("abort",z,{once:!0});let O=!1,D=Z.timeoutMs>0?setTimeout(()=>{O=!0,H.abort()},Z.timeoutMs):void 0,U;try{U=await G(Q,{...$,signal:H.signal})}catch(b){if(D!==void 0)clearTimeout(D);if(Z.signal?.removeEventListener("abort",z),Z.signal?.aborted)throw b;if(B=O?new r(Z.timeoutMs):b,K===V)throw B;await X(X2(K,Y));continue}if(D!==void 0)clearTimeout(D);if(U.ok)return U;Z.signal?.removeEventListener("abort",z);let j=await W5(U),F=new a(U.status,j,U.headers.get("x-request-id")??void 0);if(K===V||!J5(U.status,F))throw F;let w=Z5(U.headers.get("retry-after"),W());await X(w===void 0?X2(K,Y):Math.min(w,B2)),B=F}throw B??Error("Provider request failed with no response.")}async function W5(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}async function*V5(Q){let $="",Z="",G=[],J,Y=()=>{if(G.length===0&&!Z)return null;let X={event:Z,data:G.join(`
|
|
16
|
-
`),id:J};return Z="",G=[],J=void 0,
|
|
17
|
-
`);while(B!==-1){let K=$.slice(0,B);$=$.slice(B+1);let H=
|
|
18
|
-
`)}}if($.length>0){let X=W($);if(X)yield X}let V=Y();if(V)yield V}async function*H2(Q,$={}){let Z=new Map,G=new Set,J=!1;for await(let Y of V5(Q)){if(Y.data==="[DONE]")break;let W;try{W=JSON.parse(Y.data)}catch{continue}switch(typeof W.type==="string"?W.type:Y.event){case"response.output_text.delta":{let X=String(W.delta??"");if(!X)break;yield $.structuredOutput?{type:"output-delta",delta:X}:{type:"text-delta",delta:X};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let X=String(W.delta??"");if(!X)break;yield{type:"reasoning-delta",delta:X,id:W.item_id};break}case"response.output_item.added":{let X=W.item;if(!X)break;if(X.type==="function_call"){let B=String(X.id??W.item_id??X.call_id??"");Z.set(B,{callId:String(X.call_id??B),name:String(X.name??""),namespace:typeof X.namespace==="string"&&X.namespace?X.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let X=Z.get(String(W.item_id??""));if(!X)break;let B=String(W.delta??"");if(!B)break;yield{type:"tool-call-delta",toolCallId:X.callId,name:X.name,argsDelta:B,...X.namespace?{namespace:X.namespace}:{}};break}case"response.function_call_arguments.done":{let X=String(W.item_id??""),B=Z.get(X);if(!B)break;B.done=!0,yield{type:"tool-call",toolCallId:B.callId,name:B.name,args:String(W.arguments??""),...B.namespace?{namespace:B.namespace}:{}};break}case"response.output_item.done":{let X=W.item;if(!X)break;if(X.type==="function_call"){let B=String(X.id??W.item_id??X.call_id??""),K=Z.get(B);if(K?.done)break;let H=(typeof X.namespace==="string"?X.namespace:"")||K?.namespace;if(yield{type:"tool-call",toolCallId:String(X.call_id??B),name:String(X.name??K?.name??""),args:String(X.arguments??""),...H?{namespace:H}:{}},K)K.done=!0;break}if(X.type==="tool_search_call"||X.type==="tool_search_output"){let B=X5(X);if(B.loaded.length===0&&B.namespaces.length===0)break;let K=String(X.tool_search_call_id??X.id??"");if(G.has(K))break;G.add(K),yield{type:"tool-search",...B}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(W.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{J=!0,yield{type:"finish",reason:"stop",usage:_Q(W.response?.usage)};break}case"response.incomplete":{J=!0;let X=_Q(W.response?.usage),B=W.response?.incomplete_details?.reason;if(B==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:B5(W.response?.content_filters),retryable:!1}},yield{type:"finish",reason:"error",usage:X};break}yield{type:"finish",reason:B==="max_output_tokens"?"length":"stop",usage:X};break}case"response.failed":case"error":{J=!0;let X=W.response?.error??W.error??W;yield{type:"error",error:K5(X)},yield{type:"finish",reason:"error",usage:_Q(W.response?.usage)};break}}if(J)return}if(!J)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield{type:"finish",reason:"error",usage:A()}}function X5(Q){let $=[],Z=[];return z2(Q.results??Q.tools??Q.loaded??Q.output,$,Z,0),{loaded:PQ($),namespaces:PQ(Z)}}function z2(Q,$,Z,G){if(!Array.isArray(Q)||G>4)return;for(let J of Q){if(typeof J==="string"){$.push(J);continue}if(!J||typeof J!=="object")continue;let Y=J,W=typeof Y.name==="string"?Y.name:typeof Y.tool_name==="string"?Y.tool_name:"",V=Y.tools??Y.functions;if(Array.isArray(V)){if(W)Z.push(W);z2(V,$,Z,G+1);continue}if(W)$.push(W)}}function PQ(Q){return Q.filter(($,Z)=>Q.indexOf($)===Z)}function B5(Q){if(!Array.isArray(Q))return"The provider's content filter blocked this request.";let Z=[];for(let G of Q){if(!G||typeof G!=="object")continue;let J=G,Y=J.content_filter_results;if(!Y||typeof Y!=="object")continue;for(let[W,V]of Object.entries(Y))if(V&&typeof V==="object"&&V.filtered===!0)Z.push(`${W} (${String(J.source_type??"unknown")})`)}return Z.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${PQ(Z).join(", ")}.`}function K5(Q){let $=typeof Q?.message==="string"?Q.message:"The provider stream failed.",Z=String(Q?.code??"").toLowerCase();if(Z==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(Z==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(Z.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function A(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function _Q(Q){if(!Q)return A();let $=Number(Q.input_tokens??0),Z=Number(Q.output_tokens??0),G={inputTokens:$,outputTokens:Z,totalTokens:Number(Q.total_tokens??$+Z)},J=Q.output_tokens_details?.reasoning_tokens;if(typeof J==="number")G.reasoningTokens=J;let Y=Q.input_tokens_details?.cached_tokens;if(typeof Y==="number")G.cachedInputTokens=Y;return G}async function*U2(Q){if(!Q)return;let $=Q.getReader(),Z=new TextDecoder;try{while(!0){let{done:J,value:Y}=await $.read();if(J)break;if(Y)yield Z.decode(Y,{stream:!0})}let G=Z.decode();if(G)yield G}finally{$.releaseLock()}}async function*MQ(Q,$,Z){let G;try{G=await NQ(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify($)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(J){let Y=R(J);if(Y.code!=="aborted")yield{type:"error",error:Y};yield{type:"finish",reason:Y.code==="aborted"?"aborted":"error",usage:A()};return}try{yield*H2(U2(G.body),{structuredOutput:Z.structuredOutput})}catch(J){let Y=R(J);if(Y.code==="aborted"){yield{type:"finish",reason:"aborted",usage:A()};return}yield{type:"error",error:Y},yield{type:"finish",reason:"error",usage:A()}}}async function qQ(Q,$){let Z=new FormData;Z.set("purpose","user_data"),Z.set("file",$);let J=await(await NQ(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:Z},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl})).json();if(!J?.id)throw Error("The provider accepted the upload but returned no file id.");return J.id}function SQ(Q){let $=H5(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Z=z5($);if(Z?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Z.major>1,toolSearch:D2(Z)};if(Z?.kind==="gpt")return{reasoning:Z.major>=5,structuredOutput:Z.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:Z.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:D2(Z)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function D2(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function H5(Q){return Q.trim().toLowerCase()}function z5(Q){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(Q);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let Z=/^o(\d+)(?:[-.]|$)/.exec(Q);if(Z?.[1])return{kind:"o",major:Number(Z[1]),minor:0};return null}function RQ(Q,$){let{capabilities:Z}=$,G={model:$.model,input:U5(Q.messages,Z),stream:!0};if(Q.systemPrompt)G.instructions=Q.systemPrompt;let J=P5(Q.tools,Z);if(J.length>0){if(G.tools=J,!Z.parallelToolCalls)G.parallel_tool_calls=!1}if(Q.output)G.text={format:{type:"json_schema",name:Q.output.name,schema:Q.output.schema,strict:!0}};if(Q.reasoning&&Z.reasoning)G.reasoning={effort:Q.reasoning,summary:"auto"};if(typeof Q.temperature==="number")G.temperature=Q.temperature;if(typeof Q.maxOutputTokens==="number")G.max_output_tokens=Q.maxOutputTokens;return G}function U5(Q,$){let Z=[];for(let G of Q){let J=G.role,Y=[],W=()=>{if(Y.length===0)return;Z.push({type:"message",role:J,content:Y}),Y=[]};for(let V of G.content??[])switch(V.type){case"text":{if(!V.text)break;Y.push(e(J,V.text));break}case"output":{if(V.partial)break;Y.push(e(J,JSON.stringify(V.value)));break}case"file":{if(J==="assistant")break;let X=j5(V);if(!$.fileInput){if(X)Y.push(e(J,O2(V,!1)));break}if(V.fileId?.startsWith(C))throw Error(`FilePart.fileId holds a gemi attachment id (${V.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(!V.fileId&&!X)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)Y.push(e(J,O2(V,!!V.fileId)));if(V.fileId)Y.push(L5(V));break}case"reasoning":{W();let X=N5(V);if(X)Z.push(X);break}case"tool-call":{if(V.partial)break;W(),Z.push({type:"function_call",call_id:V.toolCallId,name:String(V.name),arguments:JSON.stringify(V.input??{})});break}case"tool-result":{W(),Z.push({type:"function_call_output",call_id:V.toolCallId,output:_5(V)});break}}W()}return O5(Z)}var D5="No result was recorded for this tool call. Assume it did not complete.";function O5(Q){let $=new Set,Z=new Set,G=[];for(let Y of Q){if(Y.type==="function_call"){let W=String(Y.call_id);if($.has(W))continue;$.add(W)}else if(Y.type==="function_call_output"){let W=String(Y.call_id);if(!$.has(W)||Z.has(W))continue;Z.add(W)}G.push(Y)}if(Z.size===$.size)return G;let J=[];for(let Y of G){if(J.push(Y),Y.type!=="function_call")continue;let W=String(Y.call_id);if(Z.has(W))continue;Z.add(W),J.push({type:"function_call_output",call_id:W,output:D5})}return J}function e(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function j5(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(C)?$:void 0}function O2(Q,$){let Z=[`id=${JSON.stringify(Q.attachmentId)}`];if(Q.name)Z.push(`name=${JSON.stringify(Q.name)}`);if(Q.mimeType)Z.push(`mimeType=${JSON.stringify(Q.mimeType)}`);let G=`attachment ${Z.join(" ")}`;return $?`[${G}]`:`[${G} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function L5(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":F5(Q.name))?"input_image":"input_file",file_id:Q.fileId}}function F5(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&C5.has($[1])}var C5=new Set(["jpeg","jpg","png","gif","webp"]);function N5(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function _5(Q){if(Q.status==="ok")return typeof Q.output==="string"?Q.output:JSON.stringify(Q.output??null);if(Q.status==="denied"){let $=Q.reason?` Reason given: ${Q.reason}`:"";if(Q.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${Q.error?.code??"unknown"}): ${Q.error?.message??"no message"}`}function j2(Q){return Array.isArray(Q.tools)}function P5(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let J=[];for(let Y of Q)if(j2(Y))for(let W of Y.tools)J.push(QQ(W,!1));else J.push(QQ(Y,!1));return J}let Z=[],G=!1;for(let J of Q)if(j2(J)){let Y=J.tools.map((W)=>{if(W.deferred)G=!0;return QQ(W,!0)});Z.push({type:"namespace",name:J.name,description:J.description,tools:Y})}else{if(J.deferred)G=!0;Z.push(QQ(J,!0))}if(G)Z.push({type:"tool_search"});return Z}function QQ(Q,$){let Z={type:"function",name:Q.name,description:Q.description,parameters:Q.parameters,strict:Q.strict};if($&&Q.deferred)Z.defer_loading=!0;return Z}var F2=120000,C2=2;function T(Q){return typeof process>"u"?void 0:process.env?.[Q]}class $Q{static models(){return[]}normalizeError(Q){return R(Q)}}var N2=["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 TQ extends $Q{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=SQ(Q),this.config=$}static model(Q,$){return new TQ(Q,$)}static models(){return N2}stream(Q){let $=RQ(Q,{model:this.model,capabilities:this.capabilities});return MQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return qQ(this.endpoint(),Q)}baseURL(){return(this.config.baseURL??T("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,"")}endpoint(){let Q=this.baseURL(),$=this.config;return{responsesUrl:`${Q}/responses`,filesUrl:`${Q}/files`,headers:async()=>{let Z=$.apiKey??T("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...$.headers}},timeoutMs:$.timeoutMs??F2,maxRetries:$.maxRetries??C2}}}var M5="preview";function L2(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function q5(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}class kQ extends $Q{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=SQ(Q),this.config=$}static model(Q,$){return new kQ(Q,$)}static models(){return N2}stream(Q){let $=RQ(Q,{model:this.deployment(),capabilities:this.capabilities});return MQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return qQ(this.endpoint(),Q)}deployment(){return this.config.deployment??this.model}base(){let Q=this.config,$=Q.baseURL??Q.endpoint??T("AZURE_OPENAI_ENDPOINT");if($)return L2($);let Z=Q.resourceName??T("AZURE_OPENAI_RESOURCE_NAME")??T("AZURE_RESOURCE_NAME");return Z?L2(`https://${Z.trim()}.cognitiveservices.azure.com`):""}endpoint(){let Q=this.config,$=this.base(),Z=Q.apiVersion??T("AZURE_OPENAI_API_VERSION")??M5,G=q5(Z),J=`?api-version=${encodeURIComponent(Z)}`;return{responsesUrl:`${$}${G}/responses${J}`,filesUrl:`${$}${G}/files${J}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let Y=Q.apiKey??T("AZURE_OPENAI_API_KEY");return{...Y?{"api-key":Y}:{},...Q.headers}},timeoutMs:Q.timeoutMs??F2,maxRetries:Q.maxRetries??C2}}}class I extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(Q,$,Z){super(`Frame ${$} of run ${Q} has been evicted; the oldest frame still buffered is ${Z}. Reload the thread instead of resuming.`);this.runId=Q;this.requested=$;this.oldest=Z}}class y extends Error{runId;code="live_run_not_found";constructor(Q){super(`No live run ${Q} in this process.`);this.runId=Q}}class ZQ{ttlMs;maxFrames;runs=new Map;byThread=new Map;byClientRun=new Map;constructor(Q={}){this.ttlMs=Q.ttlMs??60000,this.maxFrames=Q.maxFrames??4096}register(Q,$={}){let Z={run:Q,threadId:$.threadId,clientRunId:$.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evictAt:null,wake:new Set,version:0};if(this.runs.set(Q.runId,Z),$.threadId)this.byThread.set($.threadId,Q.runId);if($.clientRunId)this.byClientRun.set($.clientRunId,Q.runId);return this.pump(Z,$)}findByClientRunId(Q){let $=this.byClientRun.get(Q);return $&&this.runs.has($)?$:null}async find(Q){let $=this.byThread.get(Q.threadId);if(!$)return null;let Z=this.runs.get($);if(!Z)return null;return{runId:$,seq:Z.lastSeq}}get(Q){return this.runs.get(Q)?.run??null}replay(Q,$){let Z=this.runs.get(Q);if(!Z)throw new y(Q);if($!==void 0&&$<Z.lostBefore)throw new I(Q,$,Z.lostBefore);let G=Z.frames[0]?.seq;return this.drain(Z,Q,$??G??Z.lastSeq+1)}clear(){for(let Q of this.runs.values()){if(Q.evictAt)clearTimeout(Q.evictAt);Q.ended=!0,this.notify(Q)}this.runs.clear(),this.byThread.clear(),this.byClientRun.clear()}get size(){return this.runs.size}async pump(Q,$){let Z=Promise.resolve();try{for await(let G of Q.run.frames()){if(Q.frames.push(G),Q.lastSeq=G.seq,Q.frames.length>this.maxFrames){let Y=Q.frames.shift();if(Y)Q.lostBefore=Y.seq+1}this.notify(Q);let J=$.onEvent;if(J)Z=Z.then(()=>J(G.event)).catch((Y)=>_2($,Y))}}catch(G){_2($,G)}finally{Q.ended=!0,this.notify(Q),this.scheduleEviction(Q),await Z}}async*drain(Q,$,Z){let G=Z;while(!0){let J=Q.version;for(;;){if(G<Q.lostBefore)throw new I($,G,Q.lostBefore);let Y=Q.frames,W=Y[0]?.seq;if(W===void 0)break;let V=Math.max(0,G-W);if(V>=Y.length)break;let X=Y[V];yield X,G=X.seq+1}if(Q.ended&&G>Q.lastSeq)return;await this.wait(Q,J)}}wait(Q,$){if(Q.version!==$)return Promise.resolve();return new Promise((Z)=>Q.wake.add(Z))}notify(Q){Q.version++;let $=Array.from(Q.wake);Q.wake.clear();for(let Z of $)Z()}scheduleEviction(Q){if(Q.evictAt)return;let $=setTimeout(()=>{let Z=Q.run.runId;if(this.runs.delete(Z),Q.threadId&&this.byThread.get(Q.threadId)===Z)this.byThread.delete(Q.threadId);if(Q.clientRunId&&this.byClientRun.get(Q.clientRunId)===Z)this.byClientRun.delete(Q.clientRunId);this.notify(Q)},this.ttlMs);$.unref?.(),Q.evictAt=$}}var EQ=new ZQ;function _2(Q,$){try{Q.onInternalError?.($)}catch{}}class GQ{ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor(Q={}){this.ttlMs=Q.ttlMs??86400000,this.clientOwnedIds=Q.clientOwnedIds??!1}async createThread(Q){let $=crypto.randomUUID();return this.threads.set($,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:$}}async loadThread(Q){this.sweep();let $=this.threads.get(Q);if(!$)return this.clientOwnedIds?[]:null;return $.touchedAt=Date.now(),$.messages.slice()}async appendMessages(Q,$){this.sweep();let Z=this.threads.get(Q);if(!Z){if(!this.clientOwnedIds)throw Error(`Thread ${Q} does not exist here, or has expired.`);Z={messages:[],touchedAt:Date.now()},this.threads.set(Q,Z)}for(let G of $){let J=Z.messages.findIndex((Y)=>Y.id===G.id);if(J===-1)Z.messages.push(G);else Z.messages[J]=G}Z.touchedAt=Date.now()}delete(Q){this.threads.delete(Q)}get size(){return this.threads.size}sweep(Q=Date.now()){if(Q-this.lastSweep<60000)return;this.lastSweep=Q;for(let[$,Z]of this.threads)if(Q-Z.touchedAt>this.ttlMs)this.threads.delete($)}}var xQ=new GQ;var S5=S2,JQ=new Map,P2=new WeakMap,YQ=new Map;class T2 extends S5{static kind="agent-controller";store=xQ;liveRuns=EQ;attachments=d;attachmentStorage=R2;hookHoldMs=30000;instructions(Q){}requireThread=!1;authorizeRequest(Q,$){}async stream(Q=new g){let $=await AQ(Q);if($.error)return WQ($);let Z=$.body,G=typeof Z.threadId==="string"?Z.threadId:void 0,J=T5(Z);if(J.error)return WQ({body:{},error:J.error});let Y=J.turn,W=typeof Z.clientRunId==="string"?Z.clientRunId:void 0;if(this.requireThread&&!G)return N(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});let V=W?{cancelled:!1}:null;if(V)YQ.set(W,V);let X=async()=>{let B;if(G){let F=await this.store.loadThread(G);if(!F)return N(404,{code:"thread_not_found",message:`Thread ${G} does not exist here, or has expired.`});B=F}else B=Array.isArray(Z.messages)?Z.messages:[];let K=await this.instructions(Q)||void 0,H=await this.attachmentsFor(Q,G);if(V?.cancelled)return M2();let z=this.agent.stream({messages:B,turn:Y,req:Q,threadId:G,instructions:K,attachments:H}),O={req:Q,runId:z.runId,threadId:G},D=this.liveRuns.register(z,{threadId:G,clientRunId:W,onEvent:(F)=>this.dispatchEvent(F,O),onInternalError:(F)=>this.reportHookFailure(F)}),{stored:U,hooks:j}=this.persistRun(z,O,D);return P2.set(z,U),Q.ctx?.()?.waitUntil(j),z.toResponse()};try{if(await this.authorizeRequest(Q,{route:"stream",threadId:G}),V?.cancelled)return M2();return G?await this.withThread(G,X):await X()}finally{if(V&&YQ.get(W)===V)YQ.delete(W)}}async withThread(Q,$){let Z=JQ.get(Q)??Promise.resolve(),G,J=new Promise((W)=>{G=W}),Y=Z.then(()=>J);JQ.set(Q,Y),await Z;try{let W=await this.liveRuns.find({threadId:Q}),V=W?this.liveRuns.get(W.runId):null;if(V)V.stop({reason:"superseded by a later turn on this thread"}),await P2.get(V);return await $()}finally{if(G(),JQ.get(Q)===Y)JQ.delete(Q)}}async attach(Q=new g){let $=await AQ(Q);if($.error)return WQ($);let Z=$.body,G=typeof Z.threadId==="string"?Z.threadId:x5(Q,"threadId");if(!G)return N(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(Q,{route:"attach",threadId:G});let J=await this.liveRuns.find({threadId:G});if(!J)return N(404,{code:"no_live_run",message:`No run in progress for thread ${G} in this process.`});let Y=typeof Z.runId==="string"?Z.runId:void 0,W=Y&&Y!==J.runId?void 0:E5(Q,Z);try{return oQ(this.liveRuns.replay(J.runId,W))}catch(V){if(V instanceof I)return N(410,{code:V.code,message:V.message,oldestSeq:V.oldest});if(V instanceof y)return N(404,{code:V.code,message:V.message});throw V}}async stop(Q=new g){let $=await AQ(Q);if($.error)return WQ($);let Z=$.body;await this.authorizeRequest(Q,{route:"stop",threadId:typeof Z.threadId==="string"?Z.threadId:void 0});let G=typeof Z.runId==="string"?Z.runId:void 0;if(!G&&typeof Z.clientRunId==="string"){if(G=this.liveRuns.findByClientRunId(Z.clientRunId)??void 0,!G){let Y=YQ.get(Z.clientRunId);if(Y)return Y.cancelled=!0,{stopped:!0}}}if(!G&&typeof Z.threadId==="string")G=(await this.liveRuns.find({threadId:Z.threadId}))?.runId;let J=G?this.liveRuns.get(G):null;if(!J)return{stopped:!1};return J.stop({reason:typeof Z.reason==="string"?Z.reason:void 0}),{stopped:!0}}attachmentScope(Q,$){let Z=Q.ctx()?.user,G=Z?.id??Z?.publicId;if(G!==void 0&&G!==null&&String(G)!=="")return{key:`user:${String(G)}`};if($)return{key:`thread:${$}`};return null}attachmentDestination(Q,$){return"both"}async attachmentsFor(Q,$){let Z=await this.attachmentScope(Q,$);if(!Z)return null;return new f(this.attachments,this.attachmentStorage,Z)}async upload(Q=new g){let $=await Q.rawRequest.formData(),Z=$.get("file");if(!(Z instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let G=Z instanceof File&&Z.name?Z.name:"upload",J=Z.type||"application/octet-stream",Y=$.get("threadId");await this.authorizeRequest(Q,{route:"upload",threadId:typeof Y==="string"&&Y.length>0?Y:void 0});let W=typeof Y==="string"&&Y.length>0&&await this.store.loadThread(Y)!==null?Y:void 0,V=await this.attachmentDestination(Z,Q),X=A5(V,$.get("destination")),B=await this.attachmentScope(Q,W),K=X!=="provider"&&!B;if(K){if(X==="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()`.');I5()}if(X==="provider"||!B){let j={fileId:await this.agent.provider.upload(Z),name:G,mimeType:J,size:Z.size,destination:"provider"};if(K)j.downgraded="no_scope";return j}let H=KQ(),z=await this.attachmentStorage.put({name:HQ(H,G),body:Z,contentType:J}),O=X==="both"?await this.agent.provider.upload(Z):void 0,D={id:H,scopeKey:B.key,fileId:O,objectName:z,name:G,mimeType:J,size:Z.size,createdAt:new Date().toISOString(),destination:X};return await this.attachments.put(B,D),{fileId:O,attachmentId:H,name:G,mimeType:J,size:Z.size,destination:X}}onMessage(Q,$){}onToolCall(Q,$){}onAwaitingInput(Q,$){}onError(Q,$){}onStreamComplete(Q,$){}reportHookFailure(Q){console.error("[gemi/ai] agent controller hook failed",Q)}async dispatchEvent(Q,$){switch(Q.type){case"tool-call":if(!Q.part.partial&&!Q.resent)await this.onToolCall({toolCallId:Q.part.toolCallId,name:String(Q.part.name),input:Q.part.input},$);return;case"awaiting-input":await this.onAwaitingInput(Q.pending,$);return;case"error":await this.onError(Q.error,$);return;default:return}}persistRun(Q,$,Z){let G=Promise.resolve(),J=(async()=>{let W;try{W=await Q.result()}catch(X){G=this.safely(()=>this.onError({code:"unknown",message:X instanceof Error?X.message:String(X),retryable:!1},$));return}let V=W.messages;if($.threadId&&V.length>0)try{await this.store.appendMessages($.threadId,V)}catch(X){this.reportHookFailure(X)}G=this.notifyRun(W,V,$)})(),Y=J.then(()=>b5(Promise.all([G,Z]).then(()=>{}),this.hookHoldMs));return{stored:J,hooks:Y}}async notifyRun(Q,$,Z){for(let G of $)await this.safely(()=>this.onMessage(G,Z));await this.safely(()=>this.onStreamComplete(Q,Z))}async safely(Q){try{await Q()}catch($){this.reportHookFailure($)}}}async function AQ(Q){let $=Q?.rawRequest;if(!$||$.method==="GET"||$.method==="HEAD"||!$.body)return{body:{}};if(!R5($.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let Z;try{Z=await $.text()}catch{return{body:{},error:"The request body could not be read."}}if(!Z.trim())return{body:{}};let G;try{G=JSON.parse(Z)}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 R5(Q){if(typeof Q!=="string")return!1;let[$]=Q.split(";",1);return $.trim().toLowerCase()==="application/json"}function WQ(Q){return N(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function T5(Q){let $=Q.turn&&typeof Q.turn==="object"?Q.turn:Q,Z={};if(typeof $.text==="string")Z.text=$.text;if(Array.isArray($.files)){let G=k5($.files);if(typeof G==="string")return{error:G};Z.files=G}if(Array.isArray($.toolResults))Z.toolResults=$.toolResults;return Object.keys(Z).length>0?{turn:Z}:{}}function k5(Q){let $=[];for(let[Z,G]of Q.entries()){let J=`turn.files[${Z}]`;if(!G||typeof G!=="object"||Array.isArray(G))return`${J} must be an object.`;let Y={};for(let K of["fileId","attachmentId","name","mimeType"]){let H=G[K];if(H===void 0||H===null||H==="")continue;if(typeof H!=="string")return`${J}.${K} must be a string.`;Y[K]=H}let{fileId:W,attachmentId:V,name:X,mimeType:B}=Y;if(W?.startsWith(C))return`${J}.fileId holds a gemi attachment id (${W}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(V!==void 0&&!V.startsWith(C))return`${J}.attachmentId is not a gemi attachment id: it must start with "${C}".`;if(!W&&!V)return`${J} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...W?{fileId:W}:{},...V?{attachmentId:V}:{},...X!==void 0?{name:X}:{},...B!==void 0?{mimeType:B}:{}})}return $}function E5(Q,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let G=Math.floor($.cursor);if(G>=0)return G+1;return}let Z=Q?.rawRequest?.headers?.get("Last-Event-ID");if(Z){let G=Number.parseInt(Z,10);if(Number.isFinite(G))return Math.max(0,G+1)}return}function x5(Q,$){let Z=Q?.search?.get($);return typeof Z==="string"?Z:void 0}function M2(){return N(409,{code:"stopped",message:"The turn was stopped before it started."})}function N(Q,$){return new Response(JSON.stringify({error:$}),{status:Q,headers:{"Content-Type":"application/json"}})}function A5(Q,$){if(typeof $!=="string"||$.length===0)return Q;if($!=="both"&&$!=="provider"&&$!=="storage")throw Error(`Unknown attachment destination "${$}". Expected "both", "provider" or "storage".`);if($===Q||Q==="both"&&$==="storage")return $;if(Q==="both"&&$==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${$}" destination, but the server's policy for it is "${Q}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var q2=!1;function I5(){if(q2)return;q2=!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 w5=2147483647;function b5(Q,$){let Z=Q.then(()=>{},()=>{});if(!($<=w5))return Z;let G,J=new Promise((Y)=>{G=setTimeout(Y,$)});return Promise.race([Z,J]).finally(()=>clearTimeout(G))}export{s2 as toAgentTools,v5 as s,EQ as liveRuns,d as defaultAttachmentStore,xQ as defaultAgentStore,t as ToolNamespace,FQ as Skill,f as ScopedAttachments,h as SKILLS_NAMESPACE,M as PendingEscalation,TQ as OpenAIProvider,ZQ as MemoryLiveRuns,l as MemoryAttachmentStore,GQ as MemoryAgentStore,y as LiveRunNotFoundError,x as InvalidAttachmentScopeError,I as FrameCursorEvictedError,kQ as AzureOpenAIProvider,v as AttachmentNotFoundError,S as AgentTool,$Q as AgentProvider,T2 as AgentController,CQ as Agent};
|
|
15
|
+
`):void 0}async runTools(Q,$,Z){let G=[],J=[];for(let W of $){let Y=this.config.registry.get(String(W.name));if(!Y){this.addResult(Q,{type:"tool-result",toolCallId:W.toolCallId,name:W.name,status:"error",error:{code:"tool_error",message:`There is no tool named "${String(W.name)}".`,toolCallId:W.toolCallId,retryable:!0}});continue}let X=Y.tool.inputSchema.safeParse(W.input);if(X.ok===!1){this.addResult(Q,{type:"tool-result",toolCallId:W.toolCallId,name:W.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${String(W.name)}": ${X.errors.join(", ")}`,toolCallId:W.toolCallId,retryable:!0}});continue}W.input=X.value;let V=G2(Y.tool);if(V){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(W));continue}G.push({toolCallId:W.toolCallId,name:W.name,input:X.value,kind:V,signature:gQ(this.claimsFor(W.toolCallId,String(W.name),V,X.value)),...this.pathPrefix.length>0?{path:[...this.pathPrefix]}:{}});continue}J.push(this.executeTool(Y,Q.id,W,X.value,Z).then(async(B)=>{this.addResult(Q,B),await this.settleShown(W.toolCallId)}).catch((B)=>{if(B instanceof q){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(W));return}G.push(...B.pending);return}}))}return await n(Promise.all(J).then(()=>{return}),this.controller.signal),G}claimsFor(Q,$,Z,G){return{runId:this.signingRunId,toolCallId:Q,name:$,kind:Z,input:G,path:this.pathPrefix.length>0?[...this.pathPrefix]:void 0}}deniedByPolicy(Q){return{type:"tool-result",toolCallId:Q.toolCallId,name:Q.name,status:"denied",cause:"refused",reason:`"${String(Q.name)}" needs the user, and this run was started with onPending: "deny". Answer from what you already have.`}}async executeTool(Q,$,Z,G,J,W){let Y={req:this.params.req,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,toolCallId:Z.toolCallId,signal:this.controller.signal,step:J,depth:this.depth,resumed:W!==void 0,attachments:this.toolAttachments(Z),turn:this.toolTurn($),runAgent:this.nestedRunner($,Z,W)};try{let X=Q.tool.execute(G,Y),V;if(l2(X)){let B=await X.next();while(!B.done)this.emit({type:"tool-progress",toolCallId:Z.toolCallId,data:B.value}),B=await X.next();V=B.value}else V=await X;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"ok",output:V}}catch(X){if(X instanceof S||this.controller.signal.aborted)throw new S;if(X instanceof q)throw X;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:{code:"tool_error",message:X instanceof Error?X.message:String(X),toolCallId:Z.toolCallId,retryable:!0}}}}nestedRunner(Q,$,Z){let G=new FQ(()=>$.nested,()=>$.nested=[]);return async(J,W={})=>{let{at:Y,recorded:X,write:V}=G.next();if(X){let B=o2(X,J,W);if(B)throw Error(`Nested run ${Y} of "${String($.name)}" ${B}. `+"runAgent is memoized by call index, so a body whose runAgent calls depend on a condition that changed between turns cannot be resumed \u2014 the answer would be paired with a different sub-run. "+"Make the sequence of runAgent calls, and what each one is asked, the same every time this tool runs, or branch on ctx.resumed.");if(X.finishReason!=="awaiting-input")return{runId:X.runId,agent:X.agent,messages:X.messages,finishReason:X.finishReason??"stop",usage:X.usage??o(),output:rQ(X.messages),nested:X}}return this.runNested(Q,$,J,W,V,X,Z?.answers??[])}}async runNested(Q,$,Z,G,J,W,Y){let X=[...this.chain,Z.name];if(this.chain.includes(Z.name))throw Error(`"${Z.name}" is already running further up this chain: ${X.join(" -> ")}. An agent cannot run itself, directly or through another agent.`);let V=this.depth+1;if(V>this.maxDepth)throw Error(`Nested agent runs are ${this.maxDepth} deep at most and this one would be ${V}: ${X.join(" -> ")}. Raise maxDepth on the agent at the root of the run if the tree is meant to be this deep.`);let B=G.label,K=[...this.pathPrefix,$.toolCallId],H=this.onPending==="deny"?"deny":G.onPending??"escalate",z=W!==void 0,O=z?s(W.messages):new Set,D=z?Y.filter((F)=>{let x=Z2(F.path,K);if(x===null)return!1;return O.has(x.length>0?x[0]:F.toolCallId)}):[],U=Z.stream({messages:z?W.messages:G.messages??[],turn:z?{toolResults:D}:G.prompt?{text:G.prompt}:void 0,req:this.params.req,attachments:this.params.attachments,body:this.params.body,signal:this.controller.signal,threadId:this.params.threadId,instructions:G.instructions,maxOutputTokens:G.maxOutputTokens,temperature:G.temperature,runId:z?W.runId:void 0,nesting:{depth:V,maxDepth:this.maxDepth,chain:X,signingRunId:this.signingRunId,signingPath:K,onPending:H}}),j=[],_=(async()=>{for await(let F of U){if(F.type==="awaiting-input")j=F.pending;this.emit({type:"nested-event",toolCallId:$.toolCallId,runId:U.runId,agent:Z.name,label:B,event:F})}})(),L=(async()=>{let F=await U.result();await _;let x=z?aQ(W.messages,F.messages):aQ(G.messages??[],F.messages),wQ={runId:U.runId,agent:Z.name,label:B,messages:x,finishReason:F.finishReason,usage:z?OQ(W.usage??o(),F.usage):F.usage,...F.finishReason==="awaiting-input"?{signature:mQ({runId:this.signingRunId,path:K,nestedRunId:U.runId,open:[...s(x)],input:$.input})}:{}};return J(wQ),this.usage=OQ(this.usage,F.usage),{result:F,record:wQ}})(),b=L.then(()=>{return},()=>{return});this.nestedSettling.add(b);let u,P;try{({result:u,record:P}=await L)}finally{this.nestedSettling.delete(b)}if(this.controller.signal.aborted)throw new S;if(u.finishReason==="awaiting-input"){if(j.length===0)throw Error(`"${Z.name}" ended awaiting input but asked nothing, so there is no question to escalate.`);throw this.emit({type:"tool-call",messageId:Q,part:$,resent:!0}),new q({pending:j,path:K,nested:P})}return{runId:P.runId,agent:Z.name,messages:P.messages,finishReason:u.finishReason,usage:P.usage??o(),output:u.output??rQ(P.messages),nested:P}}addResult(Q,$){Q.content.push($),this.emit({type:"tool-result",messageId:Q.id,part:$})}toolAttachments(Q){let $=this.params.attachments??null,Z=new FQ(()=>Q.attachments,()=>Q.attachments=[],()=>({failed:!0})),G=()=>{if(!$)throw new A("This request has no attachment scope, so a tool cannot store or read files on it. `attachmentScope()` returned null \u2014 put the chat route behind authentication, send a `threadId`, or override `attachmentScope()` on the controller.");return $};return{get:(J)=>G().get(J),read:(J)=>G().read(J),file:(J)=>G().file(J),put:async(J,W={})=>{let{at:Y,recorded:X,write:V}=Z.next();if(X&&"attachment"in X){let U=n2(X,J,W);if(U)throw Error(`Attachment ${Y} of "${String(Q.name)}" ${U}. `+"ctx.attachments.put is memoized by call index within a tool call, so a body whose put calls depend on a condition that changed between turns cannot be replayed \u2014 the model would be shown a file under an id that names different bytes. "+"Make the sequence of put calls the same every time this tool runs, or branch on ctx.resumed.");if(X.shown)this.queueShown(Q.toolCallId,X);return X.attachment}let B=G(),K=W.mimeType||J.type||"",H=W.name??(J instanceof File?J.name:"attachment"),z;if(W.showModel){let U=this.config.provider;if(!U.capabilities.fileInput)throw Error(`"${String(Q.name)}" asked to show a file to ${U.model}, which does not accept file input. Drop \`showModel\` for this provider, or run this agent on a model that takes files \u2014 \`capabilities.fileInput\` is what says which do.`);z=await U.upload(new File([J],H,{type:K||void 0}))}let O=await B.put(J,{name:H,mimeType:K,fileId:z}),D={attachment:O,...z?{shown:{fileId:z,messageId:`msg_${crypto.randomUUID()}`,createdAt:new Date().toISOString()}}:{}};if(V(D),D.shown)this.queueShown(Q.toolCallId,D);return O}}}toolTurn(Q){let $=this.history.findIndex((W)=>W.id===Q),Z=Q2(this.history),G;for(let W=$-1;W>=0;W--){let Y=this.history[W];if(Y.role!=="user"||Z.has(Y.id))continue;G=Y;break}let J=[];for(let W of G?.content??[]){if(W.type!=="file")continue;let Y=W.attachmentId;if(typeof Y!=="string"||!Y.startsWith(C))continue;if(!J.includes(Y))J.push(Y)}return Object.freeze({attachments:Object.freeze(J)})}queueShown(Q,$){let Z=$.shown;if(!Z)return;let G=this.shownQueue.get(Q)??[];if(G.some((J)=>J.id===Z.messageId))return;G.push({id:Z.messageId,role:"user",content:[{type:"file",fileId:Z.fileId,name:$.attachment.name,mimeType:$.attachment.mimeType,attachmentId:$.attachment.id}],createdAt:Z.createdAt,finishReason:"stop"}),this.shownQueue.set(Q,G)}async settleShown(Q){let $=this.shownQueue.get(Q);if(!$||$.length===0)return;if(this.shownQueue.delete(Q),this.ended||this.controller.signal.aborted)return;for(let Z of $){if(this.history.some((G)=>G.id===Z.id))continue;this.history.push(Z),this.produced.push(Z),this.emit({type:"message",message:Z}),this.unreported.add(Z)}}historyForProvider(Q){let $=this.history.filter((W)=>W!==Q),Z=Q2($),G=[];for(let W of $){if(!Z.has(W.id))continue;for(let Y of W.content)if(Y.type==="file")G.push(Y)}if(G.length<=$2)return $;let J=new Set(G.slice(0,G.length-$2));return $.map((W)=>{if(!W.content.some((Y)=>Y.type==="file"&&J.has(Y)))return W;return{...W,content:W.content.map((Y)=>Y.type==="file"&&J.has(Y)?{type:"text",text:`[A ${Y.mimeType||"file"} produced by a tool (attachment ${Y.attachmentId}) was attached here and has been dropped from this request: only the most recent tool-produced file is kept attached, to keep the context bounded. Call the tool again if you need to look at it.]`}:Y)}})}async ingestTurn(){let Q=this.params.turn,$=this.openCalls(),Z=[];if($.length>0){let G=new Set,J=new Set,W=new Map;for(let Y of Q?.toolResults??[]){let X=`${(Y.path??[]).join("/")}#${Y.toolCallId}`;if(J.has(X))continue;J.add(X);let V=(z)=>this.emit({type:"error",error:{code:"invalid_tool_result",message:z,toolCallId:Y.toolCallId,retryable:!1}}),B=Z2(Y.path,this.pathPrefix);if(B===null){V(`The answer for "${Y.toolCallId}" is addressed to a tool call this run is not inside.`);continue}if(B.length>0){let z=B[0],O=$.find((j)=>j.call.toolCallId===z);if(!O){V(`No pending tool call with id "${z}" to deliver a nested answer to.`);continue}let D=this.parkedBelow(O.call,B,Y.toolCallId);if(D.ok===!1){let j=`The answer for "${Y.toolCallId}" is addressed under "${z}", which`;V(D.reason==="unparked"?`${j} has no sub-agent run waiting on that question.`:D.reason==="expired"?`${j} parked a sub-agent run that has since expired. Ask again.`:`${j} carries a record of a parked sub-agent run the server did not sign.`);continue}let U=W.get(z);if(!U){if(!dQ(D.signature)){V(`The answer for "${Y.toolCallId}" is addressed under "${z}", which has already been re-entered on that record. Ask again.`);continue}U=[],W.set(z,U),G.add(z)}U.push(Y);continue}let K=$.find((z)=>z.call.toolCallId===Y.toolCallId);if(!K){V(`No pending tool call with id "${Y.toolCallId}".`);continue}let H=await this.resolveAnswer(K,Y,Z);if(H===null)continue;if(G.add(Y.toolCallId),H!=="open")this.attachToHistory(K,H),await this.settleShown(Y.toolCallId)}for(let[Y,X]of W){let V=$.find((K)=>K.call.toolCallId===Y),B=await this.reenter(V,X,Z);if(B)this.attachToHistory(V,B),await this.settleShown(Y)}for(let Y of $){if(G.has(Y.call.toolCallId))continue;this.attachToHistory(Y,{type:"tool-result",toolCallId:Y.call.toolCallId,name:Y.call.name,status:"denied",cause:"refused"})}await this.reportDeferred()}if(Q&&(Q.text||Q.files&&Q.files.length>0)){let G={id:`msg_${crypto.randomUUID()}`,role:"user",content:[...Q.text?[{type:"text",text:Q.text}]:[],...(Q.files??[]).map((J)=>({type:"file",...J.fileId?{fileId:J.fileId}:{},name:J.name,mimeType:J.mimeType,...J.attachmentId?{attachmentId:J.attachmentId}:{}}))],createdAt:new Date().toISOString(),finishReason:"stop"};this.history.push(G),this.produced.push(G),await this.report(G)}return Z}parkedBelow(Q,$,Z){let G=$.length>1?$[1]:Z,J=[...this.pathPrefix,Q.toolCallId],W=(Q.nested??[]).find((X)=>X.finishReason==="awaiting-input"&&s(X.messages).has(G));if(!W)return{ok:!1,reason:"unparked"};if(typeof W.signature!=="string")return{ok:!1,reason:"unsigned"};let Y=pQ(W.signature,{path:J,nestedRunId:W.runId,open:[...s(W.messages)],input:Q.input});if(Y.ok===!1)return{ok:!1,reason:Y.reason==="expired"?"expired":"unsigned"};return{ok:!0,signature:W.signature}}async reenter(Q,$,Z){let G=String(Q.call.name),J=this.config.registry.get(G);if(!J||!J.tool.execute)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_result",message:`The tool "${G}" no longer exists, so the sub-agent's question cannot be delivered.`,toolCallId:Q.call.toolCallId,retryable:!1}};let W=J.tool.inputSchema.safeParse(Q.call.input);if(W.ok===!1)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${G}": ${W.errors.join(", ")}`,toolCallId:Q.call.toolCallId,retryable:!0}};let Y=this.amendCall(Q);Y.input=W.value;try{return await n(this.executeTool(J,Q.message.id,Y,W.value,0,{answers:$}),this.controller.signal)}catch(X){if(X instanceof q)return Z.push(...X.pending),null;throw X}}amendCall(Q){let $=this.amend(Q.message),Z=$.content.indexOf(Q.call),G={...Q.call,nested:(Q.call.nested??[]).map((J)=>({...J})),...Q.call.attachments?{attachments:Q.call.attachments.map((J)=>({...J}))}:{}};if(Z>=0)$.content[Z]=G;return this.unreported.add($),G}openCalls(){let Q=new Set;for(let Z of this.history)for(let G of Z.content)if(G.type==="tool-result")Q.add(G.toolCallId);let $=[];for(let Z of this.history)for(let G of Z.content)if(G.type==="tool-call"&&!Q.has(G.toolCallId))$.push({message:Z,call:G});return $}async resolveAnswer(Q,$,Z){let G=Q.call,J=String(G.name),W=this.config.registry.get(J),Y=(K)=>{return this.emit({type:"error",error:{code:"invalid_tool_result",message:K,toolCallId:G.toolCallId,retryable:!1}}),null};if(!W)return Y(`The tool "${J}" no longer exists, so its answer cannot be checked.`);let X=G2(W.tool);if(!X)return Y(`"${J}" is a server tool with no pending question.`);if(typeof $.signature!=="string"||$.signature.length===0)return Y(`The answer for "${J}" carried no signature.`);let V=p($.signature);if(!V)return Y(`The signature for "${J}" is malformed.`);let B=uQ($.signature,{...this.claimsFor(G.toolCallId,J,X,G.input),runId:V.runId});if(B.ok===!1)return Y(B.reason==="expired"?`The approval for "${J}" has expired. Ask again.`:`The answer for "${J}" does not match the call the server made.`);if(!lQ($.signature))return Y(`The answer for "${J}" has already been used. Ask again.`);if("approve"in $){if(X!=="approval")return Y(`"${J}" is answered by the client, not approved.`);if($.approve===!0){let K=this.amendCall(Q);try{return await n(this.executeTool(W,Q.message.id,K,K.input,0),this.controller.signal)}catch(H){if(H instanceof q)return Z.push(...H.pending),"open";throw H}}return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"denied",cause:"refused",reason:$.reason}}if("output"in $){if(X==="approval")return Y(`"${J}" is approved, not answered: the server produces its result.`);let K=W.tool.outputSchema,H=K?K.safeParse($.output):{ok:!0,value:$.output};if(H.ok===!1)return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"error",error:{code:"invalid_tool_result",message:`The answer for "${J}" did not match its output schema: ${H.errors.join(", ")}`,toolCallId:G.toolCallId,retryable:!0}};return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"ok",output:H.value}}return Y(`The answer for "${J}" carried neither an approval nor an output.`)}attachToHistory(Q,$){let Z=this.amend(Q.message);Z.content.push($),this.unreported.add(Z),this.emit({type:"tool-result",messageId:Z.id,part:$})}amend(Q){let $=this.amended.get(Q.id);if($)return $;let Z={...Q,content:[...Q.content]},G=this.history.indexOf(Q);if(G>=0)this.history[G]=Z;return this.produced.push(Z),this.amended.set(Q.id,Z),Z}async reportDeferred(){let Q=[...this.unreported];this.unreported.clear();for(let $ of Q)await this.report($)}async finalizeAborted(){if(this.nestedSettling.size>0)await Promise.all([...this.nestedSettling]);for(let $ of this.openCalls()){if($.message===this.current)continue;this.attachToHistory($,{type:"tool-result",toolCallId:$.call.toolCallId,name:$.call.name,status:"denied",cause:"stopped",reason:this.stopReason})}await this.reportDeferred();let Q=this.current;if(Q){let $=new Set(Q.content.filter((Z)=>Z.type==="tool-result").map((Z)=>Z.toolCallId));for(let Z of[...Q.content]){if(Z.type!=="tool-call"||$.has(Z.toolCallId))continue;delete Z.partial,this.addResult(Q,{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"denied",cause:"stopped",reason:this.stopReason})}}this.finishReason="aborted",await this.finalizeMessage("aborted")}}function G2(Q){if(Q.answeredBy==="client")return Q.inputSchema===LQ?"question":"client";return Q.requiresApproval?"approval":null}function J2(Q){if(!Q||!Q.trim())return{};try{return JSON.parse(Q)}catch{return Q}}function s2(Q){if(Q.length>0)Q[0];return Q}function t2(Q,$,Z){let G=Q.content[Q.content.length-1];if(G&&G.type===$){G.text=(G.text??"")+Z;return}Q.content.push($==="text"?{type:"text",text:Z}:{type:"reasoning",text:Z})}function a2(Q,$,Z){let G=Q.content[Q.content.length-1];if(G&&G.type==="reasoning"&&G.id===$){G.text=(G.text??"")+Z;return}Q.content.push($?{type:"reasoning",id:$,text:Z}:{type:"reasoning",text:Z})}function r2(Q,$){return Q.descriptors($).map((Z)=>R.create({name:Z.name,description:Z.description,inputSchema:Z.inputSchema,requiresApproval:Z.requiresApproval,execute:(G,J)=>Q.execute({kind:"local",req:J.req},Z.name,G,J)}))}class r extends Error{status;body;requestId;constructor(Q,$,Z){super(`Provider request failed with status ${Q}: ${e2($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=Z}}class e extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function e2(Q){let $=V2(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function V2(Q){if(!Q||typeof Q!=="object")return null;let $=Q,G=$.error&&typeof $.error==="object"?$.error:Q;if(typeof G.message!=="string"&&typeof G.code!=="string"&&typeof G.type!=="string")return null;let J=G.innererror?.code??G.code;return{message:G.message,type:G.type,code:J,param:G.param}}function k(Q){if(Q instanceof e)return{code:"provider_error",message:Q.message,retryable:!0};if(G5(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof r)return Q5(Q.status,V2(Q.body),Q.message);if(Q instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${Q.message}`,retryable:!0};if(Q instanceof Error)return{code:"provider_error",message:Q.message,retryable:!1};return{code:"unknown",message:String(Q),retryable:!1}}function Q5(Q,$,Z){let G=$?.message??Z,J=($?.code??"").toLowerCase(),W=($?.type??"").toLowerCase(),Y=`${J} ${W} ${G}`.toLowerCase();if(Q===429){let X=J==="insufficient_quota"||Y.includes("quota");return{code:"rate_limited",message:G,retryable:!X}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:G,retryable:!0};if($5(Y))return{code:"context_length_exceeded",message:G,retryable:!1};if(Z5(Y))return{code:"content_filtered",message:G,retryable:!1};if($?.param?.startsWith("tools")||Y.includes("invalid schema for function"))return{code:"invalid_tool_input",message:G,retryable:!1};return{code:"provider_error",message:G,retryable:!1}}function $5(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function Z5(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function G5(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}var J5=500,K2=20000;function W5(Q,$){if(!Q)return;let Z=Q.trim();if(/^\d+(\.\d+)?$/.test(Z))return Math.max(0,Number(Z)*1000);let G=Date.parse(Z);if(Number.isNaN(G))return;return Math.max(0,G-$)}function B2(Q,$){let Z=Math.min(K2,J5*2**Q);return Math.round(Z*(0.5+$()*0.5))}function Y5(Q){return Q===429||Q===408||Q===409||Q>=500}function X5(Q,$){return Y5(Q)&&k($).retryable}function H2(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function V5(Q,$){return new Promise((Z,G)=>{let J=setTimeout(Z,Q);$?.addEventListener("abort",()=>{clearTimeout(J),G(H2($))},{once:!0})})}async function _Q(Q,$,Z){let G=Z.fetchImpl??((K,H)=>fetch(K,H)),J=Z.sleep??V5,W=Z.random??Math.random,Y=Z.now??Date.now,X=Math.max(0,Z.maxRetries),V=async(K)=>{let H=Z.signal;if(!H)return await J(K);H.throwIfAborted();let z;try{await Promise.race([J(K,H),new Promise((O,D)=>{z=()=>D(H2(H)),H.addEventListener("abort",z,{once:!0})})])}finally{if(z)H.removeEventListener("abort",z)}},B;for(let K=0;K<=X;K++){Z.signal?.throwIfAborted();let H=new AbortController,z=()=>H.abort(Z.signal?.reason);Z.signal?.addEventListener("abort",z,{once:!0});let O=!1,D=Z.timeoutMs>0?setTimeout(()=>{O=!0,H.abort()},Z.timeoutMs):void 0,U;try{U=await G(Q,{...$,signal:H.signal})}catch(b){if(D!==void 0)clearTimeout(D);if(Z.signal?.removeEventListener("abort",z),Z.signal?.aborted)throw b;if(B=O?new e(Z.timeoutMs):b,K===X)throw B;await V(B2(K,W));continue}if(D!==void 0)clearTimeout(D);if(U.ok)return U;Z.signal?.removeEventListener("abort",z);let j=await B5(U),_=new r(U.status,j,U.headers.get("x-request-id")??void 0);if(K===X||!X5(U.status,_))throw _;let L=W5(U.headers.get("retry-after"),Y());await V(L===void 0?B2(K,W):Math.min(L,K2)),B=_}throw B??Error("Provider request failed with no response.")}async function B5(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}async function*K5(Q){let $="",Z="",G=[],J,W=()=>{if(G.length===0&&!Z)return null;let V={event:Z,data:G.join(`
|
|
16
|
+
`),id:J};return Z="",G=[],J=void 0,V.data?V:null},Y=(V)=>{let B=V.endsWith("\r")?V.slice(0,-1):V;if(B==="")return W();if(B.startsWith(":"))return null;let K=B.indexOf(":"),H=K===-1?B:B.slice(0,K),z=K===-1?"":B.slice(K+1);if(z.startsWith(" "))z=z.slice(1);if(H==="event")Z=z;else if(H==="data")G.push(z);else if(H==="id")J=z;return null};for await(let V of Q){$+=V;let B=$.indexOf(`
|
|
17
|
+
`);while(B!==-1){let K=$.slice(0,B);$=$.slice(B+1);let H=Y(K);if(H)yield H;B=$.indexOf(`
|
|
18
|
+
`)}}if($.length>0){let V=Y($);if(V)yield V}let X=W();if(X)yield X}async function*z2(Q,$={}){let Z=new Map,G=new Set,J=!1;for await(let W of K5(Q)){if(W.data==="[DONE]")break;let Y;try{Y=JSON.parse(W.data)}catch{continue}switch(typeof Y.type==="string"?Y.type:W.event){case"response.output_text.delta":{let V=String(Y.delta??"");if(!V)break;yield $.structuredOutput?{type:"output-delta",delta:V}:{type:"text-delta",delta:V};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let V=String(Y.delta??"");if(!V)break;yield{type:"reasoning-delta",delta:V,id:Y.item_id};break}case"response.output_item.added":{let V=Y.item;if(!V)break;if(V.type==="function_call"){let B=String(V.id??Y.item_id??V.call_id??"");Z.set(B,{callId:String(V.call_id??B),name:String(V.name??""),namespace:typeof V.namespace==="string"&&V.namespace?V.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let V=Z.get(String(Y.item_id??""));if(!V)break;let B=String(Y.delta??"");if(!B)break;yield{type:"tool-call-delta",toolCallId:V.callId,name:V.name,argsDelta:B,...V.namespace?{namespace:V.namespace}:{}};break}case"response.function_call_arguments.done":{let V=String(Y.item_id??""),B=Z.get(V);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 V=Y.item;if(!V)break;if(V.type==="function_call"){let B=String(V.id??Y.item_id??V.call_id??""),K=Z.get(B);if(K?.done)break;let H=(typeof V.namespace==="string"?V.namespace:"")||K?.namespace;if(yield{type:"tool-call",toolCallId:String(V.call_id??B),name:String(V.name??K?.name??""),args:String(V.arguments??""),...H?{namespace:H}:{}},K)K.done=!0;break}if(V.type==="tool_search_call"||V.type==="tool_search_output"){let B=H5(V);if(B.loaded.length===0&&B.namespaces.length===0)break;let K=String(V.tool_search_call_id??V.id??"");if(G.has(K))break;G.add(K),yield{type:"tool-search",...B}}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":{J=!0,yield{type:"finish",reason:"stop",usage:PQ(Y.response?.usage)};break}case"response.incomplete":{J=!0;let V=PQ(Y.response?.usage),B=Y.response?.incomplete_details?.reason;if(B==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:z5(Y.response?.content_filters),retryable:!1}},yield{type:"finish",reason:"error",usage:V};break}yield{type:"finish",reason:B==="max_output_tokens"?"length":"stop",usage:V};break}case"response.failed":case"error":{J=!0;let V=Y.response?.error??Y.error??Y;yield{type:"error",error:U5(V)},yield{type:"finish",reason:"error",usage:PQ(Y.response?.usage)};break}}if(J)return}if(!J)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield{type:"finish",reason:"error",usage:I()}}function H5(Q){let $=[],Z=[];return U2(Q.results??Q.tools??Q.loaded??Q.output,$,Z,0),{loaded:MQ($),namespaces:MQ(Z)}}function U2(Q,$,Z,G){if(!Array.isArray(Q)||G>4)return;for(let J of Q){if(typeof J==="string"){$.push(J);continue}if(!J||typeof J!=="object")continue;let W=J,Y=typeof W.name==="string"?W.name:typeof W.tool_name==="string"?W.tool_name:"",X=W.tools??W.functions;if(Array.isArray(X)){if(Y)Z.push(Y);U2(X,$,Z,G+1);continue}if(Y)$.push(Y)}}function MQ(Q){return Q.filter(($,Z)=>Q.indexOf($)===Z)}function z5(Q){if(!Array.isArray(Q))return"The provider's content filter blocked this request.";let Z=[];for(let G of Q){if(!G||typeof G!=="object")continue;let J=G,W=J.content_filter_results;if(!W||typeof W!=="object")continue;for(let[Y,X]of Object.entries(W))if(X&&typeof X==="object"&&X.filtered===!0)Z.push(`${Y} (${String(J.source_type??"unknown")})`)}return Z.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${MQ(Z).join(", ")}.`}function U5(Q){let $=typeof Q?.message==="string"?Q.message:"The provider stream failed.",Z=String(Q?.code??"").toLowerCase();if(Z==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(Z==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(Z.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function I(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function PQ(Q){if(!Q)return I();let $=Number(Q.input_tokens??0),Z=Number(Q.output_tokens??0),G={inputTokens:$,outputTokens:Z,totalTokens:Number(Q.total_tokens??$+Z)},J=Q.output_tokens_details?.reasoning_tokens;if(typeof J==="number")G.reasoningTokens=J;let W=Q.input_tokens_details?.cached_tokens;if(typeof W==="number")G.cachedInputTokens=W;return G}async function*D2(Q){if(!Q)return;let $=Q.getReader(),Z=new TextDecoder;try{while(!0){let{done:J,value:W}=await $.read();if(J)break;if(W)yield Z.decode(W,{stream:!0})}let G=Z.decode();if(G)yield G}finally{$.releaseLock()}}async function*qQ(Q,$,Z){let G;try{G=await _Q(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify($)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(J){let W=k(J);if(W.code!=="aborted")yield{type:"error",error:W};yield{type:"finish",reason:W.code==="aborted"?"aborted":"error",usage:I()};return}try{yield*z2(D2(G.body),{structuredOutput:Z.structuredOutput})}catch(J){let W=k(J);if(W.code==="aborted"){yield{type:"finish",reason:"aborted",usage:I()};return}yield{type:"error",error:W},yield{type:"finish",reason:"error",usage:I()}}}async function SQ(Q,$){let Z=new FormData;Z.set("purpose","user_data"),Z.set("file",$);let J=await(await _Q(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:Z},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl})).json();if(!J?.id)throw Error("The provider accepted the upload but returned no file id.");return J.id}function RQ(Q){let $=D5(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Z=O5($);if(Z?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Z.major>1,toolSearch:O2(Z)};if(Z?.kind==="gpt")return{reasoning:Z.major>=5,structuredOutput:Z.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:Z.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:O2(Z)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function O2(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function D5(Q){return Q.trim().toLowerCase()}function O5(Q){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(Q);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let Z=/^o(\d+)(?:[-.]|$)/.exec(Q);if(Z?.[1])return{kind:"o",major:Number(Z[1]),minor:0};return null}function kQ(Q,$){let{capabilities:Z}=$,G={model:$.model,input:j5(Q.messages,Z),stream:!0};if(Q.systemPrompt)G.instructions=Q.systemPrompt;let J=S5(Q.tools,Z);if(J.length>0){if(G.tools=J,!Z.parallelToolCalls)G.parallel_tool_calls=!1}if(Q.output)G.text={format:{type:"json_schema",name:Q.output.name,schema:Q.output.schema,strict:Q.output.strict}};if(Q.reasoning&&Z.reasoning)G.reasoning={effort:Q.reasoning,summary:"auto"};if(typeof Q.temperature==="number")G.temperature=Q.temperature;if(typeof Q.maxOutputTokens==="number")G.max_output_tokens=Q.maxOutputTokens;return G}function j5(Q,$){let Z=[];for(let G of Q){let J=G.role,W=[],Y=()=>{if(W.length===0)return;Z.push({type:"message",role:J,content:W}),W=[]};for(let X of G.content??[])switch(X.type){case"text":{if(!X.text)break;W.push(QQ(J,X.text));break}case"output":{if(X.partial)break;W.push(QQ(J,JSON.stringify(X.value)));break}case"file":{if(J==="assistant")break;let V=C5(X);if(!$.fileInput){if(V)W.push(QQ(J,j2(X,!1)));break}if(X.fileId?.startsWith(C))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&&!V)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(V)W.push(QQ(J,j2(X,!!X.fileId)));if(X.fileId)W.push(N5(X));break}case"reasoning":{Y();let V=M5(X);if(V)Z.push(V);break}case"tool-call":{if(X.partial)break;Y(),Z.push({type:"function_call",call_id:X.toolCallId,name:String(X.name),arguments:JSON.stringify(X.input??{})});break}case"tool-result":{Y(),Z.push({type:"function_call_output",call_id:X.toolCallId,output:q5(X)});break}}Y()}return L5(Z)}var F5="No result was recorded for this tool call. Assume it did not complete.";function L5(Q){let $=new Set,Z=new Set,G=[];for(let W of Q){if(W.type==="function_call"){let Y=String(W.call_id);if($.has(Y))continue;$.add(Y)}else if(W.type==="function_call_output"){let Y=String(W.call_id);if(!$.has(Y)||Z.has(Y))continue;Z.add(Y)}G.push(W)}if(Z.size===$.size)return G;let J=[];for(let W of G){if(J.push(W),W.type!=="function_call")continue;let Y=String(W.call_id);if(Z.has(Y))continue;Z.add(Y),J.push({type:"function_call_output",call_id:Y,output:F5})}return J}function QQ(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function C5(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(C)?$:void 0}function j2(Q,$){let Z=[`id=${JSON.stringify(Q.attachmentId)}`];if(Q.name)Z.push(`name=${JSON.stringify(Q.name)}`);if(Q.mimeType)Z.push(`mimeType=${JSON.stringify(Q.mimeType)}`);let G=`attachment ${Z.join(" ")}`;return $?`[${G}]`:`[${G} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function N5(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":_5(Q.name))?"input_image":"input_file",file_id:Q.fileId}}function _5(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&P5.has($[1])}var P5=new Set(["jpeg","jpg","png","gif","webp"]);function M5(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function q5(Q){if(Q.status==="ok")return typeof Q.output==="string"?Q.output:JSON.stringify(Q.output??null);if(Q.status==="denied"){let $=Q.reason?` Reason given: ${Q.reason}`:"";if(Q.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${Q.error?.code??"unknown"}): ${Q.error?.message??"no message"}`}function F2(Q){return Array.isArray(Q.tools)}function S5(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let J=[];for(let W of Q)if(F2(W))for(let Y of W.tools)J.push($Q(Y,!1));else J.push($Q(W,!1));return J}let Z=[],G=!1;for(let J of Q)if(F2(J)){let W=J.tools.map((Y)=>{if(Y.deferred)G=!0;return $Q(Y,!0)});Z.push({type:"namespace",name:J.name,description:J.description,tools:W})}else{if(J.deferred)G=!0;Z.push($Q(J,!0))}if(G)Z.push({type:"tool_search"});return Z}function $Q(Q,$){let Z={type:"function",name:Q.name,description:Q.description,parameters:Q.parameters,strict:Q.strict};if($&&Q.deferred)Z.defer_loading=!0;return Z}var C2=120000,N2=2;function T(Q){return typeof process>"u"?void 0:process.env?.[Q]}class ZQ{static models(){return[]}normalizeError(Q){return k(Q)}}var _2=["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 TQ extends ZQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=RQ(Q),this.config=$}static model(Q,$){return new TQ(Q,$)}static models(){return _2}stream(Q){let $=kQ(Q,{model:this.model,capabilities:this.capabilities});return qQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return SQ(this.endpoint(),Q)}baseURL(){return(this.config.baseURL??T("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,"")}endpoint(){let Q=this.baseURL(),$=this.config;return{responsesUrl:`${Q}/responses`,filesUrl:`${Q}/files`,headers:async()=>{let Z=$.apiKey??T("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...$.headers}},timeoutMs:$.timeoutMs??C2,maxRetries:$.maxRetries??N2}}}var R5="preview";function L2(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function k5(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}class xQ extends ZQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=RQ(Q),this.config=$}static model(Q,$){return new xQ(Q,$)}static models(){return _2}stream(Q){let $=kQ(Q,{model:this.deployment(),capabilities:this.capabilities});return qQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return SQ(this.endpoint(),Q)}deployment(){return this.config.deployment??this.model}base(){let Q=this.config,$=Q.baseURL??Q.endpoint??T("AZURE_OPENAI_ENDPOINT");if($)return L2($);let Z=Q.resourceName??T("AZURE_OPENAI_RESOURCE_NAME")??T("AZURE_RESOURCE_NAME");return Z?L2(`https://${Z.trim()}.cognitiveservices.azure.com`):""}endpoint(){let Q=this.config,$=this.base(),Z=Q.apiVersion??T("AZURE_OPENAI_API_VERSION")??R5,G=k5(Z),J=`?api-version=${encodeURIComponent(Z)}`;return{responsesUrl:`${$}${G}/responses${J}`,filesUrl:`${$}${G}/files${J}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let W=Q.apiKey??T("AZURE_OPENAI_API_KEY");return{...W?{"api-key":W}:{},...Q.headers}},timeoutMs:Q.timeoutMs??C2,maxRetries:Q.maxRetries??N2}}}class w extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(Q,$,Z){super(`Frame ${$} of run ${Q} has been evicted; the oldest frame still buffered is ${Z}. Reload the thread instead of resuming.`);this.runId=Q;this.requested=$;this.oldest=Z}}class y extends Error{runId;code="live_run_not_found";constructor(Q){super(`No live run ${Q} in this process.`);this.runId=Q}}class GQ{ttlMs;maxFrames;runs=new Map;byThread=new Map;byClientRun=new Map;constructor(Q={}){this.ttlMs=Q.ttlMs??60000,this.maxFrames=Q.maxFrames??4096}register(Q,$={}){let Z={run:Q,threadId:$.threadId,clientRunId:$.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evictAt:null,wake:new Set,version:0};if(this.runs.set(Q.runId,Z),$.threadId)this.byThread.set($.threadId,Q.runId);if($.clientRunId)this.byClientRun.set($.clientRunId,Q.runId);return this.pump(Z,$)}findByClientRunId(Q){let $=this.byClientRun.get(Q);return $&&this.runs.has($)?$:null}async find(Q){let $=this.byThread.get(Q.threadId);if(!$)return null;let Z=this.runs.get($);if(!Z)return null;return{runId:$,seq:Z.lastSeq}}get(Q){return this.runs.get(Q)?.run??null}replay(Q,$){let Z=this.runs.get(Q);if(!Z)throw new y(Q);if($!==void 0&&$<Z.lostBefore)throw new w(Q,$,Z.lostBefore);let G=Z.frames[0]?.seq;return this.drain(Z,Q,$??G??Z.lastSeq+1)}clear(){for(let Q of this.runs.values()){if(Q.evictAt)clearTimeout(Q.evictAt);Q.ended=!0,this.notify(Q)}this.runs.clear(),this.byThread.clear(),this.byClientRun.clear()}get size(){return this.runs.size}async pump(Q,$){let Z=Promise.resolve();try{for await(let G of Q.run.frames()){if(Q.frames.push(G),Q.lastSeq=G.seq,Q.frames.length>this.maxFrames){let W=Q.frames.shift();if(W)Q.lostBefore=W.seq+1}this.notify(Q);let J=$.onEvent;if(J)Z=Z.then(()=>J(G.event)).catch((W)=>P2($,W))}}catch(G){P2($,G)}finally{Q.ended=!0,this.notify(Q),this.scheduleEviction(Q),await Z}}async*drain(Q,$,Z){let G=Z;while(!0){let J=Q.version;for(;;){if(G<Q.lostBefore)throw new w($,G,Q.lostBefore);let W=Q.frames,Y=W[0]?.seq;if(Y===void 0)break;let X=Math.max(0,G-Y);if(X>=W.length)break;let V=W[X];yield V,G=V.seq+1}if(Q.ended&&G>Q.lastSeq)return;await this.wait(Q,J)}}wait(Q,$){if(Q.version!==$)return Promise.resolve();return new Promise((Z)=>Q.wake.add(Z))}notify(Q){Q.version++;let $=Array.from(Q.wake);Q.wake.clear();for(let Z of $)Z()}scheduleEviction(Q){if(Q.evictAt)return;let $=setTimeout(()=>{let Z=Q.run.runId;if(this.runs.delete(Z),Q.threadId&&this.byThread.get(Q.threadId)===Z)this.byThread.delete(Q.threadId);if(Q.clientRunId&&this.byClientRun.get(Q.clientRunId)===Z)this.byClientRun.delete(Q.clientRunId);this.notify(Q)},this.ttlMs);$.unref?.(),Q.evictAt=$}}var EQ=new GQ;function P2(Q,$){try{Q.onInternalError?.($)}catch{}}class JQ{ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor(Q={}){this.ttlMs=Q.ttlMs??86400000,this.clientOwnedIds=Q.clientOwnedIds??!1}async createThread(Q){let $=crypto.randomUUID();return this.threads.set($,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:$}}async loadThread(Q){this.sweep();let $=this.threads.get(Q);if(!$)return this.clientOwnedIds?[]:null;return $.touchedAt=Date.now(),$.messages.slice()}async appendMessages(Q,$){this.sweep();let Z=this.threads.get(Q);if(!Z){if(!this.clientOwnedIds)throw Error(`Thread ${Q} does not exist here, or has expired.`);Z={messages:[],touchedAt:Date.now()},this.threads.set(Q,Z)}for(let G of $){let J=Z.messages.findIndex((W)=>W.id===G.id);if(J===-1)Z.messages.push(G);else Z.messages[J]=G}Z.touchedAt=Date.now()}delete(Q){this.threads.delete(Q)}get size(){return this.threads.size}sweep(Q=Date.now()){if(Q-this.lastSweep<60000)return;this.lastSweep=Q;for(let[$,Z]of this.threads)if(Q-Z.touchedAt>this.ttlMs)this.threads.delete($)}}var AQ=new JQ;var T5=k2,WQ=new Map,M2=new WeakMap,YQ=new Map;class x2 extends T5{static kind="agent-controller";store=AQ;liveRuns=EQ;attachments=d;attachmentStorage=T2;hookHoldMs=30000;instructions(Q,$){}requireThread=!1;authorizeRequest(Q,$){}async stream(Q=new g){let $=await IQ(Q);if($.error)return XQ($);let Z=$.body,G=typeof Z.threadId==="string"?Z.threadId:void 0,J=I5(Z);if(J.error)return XQ({body:{},error:J.error});let W=J.turn,Y=typeof Z.clientRunId==="string"?Z.clientRunId:void 0;if(this.requireThread&&!G)return N(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});let X=Y?{cancelled:!1}:null;if(X)YQ.set(Y,X);let V=async()=>{let B;if(G){let L=await this.store.loadThread(G);if(!L)return N(404,{code:"thread_not_found",message:`Thread ${G} does not exist here, or has expired.`});B=L}else B=Array.isArray(Z.messages)?Z.messages:[];let K=E5(Z),H=await this.instructions(Q,{body:K})||void 0,z=await this.attachmentsFor(Q,G);if(X?.cancelled)return S2();let O=this.agent.stream({messages:B,turn:W,req:Q,threadId:G,instructions:H,attachments:z,body:K}),D={req:Q,runId:O.runId,threadId:G},U=this.liveRuns.register(O,{threadId:G,clientRunId:Y,onEvent:(L)=>this.dispatchEvent(L,D),onInternalError:(L)=>this.reportHookFailure(L)}),{stored:j,hooks:_}=this.persistRun(O,D,U);return M2.set(O,j),Q.ctx?.()?.waitUntil(_),O.toResponse()};try{if(await this.authorizeRequest(Q,{route:"stream",threadId:G}),X?.cancelled)return S2();return G?await this.withThread(G,V):await V()}finally{if(X&&YQ.get(Y)===X)YQ.delete(Y)}}async withThread(Q,$){let Z=WQ.get(Q)??Promise.resolve(),G,J=new Promise((Y)=>{G=Y}),W=Z.then(()=>J);WQ.set(Q,W),await Z;try{let Y=await this.liveRuns.find({threadId:Q}),X=Y?this.liveRuns.get(Y.runId):null;if(X)X.stop({reason:"superseded by a later turn on this thread"}),await M2.get(X);return await $()}finally{if(G(),WQ.get(Q)===W)WQ.delete(Q)}}async attach(Q=new g){let $=await IQ(Q);if($.error)return XQ($);let Z=$.body,G=typeof Z.threadId==="string"?Z.threadId:v5(Q,"threadId");if(!G)return N(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(Q,{route:"attach",threadId:G});let J=await this.liveRuns.find({threadId:G});if(!J)return N(404,{code:"no_live_run",message:`No run in progress for thread ${G} in this process.`});let W=typeof Z.runId==="string"?Z.runId:void 0,Y=W&&W!==J.runId?void 0:b5(Q,Z);try{return sQ(this.liveRuns.replay(J.runId,Y))}catch(X){if(X instanceof w)return N(410,{code:X.code,message:X.message,oldestSeq:X.oldest});if(X instanceof y)return N(404,{code:X.code,message:X.message});throw X}}async stop(Q=new g){let $=await IQ(Q);if($.error)return XQ($);let Z=$.body;await this.authorizeRequest(Q,{route:"stop",threadId:typeof Z.threadId==="string"?Z.threadId:void 0});let G=typeof Z.runId==="string"?Z.runId:void 0;if(!G&&typeof Z.clientRunId==="string"){if(G=this.liveRuns.findByClientRunId(Z.clientRunId)??void 0,!G){let W=YQ.get(Z.clientRunId);if(W)return W.cancelled=!0,{stopped:!0}}}if(!G&&typeof Z.threadId==="string")G=(await this.liveRuns.find({threadId:Z.threadId}))?.runId;let J=G?this.liveRuns.get(G):null;if(!J)return{stopped:!1};return J.stop({reason:typeof Z.reason==="string"?Z.reason:void 0}),{stopped:!0}}attachmentScope(Q,$){let Z=Q.ctx()?.user,G=Z?.id??Z?.publicId;if(G!==void 0&&G!==null&&String(G)!=="")return{key:`user:${String(G)}`};if($)return{key:`thread:${$}`};return null}attachmentDestination(Q,$){return"both"}async attachmentsFor(Q,$){let Z=await this.attachmentScope(Q,$);if(!Z)return null;return new f(this.attachments,this.attachmentStorage,Z)}async upload(Q=new g){let $=await Q.rawRequest.formData(),Z=$.get("file");if(!(Z instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let G=Z instanceof File&&Z.name?Z.name:"upload",J=Z.type||"application/octet-stream",W=$.get("threadId");await this.authorizeRequest(Q,{route:"upload",threadId:typeof W==="string"&&W.length>0?W:void 0});let Y=typeof W==="string"&&W.length>0&&await this.store.loadThread(W)!==null?W:void 0,X=await this.attachmentDestination(Z,Q),V=f5(X,$.get("destination")),B=await this.attachmentScope(Q,Y),K=V!=="provider"&&!B;if(K){if(V==="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()`.');h5()}if(V==="provider"||!B){let j={fileId:await this.agent.provider.upload(Z),name:G,mimeType:J,size:Z.size,destination:"provider"};if(K)j.downgraded="no_scope";return j}let H=HQ(),z=await this.attachmentStorage.put({name:zQ(H,G),body:Z,contentType:J}),O=V==="both"?await this.agent.provider.upload(Z):void 0,D={id:H,scopeKey:B.key,fileId:O,objectName:z,name:G,mimeType:J,size:Z.size,createdAt:new Date().toISOString(),destination:V};return await this.attachments.put(B,D),{fileId:O,attachmentId:H,name:G,mimeType:J,size:Z.size,destination:V}}onMessage(Q,$){}onToolCall(Q,$){}onAwaitingInput(Q,$){}onError(Q,$){}onStreamComplete(Q,$){}reportHookFailure(Q){console.error("[gemi/ai] agent controller hook failed",Q)}async dispatchEvent(Q,$){switch(Q.type){case"tool-call":if(!Q.part.partial&&!Q.resent)await this.onToolCall({toolCallId:Q.part.toolCallId,name:String(Q.part.name),input:Q.part.input},$);return;case"awaiting-input":await this.onAwaitingInput(Q.pending,$);return;case"error":await this.onError(Q.error,$);return;default:return}}persistRun(Q,$,Z){let G=Promise.resolve(),J=(async()=>{let Y;try{Y=await Q.result()}catch(V){G=this.safely(()=>this.onError({code:"unknown",message:V instanceof Error?V.message:String(V),retryable:!1},$));return}let X=Y.messages;if($.threadId&&X.length>0)try{await this.store.appendMessages($.threadId,X)}catch(V){this.reportHookFailure(V)}G=this.notifyRun(Y,X,$)})(),W=J.then(()=>g5(Promise.all([G,Z]).then(()=>{}),this.hookHoldMs));return{stored:J,hooks:W}}async notifyRun(Q,$,Z){for(let G of $)await this.safely(()=>this.onMessage(G,Z));await this.safely(()=>this.onStreamComplete(Q,Z))}async safely(Q){try{await Q()}catch($){this.reportHookFailure($)}}}var q2=["turn","clientRunId","threadId","messages"],x5=["text","files","toolResults"];function E5(Q){let $=E2(Q)?q2:[...q2,...x5],Z={};for(let[G,J]of Object.entries(Q)){if($.includes(G))continue;Object.defineProperty(Z,G,{value:J,writable:!0,enumerable:!0,configurable:!0})}return Z}async function IQ(Q){let $=Q?.rawRequest;if(!$||$.method==="GET"||$.method==="HEAD"||!$.body)return{body:{}};if(!A5($.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let Z;try{Z=await $.text()}catch{return{body:{},error:"The request body could not be read."}}if(!Z.trim())return{body:{}};let G;try{G=JSON.parse(Z)}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 A5(Q){if(typeof Q!=="string")return!1;let[$]=Q.split(";",1);return $.trim().toLowerCase()==="application/json"}function XQ(Q){return N(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function E2(Q){return Boolean(Q.turn)&&typeof Q.turn==="object"}function I5(Q){let $=E2(Q)?Q.turn:Q,Z={};if(typeof $.text==="string")Z.text=$.text;if(Array.isArray($.files)){let G=w5($.files);if(typeof G==="string")return{error:G};Z.files=G}if(Array.isArray($.toolResults))Z.toolResults=$.toolResults;return Object.keys(Z).length>0?{turn:Z}:{}}function w5(Q){let $=[];for(let[Z,G]of Q.entries()){let J=`turn.files[${Z}]`;if(!G||typeof G!=="object"||Array.isArray(G))return`${J} must be an object.`;let W={};for(let K of["fileId","attachmentId","name","mimeType"]){let H=G[K];if(H===void 0||H===null||H==="")continue;if(typeof H!=="string")return`${J}.${K} must be a string.`;W[K]=H}let{fileId:Y,attachmentId:X,name:V,mimeType:B}=W;if(Y?.startsWith(C))return`${J}.fileId holds a gemi attachment id (${Y}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(X!==void 0&&!X.startsWith(C))return`${J}.attachmentId is not a gemi attachment id: it must start with "${C}".`;if(!Y&&!X)return`${J} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...Y?{fileId:Y}:{},...X?{attachmentId:X}:{},...V!==void 0?{name:V}:{},...B!==void 0?{mimeType:B}:{}})}return $}function b5(Q,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let G=Math.floor($.cursor);if(G>=0)return G+1;return}let Z=Q?.rawRequest?.headers?.get("Last-Event-ID");if(Z){let G=Number.parseInt(Z,10);if(Number.isFinite(G))return Math.max(0,G+1)}return}function v5(Q,$){let Z=Q?.search?.get($);return typeof Z==="string"?Z:void 0}function S2(){return N(409,{code:"stopped",message:"The turn was stopped before it started."})}function N(Q,$){return new Response(JSON.stringify({error:$}),{status:Q,headers:{"Content-Type":"application/json"}})}function f5(Q,$){if(typeof $!=="string"||$.length===0)return Q;if($!=="both"&&$!=="provider"&&$!=="storage")throw Error(`Unknown attachment destination "${$}". Expected "both", "provider" or "storage".`);if($===Q||Q==="both"&&$==="storage")return $;if(Q==="both"&&$==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${$}" destination, but the server's policy for it is "${Q}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var R2=!1;function h5(){if(R2)return;R2=!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 y5=2147483647;function g5(Q,$){let Z=Q.then(()=>{},()=>{});if(!($<=y5))return Z;let G,J=new Promise((W)=>{G=setTimeout(W,$)});return Promise.race([Z,J]).finally(()=>clearTimeout(G))}export{r2 as toAgentTools,t as supportsStrict,u5 as s,EQ as liveRuns,d as defaultAttachmentStore,AQ as defaultAgentStore,a as ToolNamespace,CQ as Skill,f as ScopedAttachments,h as SKILLS_NAMESPACE,q as PendingEscalation,TQ as OpenAIProvider,GQ as MemoryLiveRuns,l as MemoryAttachmentStore,JQ as MemoryAgentStore,y as LiveRunNotFoundError,A as InvalidAttachmentScopeError,w as FrameCursorEvictedError,xQ as AzureOpenAIProvider,v as AttachmentNotFoundError,R as AgentTool,ZQ as AgentProvider,x2 as AgentController,NQ as Agent};
|
|
19
19
|
|
|
20
|
-
//# debugId=
|
|
20
|
+
//# debugId=45537E56814160B264756E2164756E21
|