gemi 0.83.0 → 0.84.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 +38 -0
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/generate.d.ts +177 -0
- package/dist/ai/generate.d.ts.map +1 -0
- package/dist/ai/index.d.ts +2 -0
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +11 -11
- package/dist/ai/index.js.map +7 -5
- package/dist/ai/runtime.d.ts +115 -0
- package/dist/ai/runtime.d.ts.map +1 -0
- package/dist/ai/types.d.ts +4 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/app/App.d.ts +0 -5
- package/dist/app/App.d.ts.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/auth/AuthController.d.ts.map +1 -1
- package/dist/auth/accessToken.d.ts +45 -0
- package/dist/auth/accessToken.d.ts.map +1 -0
- package/dist/auth/config.d.ts +3 -3
- package/dist/auth/signInRedirect.d.ts +1 -1
- package/dist/bin/gemi.js +2 -33
- package/dist/bin/gemi.js.map +6 -6
- package/dist/bin/migrate/index.d.ts.map +1 -1
- package/dist/bin/migrate/tables.d.ts.map +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-7dk4b1fn.js → chunk-159hyeng.js} +2 -2
- package/dist/{chunk-7dk4b1fn.js.map → chunk-159hyeng.js.map} +1 -1
- package/dist/{chunk-fya5147b.js → chunk-1cebv3h8.js} +2 -2
- package/dist/{chunk-fya5147b.js.map → chunk-1cebv3h8.js.map} +1 -1
- package/dist/{chunk-gzx3rskd.js → chunk-1evk2pma.js} +4 -4
- package/dist/{chunk-gzx3rskd.js.map → chunk-1evk2pma.js.map} +1 -1
- package/dist/{chunk-hfxx52vr.js → chunk-1s914cdj.js} +3 -3
- package/dist/{chunk-hfxx52vr.js.map → chunk-1s914cdj.js.map} +1 -1
- package/dist/chunk-302mkqeq.js +7 -0
- package/dist/{chunk-817dxq6w.js.map → chunk-302mkqeq.js.map} +4 -4
- package/dist/{chunk-03xrgp1m.js → chunk-3z6wkvwj.js} +2 -2
- package/dist/{chunk-03xrgp1m.js.map → chunk-3z6wkvwj.js.map} +1 -1
- package/dist/{chunk-2gprnzc3.js → chunk-3zb2ycxj.js} +2 -2
- package/dist/{chunk-2gprnzc3.js.map → chunk-3zb2ycxj.js.map} +1 -1
- package/dist/{chunk-9146818v.js → chunk-495qwteq.js} +3 -3
- package/dist/{chunk-9146818v.js.map → chunk-495qwteq.js.map} +1 -1
- package/dist/chunk-49akdtfe.js +17 -0
- package/dist/{chunk-rs0xmd64.js.map → chunk-49akdtfe.js.map} +11 -12
- package/dist/{chunk-0e5z1x9w.js → chunk-53we503k.js} +2 -2
- package/dist/{chunk-0e5z1x9w.js.map → chunk-53we503k.js.map} +3 -3
- package/dist/{chunk-q7ngq6c5.js → chunk-57ryyhh3.js} +2 -2
- package/dist/{chunk-q7ngq6c5.js.map → chunk-57ryyhh3.js.map} +1 -1
- package/dist/{chunk-mc1xsz8j.js → chunk-73dk6k4p.js} +3 -3
- package/dist/{chunk-mc1xsz8j.js.map → chunk-73dk6k4p.js.map} +1 -1
- package/dist/{chunk-t2htq1v0.js → chunk-82nn71zs.js} +2 -2
- package/dist/{chunk-t2htq1v0.js.map → chunk-82nn71zs.js.map} +1 -1
- package/dist/{chunk-bwwjkdts.js → chunk-87x692j7.js} +2 -2
- package/dist/{chunk-bwwjkdts.js.map → chunk-87x692j7.js.map} +1 -1
- package/dist/{chunk-zv7417j0.js → chunk-8mmfpqgs.js} +2 -2
- package/dist/{chunk-v0j7spj5.js.map → chunk-8mmfpqgs.js.map} +1 -1
- package/dist/{chunk-d2tpgkg2.js → chunk-ah9ajys0.js} +1 -1
- package/dist/{chunk-zbhqa2z7.js → chunk-ash9e6fn.js} +2 -2
- package/dist/{chunk-zbhqa2z7.js.map → chunk-ash9e6fn.js.map} +1 -1
- package/dist/{chunk-mmq47yh3.js → chunk-aztkrzvf.js} +2 -2
- package/dist/{chunk-mmq47yh3.js.map → chunk-aztkrzvf.js.map} +1 -1
- package/dist/chunk-b9dejyaq.js +6 -0
- package/dist/{chunk-cmj9xnbp.js.map → chunk-b9dejyaq.js.map} +2 -2
- package/dist/{chunk-actjm3wr.js → chunk-bn9pzgww.js} +2 -2
- package/dist/{chunk-actjm3wr.js.map → chunk-bn9pzgww.js.map} +1 -1
- package/dist/{chunk-2frgq249.js → chunk-cfvq30n4.js} +2 -2
- package/dist/{chunk-2frgq249.js.map → chunk-cfvq30n4.js.map} +1 -1
- package/dist/{chunk-egw90hq5.js → chunk-cg4k40zy.js} +2 -2
- package/dist/{chunk-egw90hq5.js.map → chunk-cg4k40zy.js.map} +1 -1
- package/dist/{chunk-1dgab0qn.js → chunk-d0qwdeza.js} +2 -2
- package/dist/{chunk-1dgab0qn.js.map → chunk-d0qwdeza.js.map} +1 -1
- package/dist/{chunk-1k783c44.js → chunk-dvpxkzms.js} +2 -2
- package/dist/{chunk-1k783c44.js.map → chunk-dvpxkzms.js.map} +1 -1
- package/dist/chunk-e43drft2.js +5 -0
- package/dist/{chunk-z9x8fx21.js.map → chunk-e43drft2.js.map} +5 -7
- package/dist/{chunk-8ndqqsf0.js → chunk-ekppwzyg.js} +2 -2
- package/dist/{chunk-8ndqqsf0.js.map → chunk-ekppwzyg.js.map} +1 -1
- package/dist/{chunk-3h1pd6ec.js → chunk-en3mtnsg.js} +2 -2
- package/dist/{chunk-3h1pd6ec.js.map → chunk-en3mtnsg.js.map} +1 -1
- package/dist/{chunk-v8s1dmc2.js → chunk-enf9mdac.js} +2 -2
- package/dist/{chunk-v8s1dmc2.js.map → chunk-enf9mdac.js.map} +1 -1
- package/dist/{chunk-gppm9gkg.js → chunk-eysexnqb.js} +2 -2
- package/dist/{chunk-gppm9gkg.js.map → chunk-eysexnqb.js.map} +1 -1
- package/dist/{chunk-06p4zq4m.js → chunk-g6qe6wyb.js} +2 -2
- package/dist/{chunk-06p4zq4m.js.map → chunk-g6qe6wyb.js.map} +1 -1
- package/dist/{chunk-fpy7m803.js → chunk-gr61ymse.js} +2 -2
- package/dist/{chunk-fpy7m803.js.map → chunk-gr61ymse.js.map} +1 -1
- package/dist/{chunk-0kpvbnz0.js → chunk-j9wqzemf.js} +2 -2
- package/dist/{chunk-0kpvbnz0.js.map → chunk-j9wqzemf.js.map} +1 -1
- package/dist/{chunk-9z5g1rf6.js → chunk-jg9eqd3r.js} +1 -1
- package/dist/{chunk-6sd7an1r.js → chunk-k2qh3hvd.js} +2 -2
- package/dist/{chunk-6sd7an1r.js.map → chunk-k2qh3hvd.js.map} +1 -1
- package/dist/{chunk-d2esms7y.js → chunk-kb3xk9r8.js} +2 -2
- package/dist/{chunk-d2esms7y.js.map → chunk-kb3xk9r8.js.map} +1 -1
- package/dist/{chunk-2c89p8pf.js → chunk-kfavcgv2.js} +2 -2
- package/dist/{chunk-2c89p8pf.js.map → chunk-kfavcgv2.js.map} +1 -1
- package/dist/{chunk-5krm6p9w.js → chunk-m0zba09s.js} +3 -3
- package/dist/{chunk-5krm6p9w.js.map → chunk-m0zba09s.js.map} +1 -1
- package/dist/{chunk-wmbpdjvs.js → chunk-m4xw99vm.js} +2 -2
- package/dist/{chunk-wmbpdjvs.js.map → chunk-m4xw99vm.js.map} +1 -1
- package/dist/{chunk-6c0s1mb7.js → chunk-ng8pp9k2.js} +2 -2
- package/dist/{chunk-6c0s1mb7.js.map → chunk-ng8pp9k2.js.map} +1 -1
- package/dist/{chunk-zbpgt20r.js → chunk-nvj1z2rs.js} +2 -2
- package/dist/{chunk-zbpgt20r.js.map → chunk-nvj1z2rs.js.map} +1 -1
- package/dist/{chunk-h2pbrneh.js → chunk-pa0ya991.js} +2 -2
- package/dist/{chunk-h2pbrneh.js.map → chunk-pa0ya991.js.map} +1 -1
- package/dist/{chunk-a3mgkrb2.js → chunk-pgpqsgzx.js} +1 -1
- package/dist/{chunk-sexaj89x.js → chunk-pt59xjfc.js} +2 -2
- package/dist/{chunk-sexaj89x.js.map → chunk-pt59xjfc.js.map} +1 -1
- package/dist/{chunk-8vnb3hfz.js → chunk-r5e4vpa1.js} +2 -2
- package/dist/{chunk-8vnb3hfz.js.map → chunk-r5e4vpa1.js.map} +1 -1
- package/dist/{chunk-vxxk4syx.js → chunk-r8nhndzb.js} +2 -2
- package/dist/{chunk-vxxk4syx.js.map → chunk-r8nhndzb.js.map} +1 -1
- package/dist/{chunk-vax2fp2k.js → chunk-rmv1jp9p.js} +2 -2
- package/dist/{chunk-vax2fp2k.js.map → chunk-rmv1jp9p.js.map} +1 -1
- package/dist/{chunk-d07y2ddw.js → chunk-rqh2wdhb.js} +2 -2
- package/dist/{chunk-d07y2ddw.js.map → chunk-rqh2wdhb.js.map} +1 -1
- package/dist/{chunk-9hbwvcxn.js → chunk-rv7da58g.js} +2 -2
- package/dist/chunk-rv7da58g.js.map +10 -0
- package/dist/{chunk-2y9haf48.js → chunk-tdnfhe7x.js} +3 -3
- package/dist/{chunk-2y9haf48.js.map → chunk-tdnfhe7x.js.map} +1 -1
- package/dist/chunk-tmwsvf02.js +5 -0
- package/dist/{chunk-nc82trtm.js.map → chunk-tmwsvf02.js.map} +1 -1
- package/dist/{chunk-0zr926cf.js → chunk-v1nm4tcq.js} +2 -2
- package/dist/{chunk-0zr926cf.js.map → chunk-v1nm4tcq.js.map} +1 -1
- package/dist/{chunk-mwrh96hx.js → chunk-v27a4se1.js} +3 -3
- package/dist/chunk-v27a4se1.js.map +12 -0
- package/dist/chunk-vfrrzr10.js +4 -0
- package/dist/chunk-vfrrzr10.js.map +10 -0
- package/dist/{chunk-s7rhttvd.js → chunk-vmpzg4z5.js} +3 -3
- package/dist/{chunk-s7rhttvd.js.map → chunk-vmpzg4z5.js.map} +1 -1
- package/dist/{chunk-aecx542w.js → chunk-w099t7zj.js} +2 -2
- package/dist/{chunk-aecx542w.js.map → chunk-w099t7zj.js.map} +1 -1
- package/dist/chunk-wh728wd6.js +5 -0
- package/dist/chunk-wh728wd6.js.map +10 -0
- package/dist/{chunk-vqexqkfk.js → chunk-wkdzz0rx.js} +3 -3
- package/dist/chunk-wkdzz0rx.js.map +10 -0
- package/dist/{chunk-vngyybzh.js → chunk-wsx3j5ws.js} +2 -2
- package/dist/{chunk-vngyybzh.js.map → chunk-wsx3j5ws.js.map} +1 -1
- package/dist/{chunk-7y6gpg08.js → chunk-wwdaswxh.js} +3 -3
- package/dist/{chunk-7y6gpg08.js.map → chunk-wwdaswxh.js.map} +1 -1
- package/dist/{chunk-nq2hm5xm.js → chunk-xhha1gb3.js} +2 -2
- package/dist/{chunk-nq2hm5xm.js.map → chunk-xhha1gb3.js.map} +1 -1
- package/dist/{chunk-dk0kdrkm.js → chunk-yk8s5egf.js} +2 -2
- package/dist/{chunk-dk0kdrkm.js.map → chunk-yk8s5egf.js.map} +1 -1
- package/dist/{chunk-y7gfg6tj.js → chunk-ys4fejmx.js} +2 -2
- package/dist/{chunk-y7gfg6tj.js.map → chunk-ys4fejmx.js.map} +1 -1
- package/dist/{chunk-6eprvf4s.js → chunk-z409rk5j.js} +2 -2
- package/dist/{chunk-6eprvf4s.js.map → chunk-z409rk5j.js.map} +1 -1
- package/dist/{chunk-t6yzarvt.js → chunk-z7442w3q.js} +2 -2
- package/dist/{chunk-t6yzarvt.js.map → chunk-z7442w3q.js.map} +1 -1
- package/dist/{chunk-v0j7spj5.js → chunk-zfch4da5.js} +2 -2
- package/dist/{chunk-zv7417j0.js.map → chunk-zfch4da5.js.map} +1 -1
- package/dist/{chunk-f46ntdj3.js → chunk-zp971jp2.js} +3 -3
- package/dist/{chunk-f46ntdj3.js.map → chunk-zp971jp2.js.map} +1 -1
- package/dist/chunks/{ThemeProvider-BiNFL6l7.js → ThemeProvider-Dn3UREDn.js} +64 -90
- package/dist/chunks/ThemeProvider-Dn3UREDn.js.map +1 -0
- package/dist/client/ClientRouter.d.ts.map +1 -1
- package/dist/client/QueryResource.d.ts +14 -0
- package/dist/client/QueryResource.d.ts.map +1 -1
- package/dist/client/index.d.ts +0 -2
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +4 -29
- package/dist/client/index.js.map +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/Auth.d.ts +14 -0
- package/dist/facades/Auth.d.ts.map +1 -1
- package/dist/facades/index.d.ts +0 -1
- package/dist/facades/index.d.ts.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/Application.d.ts +7 -3
- package/dist/foundation/Application.d.ts.map +1 -1
- package/dist/foundation/app.d.ts +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/AuthenticationMiddlware.d.ts +4 -3
- package/dist/http/AuthenticationMiddlware.d.ts.map +1 -1
- package/dist/http/HttpRequest.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/internal/gemiExternals.d.ts +1 -1
- package/dist/internal/gemiExternals.d.ts.map +1 -1
- package/dist/kernel/Kernel.d.ts +0 -2
- package/dist/kernel/Kernel.d.ts.map +1 -1
- package/dist/kernel/context.d.ts +3 -4
- package/dist/kernel/context.d.ts.map +1 -1
- package/dist/kernel/index.js +3 -3
- package/dist/kernel/index.js.map +5 -5
- package/dist/kernel/providers.d.ts.map +1 -1
- package/dist/orm/context.d.ts +1 -2
- package/dist/orm/context.d.ts.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/cron/ScheduleServiceProvider.d.ts +7 -2
- package/dist/services/cron/ScheduleServiceProvider.d.ts.map +1 -1
- package/dist/services/index.d.ts +0 -3
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +3 -3
- package/dist/services/index.js.map +2 -2
- package/dist/services/logging/LogManager.d.ts.map +1 -1
- package/dist/services/queue/QueueServiceProvider.d.ts +8 -2
- package/dist/services/queue/QueueServiceProvider.d.ts.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/services/router/ApiRouteDispatcher.d.ts.map +1 -1
- package/dist/services/router/globalMiddleware.d.ts +5 -3
- package/dist/services/router/globalMiddleware.d.ts.map +1 -1
- package/dist/support/ServiceProvider.d.ts +14 -1
- package/dist/support/ServiceProvider.d.ts.map +1 -1
- package/dist/support/index.d.ts +1 -1
- package/dist/support/index.d.ts.map +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/testing/Page.d.ts.map +1 -1
- package/dist/testing/index.js +16 -24
- package/dist/testing/index.js.map +1 -1
- package/package.json +1 -2
- package/dist/broadcasting/BroadcastingChannel.d.ts +0 -5
- package/dist/broadcasting/BroadcastingChannel.d.ts.map +0 -1
- package/dist/broadcasting/index.d.ts +0 -2
- package/dist/broadcasting/index.d.ts.map +0 -1
- package/dist/broadcasting/index.js +0 -4
- package/dist/broadcasting/index.js.map +0 -10
- package/dist/chunk-817dxq6w.js +0 -7
- package/dist/chunk-9hbwvcxn.js.map +0 -10
- package/dist/chunk-cmj9xnbp.js +0 -6
- package/dist/chunk-f9mwxne0.js +0 -4
- package/dist/chunk-f9mwxne0.js.map +0 -10
- package/dist/chunk-fffph77x.js +0 -5
- package/dist/chunk-fffph77x.js.map +0 -10
- package/dist/chunk-mwrh96hx.js.map +0 -12
- package/dist/chunk-nc82trtm.js +0 -5
- package/dist/chunk-rs0xmd64.js +0 -17
- package/dist/chunk-vqexqkfk.js.map +0 -10
- package/dist/chunk-z9x8fx21.js +0 -5
- package/dist/chunks/ThemeProvider-BiNFL6l7.js.map +0 -1
- package/dist/client/WebsocketContext.d.ts +0 -10
- package/dist/client/WebsocketContext.d.ts.map +0 -1
- package/dist/client/useBroadcast.d.ts +0 -4
- package/dist/client/useBroadcast.d.ts.map +0 -1
- package/dist/client/useSubscription.d.ts +0 -5
- package/dist/client/useSubscription.d.ts.map +0 -1
- package/dist/facades/Broadcast.d.ts +0 -9
- package/dist/facades/Broadcast.d.ts.map +0 -1
- package/dist/http/BroadcastingRouter.d.ts +0 -8
- package/dist/http/BroadcastingRouter.d.ts.map +0 -1
- package/dist/services/pubsub/BroadcastManager.d.ts +0 -24
- package/dist/services/pubsub/BroadcastManager.d.ts.map +0 -1
- package/dist/services/pubsub/BroadcastServiceProvider.d.ts +0 -5
- package/dist/services/pubsub/BroadcastServiceProvider.d.ts.map +0 -1
- package/dist/services/pubsub/config.d.ts +0 -7
- package/dist/services/pubsub/config.d.ts.map +0 -1
- package/dist/services/pubsub/types.d.ts +0 -6
- package/dist/services/pubsub/types.d.ts.map +0 -1
- /package/dist/{chunk-d2tpgkg2.js.map → chunk-ah9ajys0.js.map} +0 -0
- /package/dist/{chunk-9z5g1rf6.js.map → chunk-jg9eqd3r.js.map} +0 -0
- /package/dist/{chunk-a3mgkrb2.js.map → chunk-pgpqsgzx.js.map} +0 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Gb as m$,Hb as JQ}from"../chunk-zbhqa2z7.js";import{$e as U9,Ke as z9,cf as l,qf as D9,sf as x6}from"../chunk-817dxq6w.js";import{vf as GQ}from"../chunk-vax2fp2k.js";import"../chunk-mwrh96hx.js";import"../chunk-fffph77x.js";import"../chunk-vxxk4syx.js";import"../chunk-8vnb3hfz.js";import"../chunk-v0j7spj5.js";import{createHmac as N9,randomBytes as G6,timingSafeEqual as J6}from"crypto";var NQ="agt1",W6=86400000;function d(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 R(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(R).join(",")}]`;let $=Q;return`{${Object.keys($).filter((G)=>$[G]!==void 0).sort().map((G)=>`${JSON.stringify(G)}:${R($[G])}`).join(",")}}`}function C9(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function i(Q,$){return N9("sha256",Q).update(C9($)).digest()}function Y6(Q,$,Z){let G=[NQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),R(Q.input)];if(Q.path&&Q.path.length>0)G.push(R(Q.path));return G}var X6=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),P9=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function V6(Q,$={}){let Z=d($.secret),J=($.now??Date.now())+($.ttlMs??W6),W=G6(12).toString("base64url"),Y=i(Z,Y6(Q,W,J)).toString("base64url");return[NQ,X6(Q.runId),W,J.toString(36),Y].join(".")}function o(Q){return CQ(Q,NQ)}function CQ(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:P9(Z[1]),nonce:Z[2],expiresAt:G}}catch{return null}}function K6(Q,$,Z={}){let G=d(Z.secret),J=o(Q);if(!J)return{ok:!1,reason:"malformed"};let W=Buffer.from(Q.split(".")[4],"base64url"),Y=i(G,Y6($,J.nonce,J.expiresAt));if(W.length!==Y.length||!J6(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 n="agn1";function H6(Q,$,Z){return[n,Q.runId,R(Q.path),Q.nestedRunId,$,String(Z),R([...Q.open].sort()),R(Q.input)]}function B6(Q,$={}){let Z=d($.secret),J=($.now??Date.now())+($.ttlMs??W6),W=G6(12).toString("base64url"),Y=i(Z,H6(Q,W,J)).toString("base64url");return[n,X6(Q.runId),W,J.toString(36),Y].join(".")}function z6(Q,$,Z={}){let G=d(Z.secret),J=CQ(Q,n);if(!J)return{ok:!1,reason:"malformed"};let W=Buffer.from(Q.split(".")[4],"base64url"),Y=i(G,H6({...$,runId:J.runId},J.nonce,J.expiresAt));if(W.length!==Y.length||!J6(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 w=new Map,U6=1024;function _9(Q){for(let[$,Z]of w)if(Z<=Q)w.delete($);U6=Math.max(1024,w.size*2)}function D6(Q,$={}){return O6(o(Q),$)}function F6(Q,$={}){return O6(CQ(Q,n),$)}function O6(Q,$){if(!Q)return!1;let Z=$.now??Date.now();if(w.size>=U6)_9(Z);let G=w.get(Q.nonce);if(G!==void 0&&G>Z)return!1;return w.set(Q.nonce,Q.expiresAt),!0}class h extends Error{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class f extends Error{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function PQ(Q){if(!Q||typeof Q.key!=="string"||Q.key.length===0)throw new f("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 _="gemi_att_";function _Q(){return`${_}${crypto.randomUUID()}`}class u{store;storage;scope;constructor(Q,$,Z){this.store=Q;this.storage=$;this.scope=Z;PQ(Z)}async get(Q){let $=await this.store.find(this.scope,Q);if(!$||$.scopeKey!==this.scope.key)throw new h(Q);return $}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,$){if(!$.objectName)throw new h(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=_Q(),G=$.mimeType??Q.type??"",J=$.name??(Q instanceof File?Q.name:Z),W=await this.storage.put({name:jQ(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 jQ(Q,$){let Z=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Q}${Z?`.${Z[1].toLowerCase()}`:""}`}class s{rows=new Map;async put(Q,$){PQ(Q),this.rows.set($.id,{...$,scopeKey:Q.key})}async find(Q,$){PQ(Q);let Z=this.rows.get($);if(!Z||Z.scopeKey!==Q.key)return null;return Z}get size(){return this.rows.size}}var t=new s;class r extends Error{status;body;requestId;constructor(Q,$,Z){super(`Provider request failed with status ${Q}: ${j9($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=Z}}class a extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function j9(Q){let $=L6(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function L6(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 g(Q){if(!Q||typeof Q!=="object")return{};let{status:$,requestId:Z}=Q;return{...typeof $==="number"&&$>=100&&$<=599?{status:$}:{},...typeof Z==="string"&&Z?{requestId:Z}:{}}}function P(Q){if(Q instanceof a)return{code:"provider_error",message:Q.message,retryable:!0};if(R9(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof r)return M9(Q.status,L6(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 M9(Q,$,Z){let G=$?.message??Z,J=($?.code??"").toLowerCase(),W=($?.type??"").toLowerCase(),Y=`${J} ${W} ${G}`.toLowerCase();if(Q===429){let K=J==="insufficient_quota"||Y.includes("quota");return{code:"rate_limited",message:G,retryable:!K}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:G,retryable:!0};if(q9(Y))return{code:"context_length_exceeded",message:G,retryable:!1};if(S9(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 q9(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function S9(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function R9(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}var MQ=new TextEncoder;function N6(Q){return`id: ${Q.seq}
|
|
2
|
+
import{Db as t$,Eb as m}from"../chunk-ash9e6fn.js";import{Fe as N9,Ve as C9,Ye as t,kf as P9,mf as GQ}from"../chunk-302mkqeq.js";import{pf as zQ}from"../chunk-rmv1jp9p.js";import"../chunk-v27a4se1.js";import"../chunk-wh728wd6.js";import"../chunk-r8nhndzb.js";import"../chunk-r5e4vpa1.js";import"../chunk-zfch4da5.js";class r extends Error{status;body;requestId;constructor(Q,$,Z){super(`Provider request failed with status ${Q}: ${q9($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=Z}}class a extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function q9(Q){let $=H6(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function H6(Q){if(!Q||typeof Q!=="object")return null;let $=Q,J=$.error&&typeof $.error==="object"?$.error:Q;if(typeof J.message!=="string"&&typeof J.code!=="string"&&typeof J.type!=="string")return null;let G=J.innererror?.code??J.code;return{message:J.message,type:J.type,code:G,param:J.param}}function M(Q){if(!Q||typeof Q!=="object")return{};let{status:$,requestId:Z}=Q;return{...typeof $==="number"&&$>=100&&$<=599?{status:$}:{},...typeof Z==="string"&&Z?{requestId:Z}:{}}}function _(Q){if(Q instanceof a)return{code:"provider_error",message:Q.message,retryable:!0};if(T9(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof r)return S9(Q.status,H6(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 S9(Q,$,Z){let J=$?.message??Z,G=($?.code??"").toLowerCase(),Y=($?.type??"").toLowerCase(),W=`${G} ${Y} ${J}`.toLowerCase();if(Q===429){let K=G==="insufficient_quota"||W.includes("quota");return{code:"rate_limited",message:J,retryable:!K}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:J,retryable:!0};if(R9(W))return{code:"context_length_exceeded",message:J,retryable:!1};if(k9(W))return{code:"content_filtered",message:J,retryable:!1};if($?.param?.startsWith("tools")||W.includes("invalid schema for function"))return{code:"invalid_tool_input",message:J,retryable:!1};return{code:"provider_error",message:J,retryable:!1}}function R9(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function k9(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function T9(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}class P extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function T(Q,$){if($.aborted)return Promise.reject(new P);return new Promise((Z,J)=>{let G=()=>J(new P);$.addEventListener("abort",G,{once:!0}),Q.then(Z,J).finally(()=>$.removeEventListener("abort",G))})}function A(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function q(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);if($.imageInputTokens!==void 0||Q.imageInputTokens!==void 0)Z.imageInputTokens=(Q.imageInputTokens??0)+($.imageInputTokens??0);if($.imageOutputTokens!==void 0||Q.imageOutputTokens!==void 0)Z.imageOutputTokens=(Q.imageOutputTokens??0)+($.imageOutputTokens??0);return Z}function e(Q){if(!Q.trim())return{};try{return JSON.parse(Q)}catch{}let $=[],Z=!1,J=!1;for(let W of Q){if(Z){if(J)J=!1;else if(W==="\\")J=!0;else if(W==='"')Z=!1;continue}if(W==='"')Z=!0;else if(W==="{")$.push("}");else if(W==="[")$.push("]");else if(W==="}"||W==="]")$.pop()}let G=Q;if(Z)G+='"';G=G.replace(/[,:]\s*$/,"");let Y=$.reverse().join("");try{return JSON.parse(G+Y)}catch{try{return JSON.parse(G.replace(/,?\s*"[^"]*"\s*$/,"")+Y)}catch{return{}}}}function QQ(Q){return{name:"output",schema:Q.toJSONSchema(),strict:m(Q)}}function $Q(Q,$){let Z=Q.safeParse(e($));if(Z.ok===!0)return{ok:!0,value:Z.value};return{ok:!1,error:{code:"invalid_output",message:`The model's structured answer did not match the output schema: ${Z.errors.join(", ")}`,retryable:!0}}}function ZQ(Q){if(Q.length>0)Q[0];return Q}function p(Q,$,Z){let J=Q.content[Q.content.length-1];if(J&&J.type===$){J.text=(J.text??"")+Z;return}Q.content.push($==="text"?{type:"text",text:Z}:{type:"reasoning",text:Z})}function JQ(Q,$,Z){let J=Q.content[Q.content.length-1];if(J&&J.type==="reasoning"&&J.id===$){J.text=(J.text??"")+Z;return}Q.content.push($?{type:"reasoning",id:$,text:Z}:{type:"reasoning",text:Z})}function A9(Q){return RQ(Q)}async function RQ(Q,$={}){let Z=`gen_${crypto.randomUUID()}`,J=await x9(Q);if($.settled?.(J),!J.ok){if(Q.logErrors!==!1&&J.error.code!=="aborted")E9(Z,J.error,$.origin);if(Q.throwOnError)throw new d({runId:Z,messages:J.messages,finishReason:J.finishReason,usage:J.usage,error:J.error})}return J}function E9(Q,$,Z){let J=`[gemi/ai] generate() failed (${$.code}${$.status!==void 0?` ${$.status}`:""}): ${$.message}`,G={...Z,generateId:Q,error:$},Y=!1;try{GQ.error(J,G),Y=!0}catch{}if(!Y||Bun.env.NODE_ENV==="development")console.error(J,G)}async function x9(Q){let $=Q.messages??[];if($.length===0&&!Q.prompt)throw Error("generate() was given neither a `prompt` nor `messages`, so there is nothing to send the model.");let Z=[...$];if(Q.prompt)Z.push({id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:Q.prompt}],createdAt:new Date().toISOString()});let J={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()},G=Q.signal??new AbortController().signal,Y=A(),W="stop",K,V={},X="";try{let D=Q.provider.stream({messages:[...Z],systemPrompt:Q.instructions?.trim()?Q.instructions:void 0,output:QQ(Q.output),reasoning:Q.reasoning,maxOutputTokens:Q.maxOutputTokens,temperature:Q.temperature,signal:Q.signal})[Symbol.asyncIterator]();try{for(;;){let F=await T(Promise.resolve(D.next()),G);if(F.done)break;let U=F.value;switch(U.type){case"output-delta":X+=U.delta;break;case"text-delta":p(J,"text",U.delta);break;case"reasoning-delta":JQ(J,U.id,U.delta);break;case"finish":if(Y=q(Y,U.usage),!K)W=U.reason;break;case"error":W="error",K=U.error,V=M(U);break}}}finally{if(G.aborted)Promise.resolve(D.return?.()).catch(()=>{})}}catch(z){if(z instanceof P||G.aborted)W="aborted",K=b9(G);else W="error",K=Q.provider.normalizeError(z),V=M(z)}let H=!1,B;if(!K)if(W==="length")K={code:"invalid_output",message:"The model ran out of output tokens before finishing its structured answer, so it was cut off. Raise maxOutputTokens, or ask for a shorter answer.",retryable:!0};else if(!X.trim())K={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let z=$Q(Q.output,X);if(z.ok===!0)H=!0,B=z.value;else K=z.error}if(H)J.content.push({type:"output",value:B});else if(X)p(J,"text",X);for(let z of J.content)if((z.type==="text"||z.type==="reasoning")&&typeof z.text==="string")z.text=ZQ(z.text);if(J.finishReason=W,Z.push(J),H)return{ok:!0,output:B,messages:Z,usage:Y,finishReason:W};return{ok:!1,error:{...K,...V},messages:Z,usage:Y,finishReason:W}}function b9(Q){return Q.reason?.name==="TimeoutError"?{code:"timeout",message:"The generation timed out.",retryable:!0}:{code:"aborted",message:"The generation was stopped.",retryable:!1}}import{createHmac as I9,randomBytes as B6,timingSafeEqual as z6}from"crypto";var kQ="agt1",U6=86400000;function YQ(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 E(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(E).join(",")}]`;let $=Q;return`{${Object.keys($).filter((J)=>$[J]!==void 0).sort().map((J)=>`${JSON.stringify(J)}:${E($[J])}`).join(",")}}`}function w9(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function WQ(Q,$){return I9("sha256",Q).update(w9($)).digest()}function D6(Q,$,Z){let J=[kQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),E(Q.input)];if(Q.path&&Q.path.length>0)J.push(E(Q.path));return J}var F6=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),f9=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function O6(Q,$={}){let Z=YQ($.secret),G=($.now??Date.now())+($.ttlMs??U6),Y=B6(12).toString("base64url"),W=WQ(Z,D6(Q,Y,G)).toString("base64url");return[kQ,F6(Q.runId),Y,G.toString(36),W].join(".")}function XQ(Q){return TQ(Q,kQ)}function TQ(Q,$){let Z=Q.split(".");if(Z.length!==5||Z[0]!==$)return null;let J=Number.parseInt(Z[3],36);if(!Number.isFinite(J))return null;try{return{runId:f9(Z[1]),nonce:Z[2],expiresAt:J}}catch{return null}}function L6(Q,$,Z={}){let J=YQ(Z.secret),G=XQ(Q);if(!G)return{ok:!1,reason:"malformed"};let Y=Buffer.from(Q.split(".")[4],"base64url"),W=WQ(J,D6($,G.nonce,G.expiresAt));if(Y.length!==W.length||!z6(Y,W))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>G.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:G.runId,nonce:G.nonce,expiresAt:G.expiresAt}}var VQ="agn1";function N6(Q,$,Z){return[VQ,Q.runId,E(Q.path),Q.nestedRunId,$,String(Z),E([...Q.open].sort()),E(Q.input)]}function C6(Q,$={}){let Z=YQ($.secret),G=($.now??Date.now())+($.ttlMs??U6),Y=B6(12).toString("base64url"),W=WQ(Z,N6(Q,Y,G)).toString("base64url");return[VQ,F6(Q.runId),Y,G.toString(36),W].join(".")}function P6(Q,$,Z={}){let J=YQ(Z.secret),G=TQ(Q,VQ);if(!G)return{ok:!1,reason:"malformed"};let Y=Buffer.from(Q.split(".")[4],"base64url"),W=WQ(J,N6({...$,runId:G.runId},G.nonce,G.expiresAt));if(Y.length!==W.length||!z6(Y,W))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>G.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:G.runId,nonce:G.nonce,expiresAt:G.expiresAt}}var h=new Map,_6=1024;function v9(Q){for(let[$,Z]of h)if(Z<=Q)h.delete($);_6=Math.max(1024,h.size*2)}function j6(Q,$={}){return q6(XQ(Q),$)}function M6(Q,$={}){return q6(TQ(Q,VQ),$)}function q6(Q,$){if(!Q)return!1;let Z=$.now??Date.now();if(h.size>=_6)v9(Z);let J=h.get(Q.nonce);if(J!==void 0&&J>Z)return!1;return h.set(Q.nonce,Q.expiresAt),!0}class l extends Error{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class u extends Error{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function AQ(Q){if(!Q||typeof Q.key!=="string"||Q.key.length===0)throw new u("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 j="gemi_att_";function EQ(){return`${j}${crypto.randomUUID()}`}class i{store;storage;scope;constructor(Q,$,Z){this.store=Q;this.storage=$;this.scope=Z;AQ(Z)}async get(Q){let $=await this.store.find(this.scope,Q);if(!$||$.scopeKey!==this.scope.key)throw new l(Q);return $}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,$){if(!$.objectName)throw new l(Q);return await this.storage.read({name:$.objectName})}async file(Q){let $=await this.get(Q),J=(await this.readRecord(Q,$)).body,G=J instanceof Blob?J:J?await new Response(J).blob():new Blob([]);return new File([G],$.name,{type:$.mimeType})}async put(Q,$={}){let Z=EQ(),J=$.mimeType??Q.type??"",G=$.name??(Q instanceof File?Q.name:Z),Y=await this.storage.put({name:xQ(Z,G),body:Q,contentType:J||void 0}),W={id:Z,scopeKey:this.scope.key,objectName:Y,name:G,mimeType:J||"application/octet-stream",size:Q.size,createdAt:new Date().toISOString(),destination:$.fileId?"both":"storage",...$.fileId?{fileId:$.fileId}:{}};return await this.store.put(this.scope,W),W}}function xQ(Q,$){let Z=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Q}${Z?`.${Z[1].toLowerCase()}`:""}`}class KQ{rows=new Map;async put(Q,$){AQ(Q),this.rows.set($.id,{...$,scopeKey:Q.key})}async find(Q,$){AQ(Q);let Z=this.rows.get($);if(!Z||Z.scopeKey!==Q.key)return null;return Z}get size(){return this.rows.size}}var HQ=new KQ;var bQ=new TextEncoder;function S6(Q){return`id: ${Q.seq}
|
|
3
3
|
data: ${JSON.stringify(Q.event)}
|
|
4
4
|
|
|
5
|
-
`}var
|
|
5
|
+
`}var y9=5000,h9=`: keepalive
|
|
6
6
|
|
|
7
|
-
`;function
|
|
8
|
-
${await
|
|
7
|
+
`;function IQ(Q,$=y9){let Z=null,J=!1,G=()=>{if(J)return;if(Z!==null)clearTimeout(Z);Z=setTimeout(()=>{if(Z=null,J)return;try{Q.enqueue(bQ.encode(h9))}catch{Y();return}G()},$)},Y=()=>{if(J=!0,Z!==null)clearTimeout(Z);Z=null};return G(),{touch:G,stop:Y}}function u9(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function R6(Q,$=200){let Z=Q[Symbol.asyncIterator](),J=-1,G,Y=new ReadableStream({start(W){G=IQ(W)},async pull(W){try{let K=await Z.next();if(K.done){G.stop(),W.close();return}J=K.value.seq,W.enqueue(bQ.encode(S6(K.value))),G.touch()}catch(K){let V={type:"error",error:g9(K)};G.stop(),W.enqueue(bQ.encode(S6({seq:J+1,event:V}))),W.close()}},cancel(W){G.stop(),Z.return?.(W)}});return new Response(Y,{status:$,headers:u9()})}function g9(Q){return{code:"unknown",message:Q instanceof Error?Q.message:String(Q),retryable:!1}}class x 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 b{name;description;inputSchema;outputSchema;requiresApproval;deferred;answeredBy;timeoutMs;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,this.timeoutMs=Q.timeoutMs}static create(Q){if(h6(Q.inputSchema,`The tool "${Q.name}"`,"inputSchema"),Q.timeoutMs!==void 0)fQ(Q.timeoutMs,`The tool "${Q.name}"`,"timeoutMs");return new b(Q)}static ask(Q){return b.create({name:Q.name,description:Q.description,inputSchema:yQ,outputSchema:Q.outputSchema,answeredBy:"client"})}}var yQ={toJSONSchema:()=>({type:"object",properties:{question:{type:"string",description:"What to ask the user"}},required:["question"],additionalProperties:!1}),parse(Q){let $=yQ.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 UQ{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 UQ(Q)}}class hQ{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 hQ(Q)}}var o="skills",c9="Instructions this agent can load on demand. Load the relevant one before acting in the area it covers.";function h6(Q,$,Z){let J=Q?.toJSONSchema?.();if(J?.type==="object")return;let G=!J?"no JSON Schema":J.anyOf?"a union (`anyOf`) \u2014 `s.union(...)`":J.type!==void 0?`a schema of type ${JSON.stringify(J.type)}`:"an unconstrained schema (`s.json()`)";throw Error(`${$} declares an \`${Z}\` whose root is ${G}, but the provider only accepts an object there (OpenAI rejects \`anyOf\` or a non-object at the root of tool parameters and structured output). Wrap it in an object, e.g. \`s.object({ value: s.union([...]) })\`, and read \`.value\` off the result.`)}function fQ(Q,$,Z){if(typeof Q==="number"&&Q>0)return;throw Error(`${$} sets \`${Z}\` to ${String(Q)}, but it has to be a positive number of milliseconds. Use \`null\` for no limit.`)}function k6(Q){if(Q===void 0)return;if(Q===null||!Number.isFinite(Q))return null;return Q}var m9=2147483647;function T6(Q,$){if(Q===null||Q>m9)return()=>{};let Z=setTimeout($,Q);return()=>clearTimeout(Z)}function wQ(Q){if(Q<1000)return`${Q}ms`;if(Q<60000)return`${+(Q/1000).toFixed(1)}s`;return`${+(Q/60000).toFixed(1)}m`}var u6={type:"object",properties:{},required:[],additionalProperties:!1},uQ=600000;class d extends Error{code;retryable;status;requestId;toolCallId;runId;result;constructor(Q){super(Q.error.message);this.name="AgentRunError",this.code=Q.error.code,this.retryable=Q.error.retryable,this.status=Q.error.status,this.requestId=Q.error.requestId,this.toolCallId=Q.error.toolCallId,this.runId=Q.runId,this.result=Q}}function p9(Q){return{code:Q.code,message:Q.message,...Q.toolCallId!==void 0?{toolCallId:Q.toolCallId}:{},retryable:Q.retryable}}var d9=8,l9=3;class gQ{name;tools;skills;provider;output;instructions;maxSteps;maxDepth;reasoning;maxRunDurationMs;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??d9,this.maxDepth=Q.maxDepth??l9,this.reasoning=Q.reasoning;let $=k6(Q.maxRunDurationMs);this.maxRunDurationMs=$===void 0?uQ:$;let{registry:Z,providerTools:J}=i9(this.tools,this.skills);this.config={name:this.name,instructions:this.instructions,provider:this.provider,registry:Z,providerTools:J,output:Q.output,maxSteps:this.maxSteps,maxDepth:this.maxDepth,reasoning:this.reasoning,maxOutputTokens:Q.maxOutputTokens,temperature:Q.temperature,logErrors:Q.logErrors??!0,maxRunDurationMs:$}}static create(Q){if(Q.output)h6(Q.output,`The agent "${Q.name}"`,"output");if(Q.maxRunDurationMs!=null)fQ(Q.maxRunDurationMs,`The agent "${Q.name}"`,"maxRunDurationMs");return new gQ(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,maxRunDurationMs:Q.maxRunDurationMs!==void 0?k6(Q.maxRunDurationMs):this.config.maxRunDurationMs};if(Q.maxRunDurationMs!=null)fQ(Q.maxRunDurationMs,`Agent.stream for "${this.name}"`,"maxRunDurationMs");return new c6($,Q)}}function A6(Q){return{name:Q.tool.name,description:Q.tool.description,parameters:Q.tool.inputSchema.toJSONSchema(),strict:m(Q.tool.inputSchema),deferred:Q.deferred}}function i9(Q,$){let Z=new Map,J=[],G=(Y)=>{if(Z.has(Y.tool.name))throw Error(`Two tools are named "${Y.tool.name}". Tool names are global within an agent \u2014 the client discriminates a tool part by name alone.`);Z.set(Y.tool.name,Y)};for(let Y of Q){if(Y instanceof UQ){if(Y.name===o)throw Error(`"${o}" 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 K=[];for(let V of Y.tools){let X={tool:V,namespace:Y.name,deferred:Y.deferred||V.deferred};G(X),K.push(A6(X))}J.push({name:Y.name,description:Y.description,tools:K});continue}let W={tool:Y,deferred:Y.deferred};G(W),J.push(A6(W))}if($.length>0){let Y=[];for(let W of $){let K=o9(W);G({tool:K,namespace:o,deferred:!1}),Y.push({name:W.name,description:W.description,parameters:u6,strict:!0,deferred:!1})}J.push({name:o,description:c9,tools:Y})}return{registry:Z,providerTools:J}}function o9(Q){return b.create({name:Q.name,description:Q.description,inputSchema:{toJSONSchema:()=>u6,parse:()=>({}),safeParse:()=>({ok:!0,value:{}})},execute:async()=>{let Z=[typeof Q.instructions==="function"?await Q.instructions():Q.instructions];for(let J of Q.files??[])Z.push(`--- ${J} ---
|
|
8
|
+
${await n9(J)}`);return Z.join(`
|
|
9
9
|
|
|
10
|
-
`)}})}async function
|
|
10
|
+
`)}})}async function n9(Q){try{return await Bun.file(Q).text()}catch($){return`(could not be read: ${$.message})`}}function s9(Q){return typeof Q==="object"&&Q!==null&&typeof Q.next==="function"&&Symbol.asyncIterator in Q}function E6(Q,$){let Z=[...Q],J=new Map(Z.map((G,Y)=>[G.id,Y]));for(let G of $){let Y=J.get(G.id);if(Y===void 0)J.set(G.id,Z.length),Z.push(G);else Z[Y]=G}return Z}function BQ(Q){let $=new Set;for(let J of Q)for(let G of J.content)if(G.type==="tool-result")$.add(G.toolCallId);let Z=new Set;for(let J of Q)for(let G of J.content)if(G.type==="tool-call"&&!$.has(G.toolCallId))Z.add(G.toolCallId);return Z}function x6(Q){for(let $=Q.length-1;$>=0;$--){let Z=Q[$].content;for(let J=Z.length-1;J>=0;J--){let G=Z[J];if(G.type==="output"&&G.partial!==!0)return G.value}}return}function b6(Q,$){return $===void 0?`"${Q}"`:`"${Q}" labelled "${$}"`}function g6(Q){return Q.content.map(($)=>$.type==="text"?$.text:`<${$.type}>`).join("")}function t9(Q){if(Q.prompt!==void 0)return`user:${Q.prompt}`;let $=Q.messages?.[0];return $?`${$.role}:${g6($)}`:null}function I6(Q){let $=new Set;for(let Z of Q)for(let J of Z.content){if(J.type!=="tool-call")continue;for(let G of J.attachments??[])if("shown"in G&&G.shown)$.add(G.shown.messageId)}return $}var w6=1;function r9(Q,$,Z){let J=Z.mimeType||$.type||"";if(J&&Q.attachment.mimeType!==J)return`was ${JSON.stringify(Q.attachment.mimeType)} on the turn that escalated and is ${JSON.stringify(J)} on the replay`;let G=Boolean(Z.showModel);if(G!==Boolean(Q.shown))return G?"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 a9(Q,$,Z){if(Q.agent!==$.name||Q.label!==Z.label)return`was ${b6(Q.agent,Q.label)} on the turn that escalated and is ${b6($.name,Z.label)} on the replay`;let J=t9(Z),G=Q.messages[0],Y=G?`${G.role}:${g6(G)}`:null;if(J!==null&&Y!==null&&J!==Y)return`was started with ${JSON.stringify(Y)} on the turn that escalated and with ${JSON.stringify(J)} on the replay`;return null}function f6(Q,$){let Z=Q??[];if(Z.length<$.length)return null;for(let J=0;J<$.length;J++)if(Z[J]!==$[J])return null;return Z.slice($.length)}class vQ{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 J=Z.length;J<Q;J++)Z[J]=this.fill();Z[Q]=$}}}}class c6{runId;config;params;context;controller=new AbortController;buffer=[];waiters=new Set;seq=0;ended=!1;history=[];produced=[];current=null;outputTruncated=!1;amended=new Map;unreported=new Set;usage=A();finishReason="stop";failure;output;stopReason;timedOutAfter;cancelDeadline=()=>{};settled;depth;maxDepth;chain;signingRunId;pathPrefix;onPending;nestedSettling=new Set;shownQueue=new Map;constructor(Q,$){this.config=Q,this.params=$,this.context=$.context??{},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});let J=Q.maxRunDurationMs!==void 0?Q.maxRunDurationMs:Z?null:uQ;this.cancelDeadline=T6(J,()=>this.expire(J)),this.settled=this.execute(),zQ.getStore()?.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,J=!1,G,Y=new ReadableStream({start:async(W)=>{G=IQ(W);try{for await(let K of $){if(J)break;W.enqueue(Z.encode(`id: ${K.seq}
|
|
11
11
|
data: ${JSON.stringify(K.event)}
|
|
12
12
|
|
|
13
|
-
`)),
|
|
13
|
+
`)),G.touch()}}catch{}G.stop();try{W.close()}catch{}},cancel:()=>{J=!0,G.stop()}});return new Response(Y,{headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}result(Q){if(!Q?.throwOnError)return this.settled;return this.settled.then(($)=>{if($.error)throw new d({...$,error:$.error});return $})}stop(Q){if(this.ended||this.controller.signal.aborted)return;this.stopReason=Q?.reason,this.controller.abort()}expire(Q){if(this.ended||this.controller.signal.aborted)return;this.timedOutAfter=Q,this.stopReason=`The run reached its time limit of ${wQ(Q)} and was stopped.`,this.controller.abort(new DOMException(this.stopReason,"TimeoutError"))}async execute(){this.emit({type:"run-start",runId:this.runId,threadId:this.params.threadId});try{let $=await this.ingestTurn();if($.length>0)this.finishReason="awaiting-input",this.emit({type:"awaiting-input",runId:this.runId,pending:$});else await this.loop()}catch($){if($ instanceof P||this.controller.signal.aborted)await this.finalizeAborted();else this.fail(this.config.provider.normalizeError($),M($)),await this.finalizeMessage("error"),this.finishReason="error"}this.cancelDeadline(),this.emit({type:"usage",usage:this.usage}),this.emit({type:"run-end",runId:this.runId,finishReason:this.finishReason}),this.ended=!0,this.wake();let Q=this.finishReason==="error"?this.failure:void 0;if(Q&&this.config.logErrors)this.logFailure(Q);return{runId:this.runId,messages:this.produced,finishReason:this.finishReason,usage:this.usage,output:this.output,...Q?{error:Q}:{}}}fail(Q,$={}){let Z={...Q,...$};this.failure=Z,this.emit({type:"error",error:p9(Z)})}logFailure(Q){let $=`[gemi/ai] agent "${this.config.name}" run failed (${Q.code}${Q.status!==void 0?` ${Q.status}`:""}): ${Q.message}`,Z={agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},...this.depth>0?{chain:this.chain}:{},error:Q},J=!1;try{GQ.error($,Z),J=!0}catch{}if(!J||Bun.env.NODE_ENV==="development")console.error($,Z)}async loop(){let Q=Math.max(1,this.config.maxSteps);for(let $=1;$<=Q;$++){let Z=this.startMessage(),J=await this.runStep(Z);if(J.error){this.fail(J.error,J.detail),await this.finalizeMessage("error"),this.finishReason="error";return}let G=Z.content.filter((W)=>W.type==="tool-call");if(G.length===0){this.finishReason=J.reason,await this.finalizeMessage(J.reason);return}let Y=await this.runTools(Z,G,$);if(Y.length>0){this.finishReason="awaiting-input",await this.finalizeMessage("awaiting-input"),this.emit({type:"awaiting-input",runId:this.runId,pending:Y});return}if($===Q){this.finishReason="max-steps",await this.finalizeMessage("max-steps");return}await this.finalizeMessage(J.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 J of $.content)if(J.type==="text"||J.type==="reasoning"){if(typeof J.text==="string")J.text=ZQ(J.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,J={reason:"stop"},G=new Map,Y="",K=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?QQ(this.config.output):void 0,reasoning:this.config.reasoning,maxOutputTokens:this.config.maxOutputTokens,temperature:this.config.temperature,signal:$})[Symbol.asyncIterator]();for(;;){let X=await T(Promise.resolve(K.next()),$);if(X.done)break;let H=X.value;switch(H.type){case"text-delta":{p(Q,"text",H.delta),this.emit({type:"text-delta",messageId:Q.id,delta:H.delta});break}case"reasoning-delta":{JQ(Q,H.id,H.delta),this.emit({type:"reasoning-delta",messageId:Q.id,delta:H.delta,id:H.id});break}case"output-delta":{Y+=H.delta,this.emit({type:"output-delta",messageId:Q.id,delta:H.delta,snapshot:e(Y)});break}case"tool-search":{this.emit({type:"tool-search",loaded:H.loaded});break}case"tool-call-delta":{let B=G.get(H.toolCallId)??{name:H.name,args:""};B.args+=H.argsDelta,B.name=H.name||B.name,G.set(H.toolCallId,B),this.emit({type:"tool-call",messageId:Q.id,part:{type:"tool-call",toolCallId:H.toolCallId,name:B.name,input:e(B.args),partial:!0}});break}case"tool-call":{G.delete(H.toolCallId);let B={type:"tool-call",toolCallId:H.toolCallId,name:H.name,input:y6(H.args)};Q.content.push(B),this.emit({type:"tool-call",messageId:Q.id,part:B});break}case"finish":{if(this.usage=q(this.usage,H.usage),!J.error)J={reason:H.reason};break}case"error":{J={reason:"error",error:H.error,detail:M(H)};break}}}for(let[X,H]of G){let B={type:"tool-call",toolCallId:X,name:H.name,input:y6(H.args)};Q.content.push(B),this.emit({type:"tool-call",messageId:Q.id,part:B})}let V=J.reason==="length";if(V)this.outputTruncated=!0;if(this.config.output&&Y&&!J.error&&!V){let X=$Q(this.config.output,Y);if(X.ok===!0)this.output=X.value,Q.content.push({type:"output",value:X.value});else this.emit({type:"error",error:X.error})}return J}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 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 K=Y.tool.inputSchema.safeParse(W.input);if(K.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)}": ${K.errors.join(", ")}`,toolCallId:W.toolCallId,retryable:!0}});continue}W.input=K.value;let X=E6(Y.tool);if(X){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(W));continue}G.push({toolCallId:W.toolCallId,name:W.name,input:K.value,kind:X,signature:V6(this.claimsFor(W.toolCallId,String(W.name),X,K.value)),...this.pathPrefix.length>0?{path:[...this.pathPrefix]}:{}});continue}J.push(this.executeTool(Y,Q.id,W,K.value,Z).then(async(V)=>{this.addResult(Q,V),await this.settleShown(W.toolCallId)}).catch((V)=>{if(V instanceof k){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(W));return}G.push(...V.pending);return}}))}return await e(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=Q.tool.timeoutMs;if(Y===void 0)return this.runToolBody(Q,$,Z,G,J,W,this.controller.signal,()=>!1);let K=new AbortController,X=this.controller.signal,V=()=>K.abort(X.reason);if(X.aborted)V();else X.addEventListener("abort",V,{once:!0});let H=!1,B=this.runToolBody(Q,$,Z,G,J,W,K.signal,()=>H),z=()=>{},D=new Promise((F)=>{z=_6(Y,()=>{let U=`"${String(Z.name)}" did not finish within ${SQ(Y)} (timeoutMs: ${Y}) and was cancelled.`;K.abort(new DOMException(U,"TimeoutError")),F({type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:{code:"timeout",message:U,toolCallId:Z.toolCallId,retryable:!0}})})});B.catch(()=>{});try{return await Promise.race([B,D])}finally{H=!0,z()}}async runToolBody(Q,$,Z,G,J,W,Y,K){let X=this.toolFiles(Z,Y),V={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,toolCallId:Z.toolCallId,signal:Y,step:J,depth:this.depth,resumed:W!==void 0,attachments:X.attachments,generateImage:X.generateImage,editImage:X.editImage,turn:this.toolTurn($),runAgent:this.nestedRunner($,Z,Y,W)};try{let H=Q.tool.execute(G,V),B;if(u9(H)){let z=await H.next();while(!z.done){if(K())throw H.return(void 0).catch(()=>{}),new j;this.emit({type:"tool-progress",toolCallId:Z.toolCallId,data:z.value}),z=await H.next()}B=z.value}else B=await H;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"ok",output:B}}catch(H){if(H instanceof j||this.controller.signal.aborted)throw new j;if(H instanceof k)throw H;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:{code:"tool_error",message:H instanceof Error?H.message:String(H),toolCallId:Z.toolCallId,retryable:!0}}}}nestedRunner(Q,$,Z,G){let J=new TQ(()=>$.nested,()=>$.nested=[]);return async(W,Y={})=>{let{at:K,recorded:X,write:V}=J.next();if(X){let H=p9(X,W,Y);if(H)throw Error(`Nested run ${K} of "${String($.name)}" ${H}. `+"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??QQ(),output:q6(X.messages),nested:X}}return this.runNested(Q,$,Z,W,Y,V,X,G?.answers??[])}}async runNested(Q,$,Z,G,J,W,Y,K){let X=[...this.chain,G.name];if(this.chain.includes(G.name))throw Error(`"${G.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 H=J.label,B=[...this.pathPrefix,$.toolCallId],z=this.onPending==="deny"?"deny":J.onPending??"escalate",D=Y!==void 0,F=D?ZQ(Y.messages):new Set,U=D?K.filter((N)=>{let I=T6(N.path,B);if(I===null)return!1;return F.has(I.length>0?I[0]:N.toolCallId)}):[],L=G.stream({messages:D?Y.messages:J.messages??[],turn:D?{toolResults:U}:J.prompt?{text:J.prompt}:void 0,context:this.context,attachments:this.params.attachments,body:this.params.body,signal:Z,threadId:this.params.threadId,instructions:J.instructions,maxOutputTokens:J.maxOutputTokens,temperature:J.temperature,runId:D?Y.runId:void 0,nesting:{depth:V,maxDepth:this.maxDepth,chain:X,signingRunId:this.signingRunId,signingPath:B,onPending:z}}),O=[],x=(async()=>{for await(let N of L){if(N.type==="awaiting-input")O=N.pending;this.emit({type:"nested-event",toolCallId:$.toolCallId,runId:L.runId,agent:G.name,label:H,event:N})}})(),q=(async()=>{let N=await L.result();await x;let I=D?M6(Y.messages,N.messages):M6(J.messages??[],N.messages),Z6={runId:L.runId,agent:G.name,label:H,messages:I,finishReason:N.finishReason,usage:D?$Q(Y.usage??QQ(),N.usage):N.usage,...N.finishReason==="awaiting-input"?{signature:B6({runId:this.signingRunId,path:B,nestedRunId:L.runId,open:[...ZQ(I)],input:$.input})}:{}};return W(Z6),this.usage=$Q(this.usage,N.usage),{result:N,record:Z6}})(),C=q.then(()=>{return},()=>{return});this.nestedSettling.add(C);let b,S;try{({result:b,record:S}=await q)}finally{this.nestedSettling.delete(C)}if(this.controller.signal.aborted)throw new j;if(b.finishReason==="awaiting-input"){if(O.length===0)throw Error(`"${G.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 k({pending:O,path:B,nested:S})}return{runId:S.runId,agent:G.name,messages:S.messages,finishReason:b.finishReason,usage:S.usage??QQ(),output:b.output??q6(S.messages),...b.error?{error:b.error}:{},nested:S}}addResult(Q,$){Q.content.push($),this.emit({type:"tool-result",messageId:Q.id,part:$})}toolFiles(Q,$){let Z=this.params.attachments??null,G=new TQ(()=>Q.attachments,()=>Q.attachments=[],()=>({failed:!0})),J=()=>{if(!Z)throw new f("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 Z},W=async(V,H,B)=>{let z=J(),D=H.mimeType||V.type||"",F=H.name??(V instanceof File?V.name:"attachment"),U;if(H.showModel){let O=this.config.provider;if(!O.capabilities.fileInput)throw Error(`"${String(Q.name)}" asked to show a file to ${O.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.`);U=await O.upload(new File([V],F,{type:D||void 0}))}return{attachment:await z.put(V,{name:F,mimeType:D,fileId:U}),...B?{generated:B}:{},...U?{shown:{fileId:U,messageId:`msg_${crypto.randomUUID()}`,createdAt:new Date().toISOString()}}:{}}},Y=(V,H,B)=>{let z=V.generated?"image":"put";if(z===H)return;throw Error(`Attachment ${B} of "${String(Q.name)}" was ${z==="image"?"a generated image":"a stored file"} on the first attempt and is ${H==="image"?"a generated image":"a stored file"} now. ctx.attachments.put, ctx.generateImage and ctx.editImage share one memo indexed by call order within a tool call, so the sequence has to be the same every time this tool runs. Branch on ctx.resumed if it cannot be.`)},K=async(V,H,B)=>{let{at:z,recorded:D,write:F}=G.next();if(D&&"attachment"in D){if(Y(D,"image",z),D.shown)this.queueShown(Q.toolCallId,D);return{attachment:D.attachment,size:D.generated.size,mimeType:D.attachment.mimeType,usage:D.generated.usage}}let U=await B();this.usage=$Q(this.usage,U.usage);let L=U.mimeType==="image/jpeg"?"jpg":"png",O=await W(U.image,{name:H.name??`${V.name}.${L}`,mimeType:U.mimeType,...H.showModel?{showModel:!0}:{}},{size:U.size,usage:U.usage});if(F(O),O.shown)this.queueShown(Q.toolCallId,O);return{attachment:O.attachment,size:U.size,mimeType:U.mimeType,usage:U.usage}},X=async(V)=>typeof V==="string"?await J().file(V):V;return{generateImage:(V,H)=>K(V,H,()=>V.generate({...H,signal:$})),editImage:(V,H)=>K(V,H,async()=>{let{images:B,mask:z,...D}=H;return await V.edit({...D,images:await Promise.all(B.map(X)),...z?{mask:await X(z)}:{},signal:$})}),attachments:{get:(V)=>J().get(V),read:(V)=>J().read(V),file:(V)=>J().file(V),put:async(V,H={})=>{let{at:B,recorded:z,write:D}=G.next();if(z&&"attachment"in z){Y(z,"put",B);let U=c9(z,V,H);if(U)throw Error(`Attachment ${B} 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(z.shown)this.queueShown(Q.toolCallId,z);return z.attachment}let F=await W(V,H);if(D(F),F.shown)this.queueShown(Q.toolCallId,F);return F.attachment}}}}toolTurn(Q){let $=this.history.findIndex((W)=>W.id===Q),Z=R6(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(_))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=R6($),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<=k6)return $;let J=new Set(G.slice(0,G.length-k6));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 K=`${(Y.path??[]).join("/")}#${Y.toolCallId}`;if(J.has(K))continue;J.add(K);let X=(z)=>this.emit({type:"error",error:{code:"invalid_tool_result",message:z,toolCallId:Y.toolCallId,retryable:!1}}),V=T6(Y.path,this.pathPrefix);if(V===null){X(`The answer for "${Y.toolCallId}" is addressed to a tool call this run is not inside.`);continue}if(V.length>0){let z=V[0],D=$.find((L)=>L.call.toolCallId===z);if(!D){X(`No pending tool call with id "${z}" to deliver a nested answer to.`);continue}let F=this.parkedBelow(D.call,V,Y.toolCallId);if(F.ok===!1){let L=`The answer for "${Y.toolCallId}" is addressed under "${z}", which`;X(F.reason==="unparked"?`${L} has no sub-agent run waiting on that question.`:F.reason==="expired"?`${L} parked a sub-agent run that has since expired. Ask again.`:`${L} carries a record of a parked sub-agent run the server did not sign.`);continue}let U=W.get(z);if(!U){if(!F6(F.signature)){X(`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 H=$.find((z)=>z.call.toolCallId===Y.toolCallId);if(!H){X(`No pending tool call with id "${Y.toolCallId}".`);continue}let B=await this.resolveAnswer(H,Y,Z);if(B===null)continue;if(G.add(Y.toolCallId),B!=="open")this.attachToHistory(H,B),await this.settleShown(Y.toolCallId)}for(let[Y,K]of W){let X=$.find((H)=>H.call.toolCallId===Y),V=await this.reenter(X,K,Z);if(V)this.attachToHistory(X,V),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((K)=>K.finishReason==="awaiting-input"&&ZQ(K.messages).has(G));if(!W)return{ok:!1,reason:"unparked"};if(typeof W.signature!=="string")return{ok:!1,reason:"unsigned"};let Y=z6(W.signature,{path:J,nestedRunId:W.runId,open:[...ZQ(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 e(this.executeTool(J,Q.message.id,Y,W.value,0,{answers:$}),this.controller.signal)}catch(K){if(K instanceof k)return Z.push(...K.pending),null;throw K}}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=(H)=>{return this.emit({type:"error",error:{code:"invalid_tool_result",message:H,toolCallId:G.toolCallId,retryable:!1}}),null};if(!W)return Y(`The tool "${J}" no longer exists, so its answer cannot be checked.`);let K=E6(W.tool);if(!K)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 X=o($.signature);if(!X)return Y(`The signature for "${J}" is malformed.`);let V=K6($.signature,{...this.claimsFor(G.toolCallId,J,K,G.input),runId:X.runId});if(V.ok===!1)return Y(V.reason==="expired"?`The approval for "${J}" has expired. Ask again.`:`The answer for "${J}" does not match the call the server made.`);if(!D6($.signature))return Y(`The answer for "${J}" has already been used. Ask again.`);if("approve"in $){if(K!=="approval")return Y(`"${J}" is answered by the client, not approved.`);if($.approve===!0){let H=this.amendCall(Q);try{return await e(this.executeTool(W,Q.message.id,H,H.input,0),this.controller.signal)}catch(B){if(B instanceof k)return Z.push(...B.pending),"open";throw B}}return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"denied",cause:"refused",reason:$.reason}}if("output"in $){if(K==="approval")return Y(`"${J}" is approved, not answered: the server produces its result.`);let H=W.tool.outputSchema,B=H?H.safeParse($.output):{ok:!0,value:$.output};if(B.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: ${B.errors.join(", ")}`,toolCallId:G.toolCallId,retryable:!0}};return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"ok",output:B.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})}}if(this.timedOutAfter!==void 0){this.fail({code:"timeout",message:`The run did not finish within its time limit of ${SQ(this.timedOutAfter)} (maxRunDurationMs: ${this.timedOutAfter}) and was stopped.`,retryable:!0}),this.finishReason="error",await this.finalizeMessage("error");return}this.finishReason="aborted",await this.finalizeMessage("aborted")}}function E6(Q){if(Q.answeredBy==="client")return Q.inputSchema===EQ?"question":"client";return Q.requiresApproval?"approval":null}function A6(Q){if(!Q||!Q.trim())return{};try{return JSON.parse(Q)}catch{return Q}}function m9(Q){if(Q.length>0)Q[0];return Q}function l9(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 d9(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 i9(Q,$){return Q.descriptors($).map((Z)=>T.create({name:Z.name,description:Z.description,inputSchema:Z.inputSchema,requiresApproval:Z.requiresApproval,execute:(G,J)=>{let W=GQ.getStore()?.req;if(!W)throw Error(`"${Z.name}" calls an api route as the user who started this run, and this run was not started inside a request. Run it from an AgentController, or give this agent tools that do not go through the MCP registry.`);return Q.execute({kind:"local",req:W},Z.name,G,J)}}))}function o9(Q){if(Q==="auto")return;let $=/^(\d+)x(\d+)$/.exec(Q);if(!$)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(Q)}.`);let Z=Number($[1]),G=Number($[2]);if(Z%16!==0||G%16!==0)throw Error(`Image size ${Q} is not supported: width and height must both be divisible by 16.`);if(Math.max(Z/G,G/Z)>3)throw Error(`Image size ${Q} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function v6(Q,$){if(Q.size!==void 0)try{o9(Q.size)}catch(Z){throw Error(`${$}: ${Z.message}`)}if(Q.background==="transparent"&&Q.format==="jpeg")throw Error(`${$}: a transparent background needs "png"; JPEG has no alpha channel.`);if(Q.compression!==void 0){let Z=Q.compression;if(!Number.isInteger(Z)||Z<0||Z>100)throw Error(`${$}: compression is an integer from 0 to 100; got ${Z}.`)}}function y6(Q,$){if(Q instanceof File)return Q;let Z=Q.type||"image/png",G=Z==="image/jpeg"?"jpg":Z.split("/")[1]??"png";return new File([Q],`${$}.${G}`,{type:Z})}class wQ{name;provider;settings;constructor(Q){let{name:$,provider:Z,...G}=Q;v6(G,`ImageModel "${$}"`),this.name=$,this.provider=Z,this.settings=G}static create(Q){return new wQ(Q)}async generate(Q){let $=this.merge(Q);return h6(await this.provider.generate({prompt:Q.prompt,...$,signal:Q.signal}))}async edit(Q){let $=this.merge(Q);return h6(await this.provider.edit({prompt:Q.prompt,...$,images:Q.images.map((Z,G)=>y6(Z,`image-${G}`)),...Q.mask?{mask:y6(Q.mask,"mask")}:{},signal:Q.signal}))}merge(Q){let $={...this.settings,...Q.size!==void 0?{size:Q.size}:{},...Q.quality!==void 0?{quality:Q.quality}:{},...Q.background!==void 0?{background:Q.background}:{},...Q.format!==void 0?{format:Q.format}:{},...Q.compression!==void 0?{compression:Q.compression}:{}};return v6($,`ImageModel "${this.name}"`),$}}function h6(Q){return{image:new Blob([Q.bytes],{type:Q.mimeType}),mimeType:Q.mimeType,size:Q.size,usage:Q.usage}}function E(Q){return typeof process>"u"?void 0:process.env?.[Q]}var n9="preview";function u6(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function s9(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}function YQ(Q,$={}){return{base:(Q.baseURL??E("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let G=Q.apiKey??E("OPENAI_API_KEY");return{...G?{authorization:`Bearer ${G}`}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,maxRetries:Q.maxRetries??2}}function t9(Q){let $=Q.baseURL??Q.endpoint??E("AZURE_OPENAI_ENDPOINT");if($)return u6($);let Z=Q.resourceName??E("AZURE_OPENAI_RESOURCE_NAME")??E("AZURE_RESOURCE_NAME");return Z?u6(`https://${Z.trim()}.cognitiveservices.azure.com`):""}function XQ(Q,$={}){let Z=Q.apiVersion??E("AZURE_OPENAI_API_VERSION")??n9;return{base:`${t9(Q)}${s9(Z)}`,query:`?api-version=${encodeURIComponent(Z)}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let G=Q.apiKey??E("AZURE_OPENAI_API_KEY");return{...G?{"api-key":G}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,maxRetries:Q.maxRetries??2}}var r9=500,c6=20000;function a9(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 g6(Q,$){let Z=Math.min(c6,r9*2**Q);return Math.round(Z*(0.5+$()*0.5))}function e9(Q){return Q===429||Q===408||Q===409||Q>=500}function Q$(Q,$){return e9(Q)&&P($).retryable}function p6(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function $$(Q,$){return new Promise((Z,G)=>{let J=setTimeout(Z,Q);$?.addEventListener("abort",()=>{clearTimeout(J),G(p6($))},{once:!0})})}async function p(Q,$,Z){let G=Z.fetchImpl??((H,B)=>fetch(H,B)),J=Z.sleep??$$,W=Z.random??Math.random,Y=Z.now??Date.now,K=Math.max(0,Z.maxRetries),X=async(H)=>{let B=Z.signal;if(!B)return await J(H);B.throwIfAborted();let z;try{await Promise.race([J(H,B),new Promise((D,F)=>{z=()=>F(p6(B)),B.addEventListener("abort",z,{once:!0})})])}finally{if(z)B.removeEventListener("abort",z)}},V;for(let H=0;H<=K;H++){Z.signal?.throwIfAborted();let B=new AbortController,z=()=>B.abort(Z.signal?.reason);Z.signal?.addEventListener("abort",z,{once:!0});let D=!1,F=Z.timeoutMs>0?setTimeout(()=>{D=!0,B.abort()},Z.timeoutMs):void 0,U;try{U=await G(Q,{...$,signal:B.signal})}catch(q){if(F!==void 0)clearTimeout(F);if(Z.signal?.removeEventListener("abort",z),Z.signal?.aborted)throw q;if(V=D?new a(Z.timeoutMs):q,D&&Z.retryTimeouts===!1)throw V;if(H===K)throw V;await X(g6(H,W));continue}if(F!==void 0)clearTimeout(F);if(U.ok)return U;Z.signal?.removeEventListener("abort",z);let L=await Z$(U),O=new r(U.status,L,U.headers.get("x-request-id")??void 0);if(H===K||!Q$(U.status,O))throw O;let x=a9(U.headers.get("retry-after"),Y());await X(x===void 0?g6(H,W):Math.min(x,c6)),V=O}throw V??Error("Provider request failed with no response.")}async function Z$(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}var fQ=300000;function vQ(Q){return{generationsUrl:`${Q.base}/images/generations${Q.query}`,editsUrl:`${Q.base}/images/edits${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,maxRetries:Q.maxRetries}}class VQ extends Error{code;retryable;constructor(Q,$={}){super(Q.message,$);this.name="ImageRequestError",this.code=Q.code,this.retryable=Q.retryable}}var G$={png:"image/png",jpeg:"image/jpeg"};function J$(Q){let $=Number(Q?.input_tokens??0),Z=Number(Q?.output_tokens??0),G={inputTokens:$,outputTokens:Z,totalTokens:Number(Q?.total_tokens??$+Z)},J=Q?.input_tokens_details?.image_tokens;if(typeof J==="number")G.imageInputTokens=J;let W=Q?.output_tokens_details?.image_tokens;if(typeof W==="number")G.imageOutputTokens=W;return G}function W$(Q){let $=atob(Q),Z=new Uint8Array($.length);for(let G=0;G<$.length;G++)Z[G]=$.charCodeAt(G);return Z}function Y$(Q){let Z=Q?.data?.[0]?.b64_json;if(typeof Z!=="string"||Z.length===0)throw new VQ({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let G=typeof Q.output_format==="string"?Q.output_format:"png";return{bytes:W$(Z),mimeType:G$[G]??`image/${G}`,size:typeof Q.size==="string"?Q.size:"",...typeof Q.background==="string"?{background:Q.background}:{},usage:J$(Q.usage)}}async function m6(Q,$,Z,G){let J;try{J=await p(Q,$,{maxRetries:Z.maxRetries,timeoutMs:Z.timeoutMs,retryTimeouts:!1,signal:G.signal,fetchImpl:Z.fetchImpl})}catch(W){if(G.signal?.aborted)throw W;throw new VQ(P(W),{cause:W})}return Y$(await J.json())}async function l6(Q,$,Z={}){return await m6(Q.generationsUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify($)},Q,Z)}async function d6(Q,$,Z={}){return await m6(Q.editsUrl,{method:"POST",headers:await Q.headers(),body:$},Q,Z)}class KQ{static models(){return[]}modelName(){return this.model}async generate(Q){return await l6(this.endpoint(),this.body(Q),{signal:Q.signal})}async edit(Q){let $=new FormData;for(let[Z,G]of Object.entries(this.body(Q)))if(G!==void 0)$.set(Z,String(G));for(let Z of Q.images)$.append("image[]",Z,Z.name);if(Q.mask)$.set("mask",Q.mask,Q.mask.name);return await d6(this.endpoint(),$,{signal:Q.signal})}body(Q){return{model:this.modelName(),prompt:Q.prompt,...Q.size?{size:Q.size}:{},...Q.quality?{quality:Q.quality}:{},...Q.background?{background:Q.background}:{},...Q.format?{output_format:Q.format}:{},...Q.compression!==void 0?{output_compression:Q.compression}:{}}}normalizeError(Q){return P(Q)}}var i6=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class yQ extends KQ{model;config;constructor(Q,$={}){super();this.model=Q,this.config=$}static model(Q,$){return new yQ(Q,$)}static models(){return i6}endpoint(){return vQ(YQ(this.config,{timeoutMs:fQ}))}}class hQ extends KQ{model;config;constructor(Q,$={}){super();this.model=Q,this.config=$}static model(Q,$){return new hQ(Q,$)}static models(){return i6}modelName(){return this.config.deployment??this.model}endpoint(){return vQ(XQ(this.config,{timeoutMs:fQ}))}}async function*X$(Q){let $="",Z="",G=[],J,W=()=>{if(G.length===0&&!Z)return null;let X={event:Z,data:G.join(`
|
|
16
|
-
`),id:
|
|
17
|
-
`);while(
|
|
18
|
-
`)}}if($.length>0){let X=Y($);if(X)yield X}let K=W();if(K)yield K}async function*o6(Q,$={}){let Z=new Map,G=new Set,J=!1;for await(let W of X$(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 X=String(Y.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(Y.delta??"");if(!X)break;yield{type:"reasoning-delta",delta:X,id:Y.item_id};break}case"response.output_item.added":{let X=Y.item;if(!X)break;if(X.type==="function_call"){let V=String(X.id??Y.item_id??X.call_id??"");Z.set(V,{callId:String(X.call_id??V),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(Y.item_id??""));if(!X)break;let V=String(Y.delta??"");if(!V)break;yield{type:"tool-call-delta",toolCallId:X.callId,name:X.name,argsDelta:V,...X.namespace?{namespace:X.namespace}:{}};break}case"response.function_call_arguments.done":{let X=String(Y.item_id??""),V=Z.get(X);if(!V)break;V.done=!0,yield{type:"tool-call",toolCallId:V.callId,name:V.name,args:String(Y.arguments??""),...V.namespace?{namespace:V.namespace}:{}};break}case"response.output_item.done":{let X=Y.item;if(!X)break;if(X.type==="function_call"){let V=String(X.id??Y.item_id??X.call_id??""),H=Z.get(V);if(H?.done)break;let B=(typeof X.namespace==="string"?X.namespace:"")||H?.namespace;if(yield{type:"tool-call",toolCallId:String(X.call_id??V),name:String(X.name??H?.name??""),args:String(X.arguments??""),...B?{namespace:B}:{}},H)H.done=!0;break}if(X.type==="tool_search_call"||X.type==="tool_search_output"){let V=V$(X);if(V.loaded.length===0&&V.namespaces.length===0)break;let H=String(X.tool_search_call_id??X.id??"");if(G.has(H))break;G.add(H),yield{type:"tool-search",...V}}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:uQ(Y.response?.usage)};break}case"response.incomplete":{J=!0;let X=uQ(Y.response?.usage),V=Y.response?.incomplete_details?.reason;if(V==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:K$(Y.response?.content_filters),retryable:!1}},yield{type:"finish",reason:"error",usage:X};break}yield{type:"finish",reason:V==="max_output_tokens"?"length":"stop",usage:X};break}case"response.failed":case"error":{J=!0;let X=Y.response?.error??Y.error??Y;yield{type:"error",error:H$(X)},yield{type:"finish",reason:"error",usage:uQ(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:v()}}function V$(Q){let $=[],Z=[];return n6(Q.results??Q.tools??Q.loaded??Q.output,$,Z,0),{loaded:gQ($),namespaces:gQ(Z)}}function n6(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:"",K=W.tools??W.functions;if(Array.isArray(K)){if(Y)Z.push(Y);n6(K,$,Z,G+1);continue}if(Y)$.push(Y)}}function gQ(Q){return Q.filter(($,Z)=>Q.indexOf($)===Z)}function K$(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,K]of Object.entries(W))if(K&&typeof K==="object"&&K.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: ${gQ(Z).join(", ")}.`}function H$(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 v(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function uQ(Q){if(!Q)return v();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*s6(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()}}function cQ(Q){return{responsesUrl:`${Q.base}/responses${Q.query}`,filesUrl:`${Q.base}/files${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,maxRetries:Q.maxRetries}}async function*pQ(Q,$,Z){let G;try{G=await p(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=P(J);if(W.code!=="aborted")yield{type:"error",error:W,...g(J)};yield{type:"finish",reason:W.code==="aborted"?"aborted":"error",usage:v()};return}try{yield*o6(s6(G.body),{structuredOutput:Z.structuredOutput})}catch(J){let W=P(J);if(W.code==="aborted"){yield{type:"finish",reason:"aborted",usage:v()};return}yield{type:"error",error:W},yield{type:"finish",reason:"error",usage:v()}}}async function mQ(Q,$){let Z=new FormData;Z.set("purpose","user_data"),Z.set("file",$);let J=await(await p(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 lQ(Q){let $=B$(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Z=z$($);if(Z?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Z.major>1,toolSearch:t6(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:t6(Z)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function t6(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function B$(Q){return Q.trim().toLowerCase()}function z$(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 dQ(Q,$){let{capabilities:Z}=$,G={model:$.model,input:U$(Q.messages,Z),stream:!0};if(Q.systemPrompt)G.instructions=Q.systemPrompt;let J=j$(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=Q.reasoning==="none"?{effort:"none"}:{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 U$(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 K of G.content??[])switch(K.type){case"text":{if(!K.text)break;W.push(HQ(J,K.text));break}case"output":{if(K.partial)break;W.push(HQ(J,JSON.stringify(K.value)));break}case"file":{if(J==="assistant")break;let X=O$(K);if(!$.fileInput){if(X)W.push(HQ(J,r6(K,!1)));break}if(K.fileId?.startsWith(_))throw Error(`FilePart.fileId holds a gemi attachment id (${K.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(!K.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)W.push(HQ(J,r6(K,!!K.fileId)));if(K.fileId)W.push(L$(K));break}case"reasoning":{Y();let X=P$(K);if(X)Z.push(X);break}case"tool-call":{if(K.partial)break;Y(),Z.push({type:"function_call",call_id:K.toolCallId,name:String(K.name),arguments:JSON.stringify(K.input??{})});break}case"tool-result":{Y(),Z.push({type:"function_call_output",call_id:K.toolCallId,output:_$(K)});break}}Y()}return F$(Z)}var D$="No result was recorded for this tool call. Assume it did not complete.";function F$(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:D$})}return J}function HQ(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function O$(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(_)?$:void 0}function r6(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 L$(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":N$(Q.name))?"input_image":"input_file",file_id:Q.fileId}}function N$(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&C$.has($[1])}var C$=new Set(["jpeg","jpg","png","gif","webp"]);function P$(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function _$(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.${$}`;if(Q.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${Q.error?.code??"unknown"}): ${Q.error?.message??"no message"}`}function a6(Q){return Array.isArray(Q.tools)}function j$(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let J=[];for(let W of Q)if(a6(W))for(let Y of W.tools)J.push(BQ(Y,!1));else J.push(BQ(W,!1));return J}let Z=[],G=!1;for(let J of Q)if(a6(J)){let W=J.tools.map((Y)=>{if(Y.deferred)G=!0;return BQ(Y,!0)});Z.push({type:"namespace",name:J.name,description:J.description,tools:W})}else{if(J.deferred)G=!0;Z.push(BQ(J,!0))}if(G)Z.push({type:"tool_search"});return Z}function BQ(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}class zQ{static models(){return[]}normalizeError(Q){return P(Q)}}var e6=["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 iQ extends zQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=lQ(Q),this.config=$}static model(Q,$){return new iQ(Q,$)}static models(){return e6}stream(Q){let $=dQ(Q,{model:this.model,capabilities:this.capabilities});return pQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return mQ(this.endpoint(),Q)}endpoint(){return cQ(YQ(this.config))}}class oQ extends zQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=lQ(Q),this.config=$}static model(Q,$){return new oQ(Q,$)}static models(){return e6}stream(Q){let $=dQ(Q,{model:this.deployment(),capabilities:this.capabilities});return pQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return mQ(this.endpoint(),Q)}deployment(){return this.config.deployment??this.model}endpoint(){return cQ(XQ(this.config))}}class y 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 m extends Error{runId;code="live_run_not_found";constructor(Q){super(`No live run ${Q} in this process.`);this.runId=Q}}class UQ{ttlMs;maxFrames;maxAgeMs;runs=new Map;byThread=new Map;byClientRun=new Map;constructor(Q={}){this.ttlMs=Q.ttlMs??60000,this.maxFrames=Q.maxFrames??4096,this.maxAgeMs=Q.maxAgeMs===void 0?3600000:Q.maxAgeMs}register(Q,$={}){let Z={run:Q,threadId:$.threadId,clientRunId:$.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evicted:!1,evictAt:null,expireAt: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.scheduleExpiry(Z,$.maxRunDurationMs),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 m(Q);if($!==void 0&&$<Z.lostBefore)throw new y(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);if(Q.expireAt)clearTimeout(Q.expireAt);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.evicted){let W=$.onEvent;if(W)Z=Z.then(()=>W(G.event)).catch((Y)=>nQ($,Y));continue}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)=>nQ($,W))}}catch(G){nQ($,G)}finally{if(Q.ended=!0,Q.expireAt)clearTimeout(Q.expireAt),Q.expireAt=null;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 y($,G,Q.lostBefore);let W=Q.frames,Y=W[0]?.seq;if(Y===void 0)break;let K=Math.max(0,G-Y);if(K>=W.length)break;let X=W[K];yield X,G=X.seq+1}if(Q.ended&&G>Q.lastSeq||Q.evicted)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(!Q.ended)Q.evicted=!0,Q.frames=[];if(this.runs.get(Z)===Q)this.runs.delete(Z);if(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=$}scheduleExpiry(Q,$){if(this.maxAgeMs===null||$===null)return;let Z=$===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,$+this.ttlMs);if(!Number.isFinite(Z)||Z>2147483647)return;let G=setTimeout(()=>{if(Q.expireAt=null,Q.ended)return;try{Q.run.stop({reason:`The run was still going ${Math.round(Z/1000)}s after it started, past the live-run registry's age limit.`})}catch{}this.scheduleEviction(Q)},Z);G.unref?.(),Q.expireAt=G}}var sQ=new UQ;function nQ(Q,$){try{Q.onInternalError?.($)}catch{}}class DQ{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 tQ=new DQ;function G9(Q={}){return{messages:Q.messages?[...Q.messages]:[],pending:Q.pending?[...Q.pending]:[],error:null,threadId:Q.threadId,seq:Q.seq??-1,cursorRunId:Q.cursorRunId,runMessageIds:[],loadedTools:[]}}function J9(Q,$,Z=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==Q.cursorRunId)&&$.seq<=Q.seq)return Q;return{...W9(Q,$.event,Z),seq:$.seq}}function W9(Q,$,Z){switch($.type){case"run-start":return{...Q,runId:$.runId,cursorRunId:$.runId,threadId:$.threadId??Q.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0};case"message-start":return A(Q,$.messageId,Z,(G)=>({...G,role:$.role}));case"text-delta":if($9(Q,$.messageId))return Q;return A(Q,$.messageId,Z,(G)=>({...G,content:T$(G.content,$.delta)}));case"reasoning-delta":if($9(Q,$.messageId))return Q;return A(Q,$.messageId,Z,(G)=>({...G,content:E$(G.content,$.delta,$.id)}));case"output-delta":return A(Q,$.messageId,Z,(G)=>({...G,content:Z9(G.content,{type:"output",value:$.snapshot,partial:!0},(J)=>J.type==="output")}));case"tool-call":return A(Q,$.messageId,Z,(G)=>{let J=G.content.findIndex((B)=>B.type==="tool-call"&&B.toolCallId===$.part.toolCallId),W=J===-1?void 0:G.content[J],Y=$.part.progress??W?.progress,K=$.part.nested??W?.nested,X=$.part.attachments??W?.attachments,V={...$.part,...Y?{progress:Y}:{},...K?{nested:K}:{},...X?{attachments:X}:{}},H=G.content.slice();if(J===-1)H.push(V);else H[J]=V;return{...G,content:H}});case"tool-search":{let G=$.loaded.filter((J)=>!Q.loadedTools.includes(J));if(G.length===0)return Q;return{...Q,loadedTools:[...Q.loadedTools,...G]}}case"tool-progress":return Q9(Q,$.toolCallId,(G)=>({...G,progress:[...G.progress??[],$.data]}));case"nested-event":{let G=$;return Q9(Q,$.toolCallId,(J)=>{let W=J.nested??[],Y=W.findIndex((H)=>H.runId===G.runId),K=W[Y]??{runId:G.runId,agent:G.agent,messages:[]},X=S$(K,G,Z),V=Y===-1?[...W,X]:W.map((H,B)=>B===Y?X:H);return{...J,nested:V}})}case"tool-result":{let G=A(Q,$.messageId,Z,(J)=>({...J,content:Z9(J.content,$.part,(W)=>W.type==="tool-result"&&W.toolCallId===$.part.toolCallId)}));return{...G,pending:G.pending.filter((J)=>J.toolCallId!==$.part.toolCallId)}}case"message":{let G=Q.messages.findIndex((Y)=>Y.id===$.message.id),J=Q.messages.slice();if(G===-1)J.push($.message);else J[G]=$.message;let W=Q.runMessageIds.includes($.message.id)?Q.runMessageIds:[...Q.runMessageIds,$.message.id];return{...Q,messages:J,runMessageIds:W}}case"awaiting-input":return{...Q,runId:$.runId,pending:[...$.pending]};case"message-end":return A(Q,$.messageId,Z,(G)=>({...G,finishReason:$.finishReason,...$.outputTruncated?{outputTruncated:!0}:{},content:$.outputTruncated||$.finishReason==="length"?G.content.filter((J)=>!(J.type==="output"&&J.partial)):G.content.map((J)=>J.type==="output"&&J.partial?{...J,partial:!1}:J)}));case"usage":{let G=k$(Q.messages,(W)=>W.role==="assistant");if(G===-1)return Q;let J=Q.messages.slice();return J[G]={...J[G],usage:$.usage},{...Q,messages:J}}case"error":return{...Q,error:$.error,pending:[]};case"run-end":return{...Q,runId:void 0,finishReason:$.finishReason,messages:Y9(Q,$.finishReason)};default:return Q}}function Y9(Q,$){return Q.messages.map((Z)=>Z.role==="assistant"&&Q.runMessageIds.includes(Z.id)?M$(Z,$):Z)}function M$(Q,$){let Z=Q.content.map((J)=>J.type==="tool-call"&&J.nested?.some((W)=>W.finishReason===void 0)?{...J,nested:J.nested.map((W)=>W.finishReason===void 0?q$(W,$):W)}:J);if(Q.finishReason===void 0)return{...Q,finishReason:$,content:Z};return Z.some((J,W)=>J!==Q.content[W])?{...Q,content:Z}:Q}function q$(Q,$){let Z={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((G)=>G.id),loadedTools:[]};return{...Q,finishReason:$,messages:Y9(Z,$)}}function Q9(Q,$,Z){for(let G=Q.messages.length-1;G>=0;G--){let J=Q.messages[G],W=J.content.findIndex((V)=>V.type==="tool-call"&&V.toolCallId===$);if(W===-1)continue;if(J.finishReason!==void 0&&!R$(Q,J,$))return Q;let Y=J.content.slice();Y[W]=Z(Y[W]);let K=Q.messages.slice();K[G]={...J,content:Y};let X=Q.runMessageIds.includes(J.id)?Q.runMessageIds:[...Q.runMessageIds,J.id];return{...Q,runMessageIds:X,messages:K}}return Q}function S$(Q,$,Z){let G={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((W)=>W.id),loadedTools:[],finishReason:Q.finishReason},J=W9(G,$.event,Z);return{...Q,...$.label!==void 0?{label:$.label}:{},messages:J.messages,...J.finishReason!==void 0?{finishReason:J.finishReason}:{},...$.event.type==="usage"?{usage:$.event.usage}:{}}}function R$(Q,$,Z){if($.finishReason!=="awaiting-input")return!1;return!Q.messages.some((G)=>G.content.some((J)=>J.type==="tool-result"&&J.toolCallId===Z))}function $9(Q,$){let Z=Q.messages.find((G)=>G.id===$);return Z!==void 0&&Z.finishReason!==void 0}function k$(Q,$){for(let Z=Q.length-1;Z>=0;Z--)if($(Q[Z]))return Z;return-1}function A(Q,$,Z,G){let J=Q.messages.findIndex((K)=>K.id===$),W=Q.runMessageIds.includes($)?Q.runMessageIds:[...Q.runMessageIds,$];if(J===-1){let K={id:$,role:"assistant",content:[],createdAt:Z};return{...Q,runMessageIds:W,messages:[...Q.messages,G(K)]}}let Y=Q.messages.slice();return Y[J]=G(Y[J]),{...Q,runMessageIds:W,messages:Y}}function T$(Q,$){let Z=Q[Q.length-1];if(Z&&Z.type==="text")return[...Q.slice(0,-1),{type:"text",text:Z.text+$}];return[...Q,{type:"text",text:$}]}function E$(Q,$,Z){let G=Q[Q.length-1];if(G&&G.type==="reasoning"&&G.id===Z)return[...Q.slice(0,-1),{...G,text:(G.text??"")+$}];return[...Q,Z?{type:"reasoning",id:Z,text:$}:{type:"reasoning",text:$}]}function Z9(Q,$,Z){let G=Q.findIndex(Z);if(G===-1)return[...Q,$];let J=Q.slice();return J[G]=$,J}class aQ{store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(Q,$,Z,G){this.store=Q;this.threadId=$;this.report=G;this.state=G9({messages:Z})}finish(Q){if(this.closed)return;this.done.add(Q.id),this.write(()=>[rQ(Q)])}frame(Q){if(this.closed)return;let $=Q.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=J9(this.state,Q),$.type){case"message":this.write(()=>[rQ($.message)]);return;case"tool-call":if($.part.partial)return;this.checkpoint($.messageId);return;case"message-start":case"tool-result":this.checkpoint($.messageId);return;default:return}}close(Q=[]){this.closed=!0;for(let $ of Q)this.done.add($.id)}settled(){return this.chain}checkpoint(Q){if(this.done.has(Q))return;let $=this.state.messages.find((G)=>G.id===Q);if(!$)return;let Z=this.runId;this.write(()=>{let G=rQ($);if(G.finishReason===void 0&&Z)G.runId=Z;return[G]})}write(Q){let $;try{$=Q()}catch(Z){this.report(Z);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,$)).catch((Z)=>this.report(Z))}}function rQ(Q){return structuredClone(Q)}async function X9(Q,$){let Z=[],G=null,J=Q.slice();for(let W=0;W<J.length;W++){let Y=J[W];if(Y.role!=="assistant"||Y.finishReason!==void 0)continue;if(Y.runId&&await $(Y.runId))continue;G??=new Set(Q.flatMap((V)=>V.content.flatMap((H)=>H.type==="tool-result"?[H.toolCallId]:[])));let K=Y.content.map((V)=>V.type==="tool-call"?V9(V):V);for(let V of Y.content){if(V.type!=="tool-call"||G.has(V.toolCallId))continue;let H={type:"tool-result",toolCallId:V.toolCallId,name:V.name,status:"denied",cause:"interrupted"};K.push(H)}let X={...Y,content:K,finishReason:"interrupted"};J[W]=X,Z.push(X)}return{messages:J,settled:Z}}function V9(Q){let{partial:$,...Z}=Q;if(!Z.nested?.some((G)=>G.finishReason===void 0))return Z;return{...Z,nested:Z.nested.map(A$)}}function A$(Q){if(Q.finishReason!==void 0)return Q;return{...Q,finishReason:"interrupted",messages:Q.messages.map(($)=>$.role==="assistant"&&$.finishReason===void 0?{...$,finishReason:"interrupted",content:$.content.map((Z)=>Z.type==="tool-call"?V9(Z):Z)}:$)}}var x$=z9,FQ=new Map,K9=new WeakMap,OQ=new Map;class F9 extends x${static kind="agent-controller";store=tQ;liveRuns=sQ;attachments=t;attachmentStorage=D9;hookHoldMs=30000;instructions(Q,$){}context(Q,$){return{}}requireThread=!1;authorizeRequest(Q,$){}async stream(Q=new l){let $=await eQ(Q);if($.error)return LQ($);let Z=$.body,G=typeof Z.threadId==="string"?Z.threadId:void 0,J=f$(Z);if(J.error)return LQ({body:{},error:J.error});let W=J.turn,Y=typeof Z.clientRunId==="string"?Z.clientRunId:void 0,K=O9(Z);if(this.requireThread&&!G)return M(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)OQ.set(Y,X);let V=async()=>{let H;if(G){let C=await this.store.loadThread(G);if(!C)return M(404,{code:"thread_not_found",message:`Thread ${G} does not exist here, or has expired.`});H=await this.settleThread(G,C,{write:!0})}else H=Array.isArray(Z.messages)?Z.messages:[];let B=await this.instructions(Q,{body:K})||void 0,z=await this.context(Q,{body:K}),D=await this.attachmentsFor(Q,G,{body:K});if(X?.cancelled)return H9();let F=G?new aQ(this.store,G,H,(C)=>this.reportHookFailure(C)):null,U=this.agent.stream({messages:H,turn:W,threadId:G,...F?{onMessage:(C)=>F.finish(C)}:{},instructions:B,context:z,attachments:D,body:K}),L={req:Q,runId:U.runId,threadId:G},O=this.liveRuns.register(U,{threadId:G,clientRunId:Y,onEvent:(C)=>this.dispatchEvent(C,L),onInternalError:(C)=>this.reportHookFailure(C),maxRunDurationMs:this.agent.maxRunDurationMs});if(F)this.follow(U,F);let{stored:x,hooks:q}=this.persistRun(U,L,O,F);return K9.set(U,x),Q.ctx?.()?.waitUntil(q),U.toResponse()};try{if(await this.authorizeRequest(Q,{route:"stream",threadId:G,body:K}),X?.cancelled)return H9();return G?await this.withThread(G,V):await V()}finally{if(X&&OQ.get(Y)===X)OQ.delete(Y)}}async withThread(Q,$){let Z=FQ.get(Q)??Promise.resolve(),G,J=new Promise((Y)=>{G=Y}),W=Z.then(()=>J);FQ.set(Q,W),await Z;try{let Y=await this.liveRuns.find({threadId:Q}),K=Y?this.liveRuns.get(Y.runId):null;if(K)K.stop({reason:"superseded by a later turn on this thread"}),await K9.get(K);return await $()}finally{if(G(),FQ.get(Q)===W)FQ.delete(Q)}}async attach(Q=new l){let $=await eQ(Q);if($.error)return LQ($);let Z=$.body,G=typeof Z.threadId==="string"?Z.threadId:h$(Q,"threadId");if(!G)return M(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 M(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:y$(Q,Z);try{return C6(this.liveRuns.replay(J.runId,Y))}catch(K){if(K instanceof y)return M(410,{code:K.code,message:K.message,oldestSeq:K.oldest});if(K instanceof m)return M(404,{code:K.code,message:K.message});throw K}}async stop(Q=new l){let $=await eQ(Q);if($.error)return LQ($);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=OQ.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,$,Z){let G=Q.ctx()?.user,J=G?.id??G?.publicId;if(J!==void 0&&J!==null&&String(J)!=="")return{key:`user:${String(J)}`};if($)return{key:`thread:${$}`};return null}attachmentDestination(Q,$){return"both"}async attachmentsFor(Q,$,Z={body:{}}){let G=await this.attachmentScope(Q,$,Z);if(!G)return null;return new u(this.attachments,this.attachmentStorage,G)}async upload(Q=new l){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=I$($.get("body")),Y=$.get("threadId");await this.authorizeRequest(Q,{route:"upload",threadId:typeof Y==="string"&&Y.length>0?Y:void 0,body:W});let K=typeof Y==="string"&&Y.length>0&&await this.store.loadThread(Y)!==null?Y:void 0,X=await this.attachmentDestination(Z,Q),V=u$(X,$.get("destination")),H=await this.attachmentScope(Q,K,{body:W}),B=V!=="provider"&&!H;if(B){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()`.');g$()}if(V==="provider"||!H){let O={fileId:await this.agent.provider.upload(Z),name:G,mimeType:J,size:Z.size,destination:"provider"};if(B)O.downgraded="no_scope";return O}let z=_Q(),D=await this.attachmentStorage.put({name:jQ(z,G),body:Z,contentType:J}),F=V==="both"?await this.agent.provider.upload(Z):void 0,U={id:z,scopeKey:H.key,fileId:F,objectName:D,name:G,mimeType:J,size:Z.size,createdAt:new Date().toISOString(),destination:V};return await this.attachments.put(H,U),{fileId:F,attachmentId:z,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}}async readThread(Q){let $=await this.store.loadThread(Q);return $?await this.settleThread(Q,$,{write:!1}):null}isRunLive(Q,$){return this.liveRuns.get(Q)!==null}async settleThread(Q,$,{write:Z}){let{messages:G,settled:J}=await X9($,(W)=>this.isRunLive(W,Q));if(Z&&J.length>0)try{await this.store.appendMessages(Q,J)}catch(W){this.reportHookFailure(W)}return G}follow(Q,$){(async()=>{try{for await(let Z of Q.frames())$.frame(Z)}catch(Z){this.reportHookFailure(Z)}})()}persistRun(Q,$,Z,G=null){let J=Promise.resolve(),W=(async()=>{let K;try{K=await Q.result()}catch(V){G?.close(),await G?.settled(),J=this.safely(()=>this.onError({code:"unknown",message:V instanceof Error?V.message:String(V),retryable:!1},$));return}let X=K.messages;if(G?.close(X),await G?.settled(),$.threadId&&X.length>0)try{await this.store.appendMessages($.threadId,X)}catch(V){this.reportHookFailure(V)}J=this.notifyRun(K,X,$)})(),Y=W.then(()=>p$(Promise.all([J,Z]).then(()=>{}),this.hookHoldMs));return{stored:W,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($)}}}var Q6=["turn","clientRunId","threadId","messages"],b$=["text","files","toolResults"];function O9(Q,$=L9(Q)?Q6:[...Q6,...b$]){let 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}function I$(Q){if(Q===null)return{};let $;if(typeof Q==="string")try{$=JSON.parse(Q)}catch{throw new $6("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new $6("The upload's `body` field must be a JSON object.");return O9($,Q6)}class $6 extends U9{constructor(Q){super(Q);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:Q}}},view:{}}}}async function eQ(Q){let $=Q?.rawRequest;if(!$||$.method==="GET"||$.method==="HEAD"||!$.body)return{body:{}};if(!w$($.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 w$(Q){if(typeof Q!=="string")return!1;let[$]=Q.split(";",1);return $.trim().toLowerCase()==="application/json"}function LQ(Q){return M(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function L9(Q){return Boolean(Q.turn)&&typeof Q.turn==="object"}function f$(Q){let $=L9(Q)?Q.turn:Q,Z={};if(typeof $.text==="string")Z.text=$.text;if(Array.isArray($.files)){let G=v$($.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 v$(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 H of["fileId","attachmentId","name","mimeType"]){let B=G[H];if(B===void 0||B===null||B==="")continue;if(typeof B!=="string")return`${J}.${H} must be a string.`;W[H]=B}let{fileId:Y,attachmentId:K,name:X,mimeType:V}=W;if(Y?.startsWith(_))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(K!==void 0&&!K.startsWith(_))return`${J}.attachmentId is not a gemi attachment id: it must start with "${_}".`;if(!Y&&!K)return`${J} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...Y?{fileId:Y}:{},...K?{attachmentId:K}:{},...X!==void 0?{name:X}:{},...V!==void 0?{mimeType:V}:{}})}return $}function y$(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 h$(Q,$){let Z=Q?.search?.get($);return typeof Z==="string"?Z:void 0}function H9(){return M(409,{code:"stopped",message:"The turn was stopped before it started."})}function M(Q,$){return new Response(JSON.stringify({error:$}),{status:Q,headers:{"Content-Type":"application/json"}})}function u$(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 B9=!1;function g$(){if(B9)return;B9=!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 c$=2147483647;function p$(Q,$){let Z=Q.then(()=>{},()=>{});if(!($<=c$))return Z;let G,J=new Promise((W)=>{G=setTimeout(W,$)});return Promise.race([Z,J]).finally(()=>clearTimeout(G))}export{i9 as toAgentTools,JQ as supportsStrict,m$ as s,sQ as liveRuns,t as defaultAttachmentStore,tQ as defaultAgentStore,WQ as ToolNamespace,AQ as Skill,u as ScopedAttachments,c as SKILLS_NAMESPACE,k as PendingEscalation,iQ as OpenAIProvider,yQ as OpenAIImageProvider,UQ as MemoryLiveRuns,s as MemoryAttachmentStore,DQ as MemoryAgentStore,m as LiveRunNotFoundError,f as InvalidAttachmentScopeError,VQ as ImageRequestError,KQ as ImageProvider,wQ as ImageModel,y as FrameCursorEvictedError,xQ as DEFAULT_MAX_RUN_DURATION_MS,oQ as AzureOpenAIProvider,hQ as AzureOpenAIImageProvider,h as AttachmentNotFoundError,T as AgentTool,bQ as AgentRunError,zQ as AgentProvider,F9 as AgentController,IQ as Agent};
|
|
15
|
+
`):void 0}async runTools(Q,$,Z){let J=[],G=[];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 K=W.tool.inputSchema.safeParse(Y.input);if(K.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)}": ${K.errors.join(", ")}`,toolCallId:Y.toolCallId,retryable:!0}});continue}Y.input=K.value;let V=v6(W.tool);if(V){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(Y));continue}J.push({toolCallId:Y.toolCallId,name:Y.name,input:K.value,kind:V,signature:O6(this.claimsFor(Y.toolCallId,String(Y.name),V,K.value)),...this.pathPrefix.length>0?{path:[...this.pathPrefix]}:{}});continue}G.push(this.executeTool(W,Q.id,Y,K.value,Z).then(async(X)=>{this.addResult(Q,X),await this.settleShown(Y.toolCallId)}).catch((X)=>{if(X instanceof x){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(Y));return}J.push(...X.pending);return}}))}return await T(Promise.all(G).then(()=>{return}),this.controller.signal),J}claimsFor(Q,$,Z,J){return{runId:this.signingRunId,toolCallId:Q,name:$,kind:Z,input:J,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,J,G,Y){let W=Q.tool.timeoutMs;if(W===void 0)return this.runToolBody(Q,$,Z,J,G,Y,this.controller.signal,()=>!1);let K=new AbortController,V=this.controller.signal,X=()=>K.abort(V.reason);if(V.aborted)X();else V.addEventListener("abort",X,{once:!0});let H=!1,B=this.runToolBody(Q,$,Z,J,G,Y,K.signal,()=>H),z=()=>{},D=new Promise((F)=>{z=T6(W,()=>{let U=`"${String(Z.name)}" did not finish within ${wQ(W)} (timeoutMs: ${W}) and was cancelled.`;K.abort(new DOMException(U,"TimeoutError")),F({type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:{code:"timeout",message:U,toolCallId:Z.toolCallId,retryable:!0}})})});B.catch(()=>{});try{return await Promise.race([B,D])}finally{H=!0,z()}}async runToolBody(Q,$,Z,J,G,Y,W,K){let V=this.toolFiles(Z,W),X={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,toolCallId:Z.toolCallId,signal:W,step:G,depth:this.depth,resumed:Y!==void 0,attachments:V.attachments,generateImage:V.generateImage,editImage:V.editImage,turn:this.toolTurn($),runAgent:this.nestedRunner($,Z,W,Y),generate:(H)=>this.generateForTool(H,W,Z.toolCallId)};try{let H=Q.tool.execute(J,X),B;if(s9(H)){let z=await H.next();while(!z.done){if(K())throw H.return(void 0).catch(()=>{}),new P;this.emit({type:"tool-progress",toolCallId:Z.toolCallId,data:z.value}),z=await H.next()}B=z.value}else B=await H;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"ok",output:B}}catch(H){if(H instanceof P||this.controller.signal.aborted)throw new P;if(H instanceof x)throw H;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:{code:"tool_error",message:H instanceof Error?H.message:String(H),toolCallId:Z.toolCallId,retryable:!0}}}}async generateForTool(Q,$,Z){let J=this.controller.signal;return RQ({...Q,signal:Q.signal?AbortSignal.any([$,Q.signal]):$},{origin:{agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},toolCallId:Z},settled:(G)=>{if(this.usage=q(this.usage,G.usage),J.aborted)throw new P}})}nestedRunner(Q,$,Z,J){let G=new vQ(()=>$.nested,()=>$.nested=[]);return async(Y,W={})=>{let{at:K,recorded:V,write:X}=G.next();if(V){let H=a9(V,Y,W);if(H)throw Error(`Nested run ${K} of "${String($.name)}" ${H}. `+"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??A(),output:x6(V.messages),nested:V}}return this.runNested(Q,$,Z,Y,W,X,V,J?.answers??[])}}async runNested(Q,$,Z,J,G,Y,W,K){let V=[...this.chain,J.name];if(this.chain.includes(J.name))throw Error(`"${J.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 H=G.label,B=[...this.pathPrefix,$.toolCallId],z=this.onPending==="deny"?"deny":G.onPending??"escalate",D=W!==void 0,F=D?BQ(W.messages):new Set,U=D?K.filter((N)=>{let y=f6(N.path,B);if(y===null)return!1;return F.has(y.length>0?y[0]:N.toolCallId)}):[],L=J.stream({messages:D?W.messages:G.messages??[],turn:D?{toolResults:U}:G.prompt?{text:G.prompt}:void 0,context:this.context,attachments:this.params.attachments,body:this.params.body,signal:Z,threadId:this.params.threadId,instructions:G.instructions,maxOutputTokens:G.maxOutputTokens,temperature:G.temperature,runId:D?W.runId:void 0,nesting:{depth:X,maxDepth:this.maxDepth,chain:V,signingRunId:this.signingRunId,signingPath:B,onPending:z}}),O=[],f=(async()=>{for await(let N of L){if(N.type==="awaiting-input")O=N.pending;this.emit({type:"nested-event",toolCallId:$.toolCallId,runId:L.runId,agent:J.name,label:H,event:N})}})(),R=(async()=>{let N=await L.result();await f;let y=D?E6(W.messages,N.messages):E6(G.messages??[],N.messages),K6={runId:L.runId,agent:J.name,label:H,messages:y,finishReason:N.finishReason,usage:D?q(W.usage??A(),N.usage):N.usage,...N.finishReason==="awaiting-input"?{signature:C6({runId:this.signingRunId,path:B,nestedRunId:L.runId,open:[...BQ(y)],input:$.input})}:{}};return Y(K6),this.usage=q(this.usage,N.usage),{result:N,record:K6}})(),C=R.then(()=>{return},()=>{return});this.nestedSettling.add(C);let v,k;try{({result:v,record:k}=await R)}finally{this.nestedSettling.delete(C)}if(this.controller.signal.aborted)throw new P;if(v.finishReason==="awaiting-input"){if(O.length===0)throw Error(`"${J.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 x({pending:O,path:B,nested:k})}return{runId:k.runId,agent:J.name,messages:k.messages,finishReason:v.finishReason,usage:k.usage??A(),output:v.output??x6(k.messages),...v.error?{error:v.error}:{},nested:k}}addResult(Q,$){Q.content.push($),this.emit({type:"tool-result",messageId:Q.id,part:$})}toolFiles(Q,$){let Z=this.params.attachments??null,J=new vQ(()=>Q.attachments,()=>Q.attachments=[],()=>({failed:!0})),G=()=>{if(!Z)throw new u("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 Z},Y=async(X,H,B)=>{let z=G(),D=H.mimeType||X.type||"",F=H.name??(X instanceof File?X.name:"attachment"),U;if(H.showModel){let O=this.config.provider;if(!O.capabilities.fileInput)throw Error(`"${String(Q.name)}" asked to show a file to ${O.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.`);U=await O.upload(new File([X],F,{type:D||void 0}))}return{attachment:await z.put(X,{name:F,mimeType:D,fileId:U}),...B?{generated:B}:{},...U?{shown:{fileId:U,messageId:`msg_${crypto.randomUUID()}`,createdAt:new Date().toISOString()}}:{}}},W=(X,H,B)=>{let z=X.generated?"image":"put";if(z===H)return;throw Error(`Attachment ${B} of "${String(Q.name)}" was ${z==="image"?"a generated image":"a stored file"} on the first attempt and is ${H==="image"?"a generated image":"a stored file"} now. ctx.attachments.put, ctx.generateImage and ctx.editImage share one memo indexed by call order within a tool call, so the sequence has to be the same every time this tool runs. Branch on ctx.resumed if it cannot be.`)},K=async(X,H,B)=>{let{at:z,recorded:D,write:F}=J.next();if(D&&"attachment"in D){if(W(D,"image",z),D.shown)this.queueShown(Q.toolCallId,D);return{attachment:D.attachment,size:D.generated.size,mimeType:D.attachment.mimeType,usage:D.generated.usage}}let U=await B();this.usage=q(this.usage,U.usage);let L=U.mimeType==="image/jpeg"?"jpg":"png",O=await Y(U.image,{name:H.name??`${X.name}.${L}`,mimeType:U.mimeType,...H.showModel?{showModel:!0}:{}},{size:U.size,usage:U.usage});if(F(O),O.shown)this.queueShown(Q.toolCallId,O);return{attachment:O.attachment,size:U.size,mimeType:U.mimeType,usage:U.usage}},V=async(X)=>typeof X==="string"?await G().file(X):X;return{generateImage:(X,H)=>K(X,H,()=>X.generate({...H,signal:$})),editImage:(X,H)=>K(X,H,async()=>{let{images:B,mask:z,...D}=H;return await X.edit({...D,images:await Promise.all(B.map(V)),...z?{mask:await V(z)}:{},signal:$})}),attachments:{get:(X)=>G().get(X),read:(X)=>G().read(X),file:(X)=>G().file(X),put:async(X,H={})=>{let{at:B,recorded:z,write:D}=J.next();if(z&&"attachment"in z){W(z,"put",B);let U=r9(z,X,H);if(U)throw Error(`Attachment ${B} 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(z.shown)this.queueShown(Q.toolCallId,z);return z.attachment}let F=await Y(X,H);if(D(F),F.shown)this.queueShown(Q.toolCallId,F);return F.attachment}}}}toolTurn(Q){let $=this.history.findIndex((Y)=>Y.id===Q),Z=I6(this.history),J;for(let Y=$-1;Y>=0;Y--){let W=this.history[Y];if(W.role!=="user"||Z.has(W.id))continue;J=W;break}let G=[];for(let Y of J?.content??[]){if(Y.type!=="file")continue;let W=Y.attachmentId;if(typeof W!=="string"||!W.startsWith(j))continue;if(!G.includes(W))G.push(W)}return Object.freeze({attachments:Object.freeze(G)})}queueShown(Q,$){let Z=$.shown;if(!Z)return;let J=this.shownQueue.get(Q)??[];if(J.some((G)=>G.id===Z.messageId))return;J.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,J)}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((J)=>J.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=I6($),J=[];for(let Y of $){if(!Z.has(Y.id))continue;for(let W of Y.content)if(W.type==="file")J.push(W)}if(J.length<=w6)return $;let G=new Set(J.slice(0,J.length-w6));return $.map((Y)=>{if(!Y.content.some((W)=>W.type==="file"&&G.has(W)))return Y;return{...Y,content:Y.content.map((W)=>W.type==="file"&&G.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 J=new Set,G=new Set,Y=new Map;for(let W of Q?.toolResults??[]){let K=`${(W.path??[]).join("/")}#${W.toolCallId}`;if(G.has(K))continue;G.add(K);let V=(z)=>this.emit({type:"error",error:{code:"invalid_tool_result",message:z,toolCallId:W.toolCallId,retryable:!1}}),X=f6(W.path,this.pathPrefix);if(X===null){V(`The answer for "${W.toolCallId}" is addressed to a tool call this run is not inside.`);continue}if(X.length>0){let z=X[0],D=$.find((L)=>L.call.toolCallId===z);if(!D){V(`No pending tool call with id "${z}" to deliver a nested answer to.`);continue}let F=this.parkedBelow(D.call,X,W.toolCallId);if(F.ok===!1){let L=`The answer for "${W.toolCallId}" is addressed under "${z}", which`;V(F.reason==="unparked"?`${L} has no sub-agent run waiting on that question.`:F.reason==="expired"?`${L} parked a sub-agent run that has since expired. Ask again.`:`${L} carries a record of a parked sub-agent run the server did not sign.`);continue}let U=Y.get(z);if(!U){if(!M6(F.signature)){V(`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),J.add(z)}U.push(W);continue}let H=$.find((z)=>z.call.toolCallId===W.toolCallId);if(!H){V(`No pending tool call with id "${W.toolCallId}".`);continue}let B=await this.resolveAnswer(H,W,Z);if(B===null)continue;if(J.add(W.toolCallId),B!=="open")this.attachToHistory(H,B),await this.settleShown(W.toolCallId)}for(let[W,K]of Y){let V=$.find((H)=>H.call.toolCallId===W),X=await this.reenter(V,K,Z);if(X)this.attachToHistory(V,X),await this.settleShown(W)}for(let W of $){if(J.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 J={id:`msg_${crypto.randomUUID()}`,role:"user",content:[...Q.text?[{type:"text",text:Q.text}]:[],...(Q.files??[]).map((G)=>({type:"file",...G.fileId?{fileId:G.fileId}:{},name:G.name,mimeType:G.mimeType,...G.attachmentId?{attachmentId:G.attachmentId}:{}}))],createdAt:new Date().toISOString(),finishReason:"stop"};this.history.push(J),this.produced.push(J),await this.report(J)}return Z}parkedBelow(Q,$,Z){let J=$.length>1?$[1]:Z,G=[...this.pathPrefix,Q.toolCallId],Y=(Q.nested??[]).find((K)=>K.finishReason==="awaiting-input"&&BQ(K.messages).has(J));if(!Y)return{ok:!1,reason:"unparked"};if(typeof Y.signature!=="string")return{ok:!1,reason:"unsigned"};let W=P6(Y.signature,{path:G,nestedRunId:Y.runId,open:[...BQ(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 J=String(Q.call.name),G=this.config.registry.get(J);if(!G||!G.tool.execute)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_result",message:`The tool "${J}" no longer exists, so the sub-agent's question cannot be delivered.`,toolCallId:Q.call.toolCallId,retryable:!1}};let Y=G.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 "${J}": ${Y.errors.join(", ")}`,toolCallId:Q.call.toolCallId,retryable:!0}};let W=this.amendCall(Q);W.input=Y.value;try{return await T(this.executeTool(G,Q.message.id,W,Y.value,0,{answers:$}),this.controller.signal)}catch(K){if(K instanceof x)return Z.push(...K.pending),null;throw K}}amendCall(Q){let $=this.amend(Q.message),Z=$.content.indexOf(Q.call),J={...Q.call,nested:(Q.call.nested??[]).map((G)=>({...G})),...Q.call.attachments?{attachments:Q.call.attachments.map((G)=>({...G}))}:{}};if(Z>=0)$.content[Z]=J;return this.unreported.add($),J}openCalls(){let Q=new Set;for(let Z of this.history)for(let J of Z.content)if(J.type==="tool-result")Q.add(J.toolCallId);let $=[];for(let Z of this.history)for(let J of Z.content)if(J.type==="tool-call"&&!Q.has(J.toolCallId))$.push({message:Z,call:J});return $}async resolveAnswer(Q,$,Z){let J=Q.call,G=String(J.name),Y=this.config.registry.get(G),W=(H)=>{return this.emit({type:"error",error:{code:"invalid_tool_result",message:H,toolCallId:J.toolCallId,retryable:!1}}),null};if(!Y)return W(`The tool "${G}" no longer exists, so its answer cannot be checked.`);let K=v6(Y.tool);if(!K)return W(`"${G}" is a server tool with no pending question.`);if(typeof $.signature!=="string"||$.signature.length===0)return W(`The answer for "${G}" carried no signature.`);let V=XQ($.signature);if(!V)return W(`The signature for "${G}" is malformed.`);let X=L6($.signature,{...this.claimsFor(J.toolCallId,G,K,J.input),runId:V.runId});if(X.ok===!1)return W(X.reason==="expired"?`The approval for "${G}" has expired. Ask again.`:`The answer for "${G}" does not match the call the server made.`);if(!j6($.signature))return W(`The answer for "${G}" has already been used. Ask again.`);if("approve"in $){if(K!=="approval")return W(`"${G}" is answered by the client, not approved.`);if($.approve===!0){let H=this.amendCall(Q);try{return await T(this.executeTool(Y,Q.message.id,H,H.input,0),this.controller.signal)}catch(B){if(B instanceof x)return Z.push(...B.pending),"open";throw B}}return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"denied",cause:"refused",reason:$.reason}}if("output"in $){if(K==="approval")return W(`"${G}" is approved, not answered: the server produces its result.`);let H=Y.tool.outputSchema,B=H?H.safeParse($.output):{ok:!0,value:$.output};if(B.ok===!1)return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"error",error:{code:"invalid_tool_result",message:`The answer for "${G}" did not match its output schema: ${B.errors.join(", ")}`,toolCallId:J.toolCallId,retryable:!0}};return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"ok",output:B.value}}return W(`The answer for "${G}" 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]},J=this.history.indexOf(Q);if(J>=0)this.history[J]=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})}}if(this.timedOutAfter!==void 0){this.fail({code:"timeout",message:`The run did not finish within its time limit of ${wQ(this.timedOutAfter)} (maxRunDurationMs: ${this.timedOutAfter}) and was stopped.`,retryable:!0}),this.finishReason="error",await this.finalizeMessage("error");return}this.finishReason="aborted",await this.finalizeMessage("aborted")}}function v6(Q){if(Q.answeredBy==="client")return Q.inputSchema===yQ?"question":"client";return Q.requiresApproval?"approval":null}function y6(Q){if(!Q||!Q.trim())return{};try{return JSON.parse(Q)}catch{return Q}}function e9(Q,$){return Q.descriptors($).map((Z)=>b.create({name:Z.name,description:Z.description,inputSchema:Z.inputSchema,requiresApproval:Z.requiresApproval,execute:(J,G)=>{let Y=zQ.getStore()?.req;if(!Y)throw Error(`"${Z.name}" calls an api route as the user who started this run, and this run was not started inside a request. Run it from an AgentController, or give this agent tools that do not go through the MCP registry.`);return Q.execute({kind:"local",req:Y},Z.name,J,G)}}))}function Q$(Q){if(Q==="auto")return;let $=/^(\d+)x(\d+)$/.exec(Q);if(!$)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(Q)}.`);let Z=Number($[1]),J=Number($[2]);if(Z%16!==0||J%16!==0)throw Error(`Image size ${Q} is not supported: width and height must both be divisible by 16.`);if(Math.max(Z/J,J/Z)>3)throw Error(`Image size ${Q} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function m6(Q,$){if(Q.size!==void 0)try{Q$(Q.size)}catch(Z){throw Error(`${$}: ${Z.message}`)}if(Q.background==="transparent"&&Q.format==="jpeg")throw Error(`${$}: a transparent background needs "png"; JPEG has no alpha channel.`);if(Q.compression!==void 0){let Z=Q.compression;if(!Number.isInteger(Z)||Z<0||Z>100)throw Error(`${$}: compression is an integer from 0 to 100; got ${Z}.`)}}function p6(Q,$){if(Q instanceof File)return Q;let Z=Q.type||"image/png",J=Z==="image/jpeg"?"jpg":Z.split("/")[1]??"png";return new File([Q],`${$}.${J}`,{type:Z})}class cQ{name;provider;settings;constructor(Q){let{name:$,provider:Z,...J}=Q;m6(J,`ImageModel "${$}"`),this.name=$,this.provider=Z,this.settings=J}static create(Q){return new cQ(Q)}async generate(Q){let $=this.merge(Q);return d6(await this.provider.generate({prompt:Q.prompt,...$,signal:Q.signal}))}async edit(Q){let $=this.merge(Q);return d6(await this.provider.edit({prompt:Q.prompt,...$,images:Q.images.map((Z,J)=>p6(Z,`image-${J}`)),...Q.mask?{mask:p6(Q.mask,"mask")}:{},signal:Q.signal}))}merge(Q){let $={...this.settings,...Q.size!==void 0?{size:Q.size}:{},...Q.quality!==void 0?{quality:Q.quality}:{},...Q.background!==void 0?{background:Q.background}:{},...Q.format!==void 0?{format:Q.format}:{},...Q.compression!==void 0?{compression:Q.compression}:{}};return m6($,`ImageModel "${this.name}"`),$}}function d6(Q){return{image:new Blob([Q.bytes],{type:Q.mimeType}),mimeType:Q.mimeType,size:Q.size,usage:Q.usage}}function I(Q){return typeof process>"u"?void 0:process.env?.[Q]}var $$="preview";function l6(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function Z$(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}function DQ(Q,$={}){return{base:(Q.baseURL??I("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let J=Q.apiKey??I("OPENAI_API_KEY");return{...J?{authorization:`Bearer ${J}`}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,maxRetries:Q.maxRetries??2}}function J$(Q){let $=Q.baseURL??Q.endpoint??I("AZURE_OPENAI_ENDPOINT");if($)return l6($);let Z=Q.resourceName??I("AZURE_OPENAI_RESOURCE_NAME")??I("AZURE_RESOURCE_NAME");return Z?l6(`https://${Z.trim()}.cognitiveservices.azure.com`):""}function FQ(Q,$={}){let Z=Q.apiVersion??I("AZURE_OPENAI_API_VERSION")??$$;return{base:`${J$(Q)}${Z$(Z)}`,query:`?api-version=${encodeURIComponent(Z)}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let J=Q.apiKey??I("AZURE_OPENAI_API_KEY");return{...J?{"api-key":J}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,maxRetries:Q.maxRetries??2}}var G$=500,o6=20000;function Y$(Q,$){if(!Q)return;let Z=Q.trim();if(/^\d+(\.\d+)?$/.test(Z))return Math.max(0,Number(Z)*1000);let J=Date.parse(Z);if(Number.isNaN(J))return;return Math.max(0,J-$)}function i6(Q,$){let Z=Math.min(o6,G$*2**Q);return Math.round(Z*(0.5+$()*0.5))}function W$(Q){return Q===429||Q===408||Q===409||Q>=500}function X$(Q,$){return W$(Q)&&_($).retryable}function n6(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function V$(Q,$){return new Promise((Z,J)=>{let G=setTimeout(Z,Q);$?.addEventListener("abort",()=>{clearTimeout(G),J(n6($))},{once:!0})})}async function n(Q,$,Z){let J=Z.fetchImpl??((H,B)=>fetch(H,B)),G=Z.sleep??V$,Y=Z.random??Math.random,W=Z.now??Date.now,K=Math.max(0,Z.maxRetries),V=async(H)=>{let B=Z.signal;if(!B)return await G(H);B.throwIfAborted();let z;try{await Promise.race([G(H,B),new Promise((D,F)=>{z=()=>F(n6(B)),B.addEventListener("abort",z,{once:!0})})])}finally{if(z)B.removeEventListener("abort",z)}},X;for(let H=0;H<=K;H++){Z.signal?.throwIfAborted();let B=new AbortController,z=()=>B.abort(Z.signal?.reason);Z.signal?.addEventListener("abort",z,{once:!0});let D=!1,F=Z.timeoutMs>0?setTimeout(()=>{D=!0,B.abort()},Z.timeoutMs):void 0,U;try{U=await J(Q,{...$,signal:B.signal})}catch(R){if(F!==void 0)clearTimeout(F);if(Z.signal?.removeEventListener("abort",z),Z.signal?.aborted)throw R;if(X=D?new a(Z.timeoutMs):R,D&&Z.retryTimeouts===!1)throw X;if(H===K)throw X;await V(i6(H,Y));continue}if(F!==void 0)clearTimeout(F);if(U.ok)return U;Z.signal?.removeEventListener("abort",z);let L=await K$(U),O=new r(U.status,L,U.headers.get("x-request-id")??void 0);if(H===K||!X$(U.status,O))throw O;let f=Y$(U.headers.get("retry-after"),W());await V(f===void 0?i6(H,Y):Math.min(f,o6)),X=O}throw X??Error("Provider request failed with no response.")}async function K$(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}var mQ=300000;function pQ(Q){return{generationsUrl:`${Q.base}/images/generations${Q.query}`,editsUrl:`${Q.base}/images/edits${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,maxRetries:Q.maxRetries}}class OQ extends Error{code;retryable;constructor(Q,$={}){super(Q.message,$);this.name="ImageRequestError",this.code=Q.code,this.retryable=Q.retryable}}var H$={png:"image/png",jpeg:"image/jpeg"};function B$(Q){let $=Number(Q?.input_tokens??0),Z=Number(Q?.output_tokens??0),J={inputTokens:$,outputTokens:Z,totalTokens:Number(Q?.total_tokens??$+Z)},G=Q?.input_tokens_details?.image_tokens;if(typeof G==="number")J.imageInputTokens=G;let Y=Q?.output_tokens_details?.image_tokens;if(typeof Y==="number")J.imageOutputTokens=Y;return J}function z$(Q){let $=atob(Q),Z=new Uint8Array($.length);for(let J=0;J<$.length;J++)Z[J]=$.charCodeAt(J);return Z}function U$(Q){let Z=Q?.data?.[0]?.b64_json;if(typeof Z!=="string"||Z.length===0)throw new OQ({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let J=typeof Q.output_format==="string"?Q.output_format:"png";return{bytes:z$(Z),mimeType:H$[J]??`image/${J}`,size:typeof Q.size==="string"?Q.size:"",...typeof Q.background==="string"?{background:Q.background}:{},usage:B$(Q.usage)}}async function s6(Q,$,Z,J){let G;try{G=await n(Q,$,{maxRetries:Z.maxRetries,timeoutMs:Z.timeoutMs,retryTimeouts:!1,signal:J.signal,fetchImpl:Z.fetchImpl})}catch(Y){if(J.signal?.aborted)throw Y;throw new OQ(_(Y),{cause:Y})}return U$(await G.json())}async function t6(Q,$,Z={}){return await s6(Q.generationsUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify($)},Q,Z)}async function r6(Q,$,Z={}){return await s6(Q.editsUrl,{method:"POST",headers:await Q.headers(),body:$},Q,Z)}class LQ{static models(){return[]}modelName(){return this.model}async generate(Q){return await t6(this.endpoint(),this.body(Q),{signal:Q.signal})}async edit(Q){let $=new FormData;for(let[Z,J]of Object.entries(this.body(Q)))if(J!==void 0)$.set(Z,String(J));for(let Z of Q.images)$.append("image[]",Z,Z.name);if(Q.mask)$.set("mask",Q.mask,Q.mask.name);return await r6(this.endpoint(),$,{signal:Q.signal})}body(Q){return{model:this.modelName(),prompt:Q.prompt,...Q.size?{size:Q.size}:{},...Q.quality?{quality:Q.quality}:{},...Q.background?{background:Q.background}:{},...Q.format?{output_format:Q.format}:{},...Q.compression!==void 0?{output_compression:Q.compression}:{}}}normalizeError(Q){return _(Q)}}var a6=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class dQ extends LQ{model;config;constructor(Q,$={}){super();this.model=Q,this.config=$}static model(Q,$){return new dQ(Q,$)}static models(){return a6}endpoint(){return pQ(DQ(this.config,{timeoutMs:mQ}))}}class lQ extends LQ{model;config;constructor(Q,$={}){super();this.model=Q,this.config=$}static model(Q,$){return new lQ(Q,$)}static models(){return a6}modelName(){return this.config.deployment??this.model}endpoint(){return pQ(FQ(this.config,{timeoutMs:mQ}))}}async function*D$(Q){let $="",Z="",J=[],G,Y=()=>{if(J.length===0&&!Z)return null;let V={event:Z,data:J.join(`
|
|
16
|
+
`),id:G};return Z="",J=[],G=void 0,V.data?V:null},W=(V)=>{let X=V.endsWith("\r")?V.slice(0,-1):V;if(X==="")return Y();if(X.startsWith(":"))return null;let H=X.indexOf(":"),B=H===-1?X:X.slice(0,H),z=H===-1?"":X.slice(H+1);if(z.startsWith(" "))z=z.slice(1);if(B==="event")Z=z;else if(B==="data")J.push(z);else if(B==="id")G=z;return null};for await(let V of Q){$+=V;let X=$.indexOf(`
|
|
17
|
+
`);while(X!==-1){let H=$.slice(0,X);$=$.slice(X+1);let B=W(H);if(B)yield B;X=$.indexOf(`
|
|
18
|
+
`)}}if($.length>0){let V=W($);if(V)yield V}let K=Y();if(K)yield K}async function*e6(Q,$={}){let Z=new Map,J=new Set,G=!1;for await(let Y of D$(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 V=String(W.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(W.delta??"");if(!V)break;yield{type:"reasoning-delta",delta:V,id:W.item_id};break}case"response.output_item.added":{let V=W.item;if(!V)break;if(V.type==="function_call"){let X=String(V.id??W.item_id??V.call_id??"");Z.set(X,{callId:String(V.call_id??X),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(W.item_id??""));if(!V)break;let X=String(W.delta??"");if(!X)break;yield{type:"tool-call-delta",toolCallId:V.callId,name:V.name,argsDelta:X,...V.namespace?{namespace:V.namespace}:{}};break}case"response.function_call_arguments.done":{let V=String(W.item_id??""),X=Z.get(V);if(!X)break;X.done=!0,yield{type:"tool-call",toolCallId:X.callId,name:X.name,args:String(W.arguments??""),...X.namespace?{namespace:X.namespace}:{}};break}case"response.output_item.done":{let V=W.item;if(!V)break;if(V.type==="function_call"){let X=String(V.id??W.item_id??V.call_id??""),H=Z.get(X);if(H?.done)break;let B=(typeof V.namespace==="string"?V.namespace:"")||H?.namespace;if(yield{type:"tool-call",toolCallId:String(V.call_id??X),name:String(V.name??H?.name??""),args:String(V.arguments??""),...B?{namespace:B}:{}},H)H.done=!0;break}if(V.type==="tool_search_call"||V.type==="tool_search_output"){let X=F$(V);if(X.loaded.length===0&&X.namespaces.length===0)break;let H=String(V.tool_search_call_id??V.id??"");if(J.has(H))break;J.add(H),yield{type:"tool-search",...X}}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":{G=!0,yield{type:"finish",reason:"stop",usage:iQ(W.response?.usage)};break}case"response.incomplete":{G=!0;let V=iQ(W.response?.usage),X=W.response?.incomplete_details?.reason;if(X==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:O$(W.response?.content_filters),retryable:!1}},yield{type:"finish",reason:"error",usage:V};break}yield{type:"finish",reason:X==="max_output_tokens"?"length":"stop",usage:V};break}case"response.failed":case"error":{G=!0;let V=W.response?.error??W.error??W;yield{type:"error",error:L$(V)},yield{type:"finish",reason:"error",usage:iQ(W.response?.usage)};break}}if(G)return}if(!G)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield{type:"finish",reason:"error",usage:g()}}function F$(Q){let $=[],Z=[];return Q9(Q.results??Q.tools??Q.loaded??Q.output,$,Z,0),{loaded:oQ($),namespaces:oQ(Z)}}function Q9(Q,$,Z,J){if(!Array.isArray(Q)||J>4)return;for(let G of Q){if(typeof G==="string"){$.push(G);continue}if(!G||typeof G!=="object")continue;let Y=G,W=typeof Y.name==="string"?Y.name:typeof Y.tool_name==="string"?Y.tool_name:"",K=Y.tools??Y.functions;if(Array.isArray(K)){if(W)Z.push(W);Q9(K,$,Z,J+1);continue}if(W)$.push(W)}}function oQ(Q){return Q.filter(($,Z)=>Q.indexOf($)===Z)}function O$(Q){if(!Array.isArray(Q))return"The provider's content filter blocked this request.";let Z=[];for(let J of Q){if(!J||typeof J!=="object")continue;let G=J,Y=G.content_filter_results;if(!Y||typeof Y!=="object")continue;for(let[W,K]of Object.entries(Y))if(K&&typeof K==="object"&&K.filtered===!0)Z.push(`${W} (${String(G.source_type??"unknown")})`)}return Z.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${oQ(Z).join(", ")}.`}function L$(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 g(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function iQ(Q){if(!Q)return g();let $=Number(Q.input_tokens??0),Z=Number(Q.output_tokens??0),J={inputTokens:$,outputTokens:Z,totalTokens:Number(Q.total_tokens??$+Z)},G=Q.output_tokens_details?.reasoning_tokens;if(typeof G==="number")J.reasoningTokens=G;let Y=Q.input_tokens_details?.cached_tokens;if(typeof Y==="number")J.cachedInputTokens=Y;return J}async function*$9(Q){if(!Q)return;let $=Q.getReader(),Z=new TextDecoder;try{while(!0){let{done:G,value:Y}=await $.read();if(G)break;if(Y)yield Z.decode(Y,{stream:!0})}let J=Z.decode();if(J)yield J}finally{$.releaseLock()}}function nQ(Q){return{responsesUrl:`${Q.base}/responses${Q.query}`,filesUrl:`${Q.base}/files${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,maxRetries:Q.maxRetries}}async function*sQ(Q,$,Z){let J;try{J=await n(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(G){let Y=_(G);if(Y.code!=="aborted")yield{type:"error",error:Y,...M(G)};yield{type:"finish",reason:Y.code==="aborted"?"aborted":"error",usage:g()};return}try{yield*e6($9(J.body),{structuredOutput:Z.structuredOutput})}catch(G){let Y=_(G);if(Y.code==="aborted"){yield{type:"finish",reason:"aborted",usage:g()};return}yield{type:"error",error:Y},yield{type:"finish",reason:"error",usage:g()}}}async function tQ(Q,$){let Z=new FormData;Z.set("purpose","user_data"),Z.set("file",$);let G=await(await n(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:Z},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl})).json();if(!G?.id)throw Error("The provider accepted the upload but returned no file id.");return G.id}function rQ(Q){let $=N$(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Z=C$($);if(Z?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Z.major>1,toolSearch:Z9(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:Z9(Z)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function Z9(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function N$(Q){return Q.trim().toLowerCase()}function C$(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 aQ(Q,$){let{capabilities:Z}=$,J={model:$.model,input:P$(Q.messages,Z),stream:!0};if(Q.systemPrompt)J.instructions=Q.systemPrompt;let G=A$(Q.tools,Z);if(G.length>0){if(J.tools=G,!Z.parallelToolCalls)J.parallel_tool_calls=!1}if(Q.output)J.text={format:{type:"json_schema",name:Q.output.name,schema:Q.output.schema,strict:Q.output.strict}};if(Q.reasoning&&Z.reasoning)J.reasoning=Q.reasoning==="none"?{effort:"none"}:{effort:Q.reasoning,summary:"auto"};if(typeof Q.temperature==="number")J.temperature=Q.temperature;if(typeof Q.maxOutputTokens==="number")J.max_output_tokens=Q.maxOutputTokens;return J}function P$(Q,$){let Z=[];for(let J of Q){let G=J.role,Y=[],W=()=>{if(Y.length===0)return;Z.push({type:"message",role:G,content:Y}),Y=[]};for(let K of J.content??[])switch(K.type){case"text":{if(!K.text)break;Y.push(NQ(G,K.text));break}case"output":{if(K.partial)break;Y.push(NQ(G,JSON.stringify(K.value)));break}case"file":{if(G==="assistant")break;let V=M$(K);if(!$.fileInput){if(V)Y.push(NQ(G,J9(K,!1)));break}if(K.fileId?.startsWith(j))throw Error(`FilePart.fileId holds a gemi attachment id (${K.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(!K.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)Y.push(NQ(G,J9(K,!!K.fileId)));if(K.fileId)Y.push(q$(K));break}case"reasoning":{W();let V=k$(K);if(V)Z.push(V);break}case"tool-call":{if(K.partial)break;W(),Z.push({type:"function_call",call_id:K.toolCallId,name:String(K.name),arguments:JSON.stringify(K.input??{})});break}case"tool-result":{W(),Z.push({type:"function_call_output",call_id:K.toolCallId,output:T$(K)});break}}W()}return j$(Z)}var _$="No result was recorded for this tool call. Assume it did not complete.";function j$(Q){let $=new Set,Z=new Set,J=[];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)}J.push(Y)}if(Z.size===$.size)return J;let G=[];for(let Y of J){if(G.push(Y),Y.type!=="function_call")continue;let W=String(Y.call_id);if(Z.has(W))continue;Z.add(W),G.push({type:"function_call_output",call_id:W,output:_$})}return G}function NQ(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function M$(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(j)?$:void 0}function J9(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 J=`attachment ${Z.join(" ")}`;return $?`[${J}]`:`[${J} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function q$(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":S$(Q.name))?"input_image":"input_file",file_id:Q.fileId}}function S$(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&R$.has($[1])}var R$=new Set(["jpeg","jpg","png","gif","webp"]);function k$(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function T$(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.${$}`;if(Q.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${Q.error?.code??"unknown"}): ${Q.error?.message??"no message"}`}function G9(Q){return Array.isArray(Q.tools)}function A$(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let G=[];for(let Y of Q)if(G9(Y))for(let W of Y.tools)G.push(CQ(W,!1));else G.push(CQ(Y,!1));return G}let Z=[],J=!1;for(let G of Q)if(G9(G)){let Y=G.tools.map((W)=>{if(W.deferred)J=!0;return CQ(W,!0)});Z.push({type:"namespace",name:G.name,description:G.description,tools:Y})}else{if(G.deferred)J=!0;Z.push(CQ(G,!0))}if(J)Z.push({type:"tool_search"});return Z}function CQ(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}class PQ{static models(){return[]}normalizeError(Q){return _(Q)}}var Y9=["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 eQ extends PQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=rQ(Q),this.config=$}static model(Q,$){return new eQ(Q,$)}static models(){return Y9}stream(Q){let $=aQ(Q,{model:this.model,capabilities:this.capabilities});return sQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return tQ(this.endpoint(),Q)}endpoint(){return nQ(DQ(this.config))}}class Q6 extends PQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=rQ(Q),this.config=$}static model(Q,$){return new Q6(Q,$)}static models(){return Y9}stream(Q){let $=aQ(Q,{model:this.deployment(),capabilities:this.capabilities});return sQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return tQ(this.endpoint(),Q)}deployment(){return this.config.deployment??this.model}endpoint(){return nQ(FQ(this.config))}}class c 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 s extends Error{runId;code="live_run_not_found";constructor(Q){super(`No live run ${Q} in this process.`);this.runId=Q}}class _Q{ttlMs;maxFrames;maxAgeMs;runs=new Map;byThread=new Map;byClientRun=new Map;constructor(Q={}){this.ttlMs=Q.ttlMs??60000,this.maxFrames=Q.maxFrames??4096,this.maxAgeMs=Q.maxAgeMs===void 0?3600000:Q.maxAgeMs}register(Q,$={}){let Z={run:Q,threadId:$.threadId,clientRunId:$.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evicted:!1,evictAt:null,expireAt: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.scheduleExpiry(Z,$.maxRunDurationMs),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 s(Q);if($!==void 0&&$<Z.lostBefore)throw new c(Q,$,Z.lostBefore);let J=Z.frames[0]?.seq;return this.drain(Z,Q,$??J??Z.lastSeq+1)}clear(){for(let Q of this.runs.values()){if(Q.evictAt)clearTimeout(Q.evictAt);if(Q.expireAt)clearTimeout(Q.expireAt);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 J of Q.run.frames()){if(Q.evicted){let Y=$.onEvent;if(Y)Z=Z.then(()=>Y(J.event)).catch((W)=>$6($,W));continue}if(Q.frames.push(J),Q.lastSeq=J.seq,Q.frames.length>this.maxFrames){let Y=Q.frames.shift();if(Y)Q.lostBefore=Y.seq+1}this.notify(Q);let G=$.onEvent;if(G)Z=Z.then(()=>G(J.event)).catch((Y)=>$6($,Y))}}catch(J){$6($,J)}finally{if(Q.ended=!0,Q.expireAt)clearTimeout(Q.expireAt),Q.expireAt=null;this.notify(Q),this.scheduleEviction(Q),await Z}}async*drain(Q,$,Z){let J=Z;while(!0){let G=Q.version;for(;;){if(J<Q.lostBefore)throw new c($,J,Q.lostBefore);let Y=Q.frames,W=Y[0]?.seq;if(W===void 0)break;let K=Math.max(0,J-W);if(K>=Y.length)break;let V=Y[K];yield V,J=V.seq+1}if(Q.ended&&J>Q.lastSeq||Q.evicted)return;await this.wait(Q,G)}}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(!Q.ended)Q.evicted=!0,Q.frames=[];if(this.runs.get(Z)===Q)this.runs.delete(Z);if(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=$}scheduleExpiry(Q,$){if(this.maxAgeMs===null||$===null)return;let Z=$===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,$+this.ttlMs);if(!Number.isFinite(Z)||Z>2147483647)return;let J=setTimeout(()=>{if(Q.expireAt=null,Q.ended)return;try{Q.run.stop({reason:`The run was still going ${Math.round(Z/1000)}s after it started, past the live-run registry's age limit.`})}catch{}this.scheduleEviction(Q)},Z);J.unref?.(),Q.expireAt=J}}var Z6=new _Q;function $6(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 J of $){let G=Z.messages.findIndex((Y)=>Y.id===J.id);if(G===-1)Z.messages.push(J);else Z.messages[G]=J}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 J6=new jQ;function K9(Q={}){return{messages:Q.messages?[...Q.messages]:[],pending:Q.pending?[...Q.pending]:[],error:null,threadId:Q.threadId,seq:Q.seq??-1,cursorRunId:Q.cursorRunId,runMessageIds:[],loadedTools:[]}}function H9(Q,$,Z=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==Q.cursorRunId)&&$.seq<=Q.seq)return Q;return{...B9(Q,$.event,Z),seq:$.seq}}function B9(Q,$,Z){switch($.type){case"run-start":return{...Q,runId:$.runId,cursorRunId:$.runId,threadId:$.threadId??Q.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0};case"message-start":return w(Q,$.messageId,Z,(J)=>({...J,role:$.role}));case"text-delta":if(X9(Q,$.messageId))return Q;return w(Q,$.messageId,Z,(J)=>({...J,content:f$(J.content,$.delta)}));case"reasoning-delta":if(X9(Q,$.messageId))return Q;return w(Q,$.messageId,Z,(J)=>({...J,content:v$(J.content,$.delta,$.id)}));case"output-delta":return w(Q,$.messageId,Z,(J)=>({...J,content:V9(J.content,{type:"output",value:$.snapshot,partial:!0},(G)=>G.type==="output")}));case"tool-call":return w(Q,$.messageId,Z,(J)=>{let G=J.content.findIndex((B)=>B.type==="tool-call"&&B.toolCallId===$.part.toolCallId),Y=G===-1?void 0:J.content[G],W=$.part.progress??Y?.progress,K=$.part.nested??Y?.nested,V=$.part.attachments??Y?.attachments,X={...$.part,...W?{progress:W}:{},...K?{nested:K}:{},...V?{attachments:V}:{}},H=J.content.slice();if(G===-1)H.push(X);else H[G]=X;return{...J,content:H}});case"tool-search":{let J=$.loaded.filter((G)=>!Q.loadedTools.includes(G));if(J.length===0)return Q;return{...Q,loadedTools:[...Q.loadedTools,...J]}}case"tool-progress":return W9(Q,$.toolCallId,(J)=>({...J,progress:[...J.progress??[],$.data]}));case"nested-event":{let J=$;return W9(Q,$.toolCallId,(G)=>{let Y=G.nested??[],W=Y.findIndex((H)=>H.runId===J.runId),K=Y[W]??{runId:J.runId,agent:J.agent,messages:[]},V=b$(K,J,Z),X=W===-1?[...Y,V]:Y.map((H,B)=>B===W?V:H);return{...G,nested:X}})}case"tool-result":{let J=w(Q,$.messageId,Z,(G)=>({...G,content:V9(G.content,$.part,(Y)=>Y.type==="tool-result"&&Y.toolCallId===$.part.toolCallId)}));return{...J,pending:J.pending.filter((G)=>G.toolCallId!==$.part.toolCallId)}}case"message":{let J=Q.messages.findIndex((W)=>W.id===$.message.id),G=Q.messages.slice();if(J===-1)G.push($.message);else G[J]=$.message;let Y=Q.runMessageIds.includes($.message.id)?Q.runMessageIds:[...Q.runMessageIds,$.message.id];return{...Q,messages:G,runMessageIds:Y}}case"awaiting-input":return{...Q,runId:$.runId,pending:[...$.pending]};case"message-end":return w(Q,$.messageId,Z,(J)=>({...J,finishReason:$.finishReason,...$.outputTruncated?{outputTruncated:!0}:{},content:$.outputTruncated||$.finishReason==="length"?J.content.filter((G)=>!(G.type==="output"&&G.partial)):J.content.map((G)=>G.type==="output"&&G.partial?{...G,partial:!1}:G)}));case"usage":{let J=w$(Q.messages,(Y)=>Y.role==="assistant");if(J===-1)return Q;let G=Q.messages.slice();return G[J]={...G[J],usage:$.usage},{...Q,messages:G}}case"error":return{...Q,error:$.error,pending:[]};case"run-end":return{...Q,runId:void 0,finishReason:$.finishReason,messages:z9(Q,$.finishReason)};default:return Q}}function z9(Q,$){return Q.messages.map((Z)=>Z.role==="assistant"&&Q.runMessageIds.includes(Z.id)?E$(Z,$):Z)}function E$(Q,$){let Z=Q.content.map((G)=>G.type==="tool-call"&&G.nested?.some((Y)=>Y.finishReason===void 0)?{...G,nested:G.nested.map((Y)=>Y.finishReason===void 0?x$(Y,$):Y)}:G);if(Q.finishReason===void 0)return{...Q,finishReason:$,content:Z};return Z.some((G,Y)=>G!==Q.content[Y])?{...Q,content:Z}:Q}function x$(Q,$){let Z={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((J)=>J.id),loadedTools:[]};return{...Q,finishReason:$,messages:z9(Z,$)}}function W9(Q,$,Z){for(let J=Q.messages.length-1;J>=0;J--){let G=Q.messages[J],Y=G.content.findIndex((X)=>X.type==="tool-call"&&X.toolCallId===$);if(Y===-1)continue;if(G.finishReason!==void 0&&!I$(Q,G,$))return Q;let W=G.content.slice();W[Y]=Z(W[Y]);let K=Q.messages.slice();K[J]={...G,content:W};let V=Q.runMessageIds.includes(G.id)?Q.runMessageIds:[...Q.runMessageIds,G.id];return{...Q,runMessageIds:V,messages:K}}return Q}function b$(Q,$,Z){let J={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((Y)=>Y.id),loadedTools:[],finishReason:Q.finishReason},G=B9(J,$.event,Z);return{...Q,...$.label!==void 0?{label:$.label}:{},messages:G.messages,...G.finishReason!==void 0?{finishReason:G.finishReason}:{},...$.event.type==="usage"?{usage:$.event.usage}:{}}}function I$(Q,$,Z){if($.finishReason!=="awaiting-input")return!1;return!Q.messages.some((J)=>J.content.some((G)=>G.type==="tool-result"&&G.toolCallId===Z))}function X9(Q,$){let Z=Q.messages.find((J)=>J.id===$);return Z!==void 0&&Z.finishReason!==void 0}function w$(Q,$){for(let Z=Q.length-1;Z>=0;Z--)if($(Q[Z]))return Z;return-1}function w(Q,$,Z,J){let G=Q.messages.findIndex((K)=>K.id===$),Y=Q.runMessageIds.includes($)?Q.runMessageIds:[...Q.runMessageIds,$];if(G===-1){let K={id:$,role:"assistant",content:[],createdAt:Z};return{...Q,runMessageIds:Y,messages:[...Q.messages,J(K)]}}let W=Q.messages.slice();return W[G]=J(W[G]),{...Q,runMessageIds:Y,messages:W}}function f$(Q,$){let Z=Q[Q.length-1];if(Z&&Z.type==="text")return[...Q.slice(0,-1),{type:"text",text:Z.text+$}];return[...Q,{type:"text",text:$}]}function v$(Q,$,Z){let J=Q[Q.length-1];if(J&&J.type==="reasoning"&&J.id===Z)return[...Q.slice(0,-1),{...J,text:(J.text??"")+$}];return[...Q,Z?{type:"reasoning",id:Z,text:$}:{type:"reasoning",text:$}]}function V9(Q,$,Z){let J=Q.findIndex(Z);if(J===-1)return[...Q,$];let G=Q.slice();return G[J]=$,G}class Y6{store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(Q,$,Z,J){this.store=Q;this.threadId=$;this.report=J;this.state=K9({messages:Z})}finish(Q){if(this.closed)return;this.done.add(Q.id),this.write(()=>[G6(Q)])}frame(Q){if(this.closed)return;let $=Q.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=H9(this.state,Q),$.type){case"message":this.write(()=>[G6($.message)]);return;case"tool-call":if($.part.partial)return;this.checkpoint($.messageId);return;case"message-start":case"tool-result":this.checkpoint($.messageId);return;default:return}}close(Q=[]){this.closed=!0;for(let $ of Q)this.done.add($.id)}settled(){return this.chain}checkpoint(Q){if(this.done.has(Q))return;let $=this.state.messages.find((J)=>J.id===Q);if(!$)return;let Z=this.runId;this.write(()=>{let J=G6($);if(J.finishReason===void 0&&Z)J.runId=Z;return[J]})}write(Q){let $;try{$=Q()}catch(Z){this.report(Z);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,$)).catch((Z)=>this.report(Z))}}function G6(Q){return structuredClone(Q)}async function U9(Q,$){let Z=[],J=null,G=Q.slice();for(let Y=0;Y<G.length;Y++){let W=G[Y];if(W.role!=="assistant"||W.finishReason!==void 0)continue;if(W.runId&&await $(W.runId))continue;J??=new Set(Q.flatMap((X)=>X.content.flatMap((H)=>H.type==="tool-result"?[H.toolCallId]:[])));let K=W.content.map((X)=>X.type==="tool-call"?D9(X):X);for(let X of W.content){if(X.type!=="tool-call"||J.has(X.toolCallId))continue;let H={type:"tool-result",toolCallId:X.toolCallId,name:X.name,status:"denied",cause:"interrupted"};K.push(H)}let V={...W,content:K,finishReason:"interrupted"};G[Y]=V,Z.push(V)}return{messages:G,settled:Z}}function D9(Q){let{partial:$,...Z}=Q;if(!Z.nested?.some((J)=>J.finishReason===void 0))return Z;return{...Z,nested:Z.nested.map(y$)}}function y$(Q){if(Q.finishReason!==void 0)return Q;return{...Q,finishReason:"interrupted",messages:Q.messages.map(($)=>$.role==="assistant"&&$.finishReason===void 0?{...$,finishReason:"interrupted",content:$.content.map((Z)=>Z.type==="tool-call"?D9(Z):Z)}:$)}}var h$=N9,MQ=new Map,F9=new WeakMap,qQ=new Map;class _9 extends h${static kind="agent-controller";store=J6;liveRuns=Z6;attachments=HQ;attachmentStorage=P9;hookHoldMs=30000;instructions(Q,$){}context(Q,$){return{}}requireThread=!1;authorizeRequest(Q,$){}async stream(Q=new t){let $=await W6(Q);if($.error)return SQ($);let Z=$.body,J=typeof Z.threadId==="string"?Z.threadId:void 0,G=m$(Z);if(G.error)return SQ({body:{},error:G.error});let Y=G.turn,W=typeof Z.clientRunId==="string"?Z.clientRunId:void 0,K=j9(Z);if(this.requireThread&&!J)return S(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)qQ.set(W,V);let X=async()=>{let H;if(J){let C=await this.store.loadThread(J);if(!C)return S(404,{code:"thread_not_found",message:`Thread ${J} does not exist here, or has expired.`});H=await this.settleThread(J,C,{write:!0})}else H=Array.isArray(Z.messages)?Z.messages:[];let B=await this.instructions(Q,{body:K})||void 0,z=await this.context(Q,{body:K}),D=await this.attachmentsFor(Q,J,{body:K});if(V?.cancelled)return O9();let F=J?new Y6(this.store,J,H,(C)=>this.reportHookFailure(C)):null,U=this.agent.stream({messages:H,turn:Y,threadId:J,...F?{onMessage:(C)=>F.finish(C)}:{},instructions:B,context:z,attachments:D,body:K}),L={req:Q,runId:U.runId,threadId:J},O=this.liveRuns.register(U,{threadId:J,clientRunId:W,onEvent:(C)=>this.dispatchEvent(C,L),onInternalError:(C)=>this.reportHookFailure(C),maxRunDurationMs:this.agent.maxRunDurationMs});if(F)this.follow(U,F);let{stored:f,hooks:R}=this.persistRun(U,L,O,F);return F9.set(U,f),Q.ctx?.()?.waitUntil(R),U.toResponse()};try{if(await this.authorizeRequest(Q,{route:"stream",threadId:J,body:K}),V?.cancelled)return O9();return J?await this.withThread(J,X):await X()}finally{if(V&&qQ.get(W)===V)qQ.delete(W)}}async withThread(Q,$){let Z=MQ.get(Q)??Promise.resolve(),J,G=new Promise((W)=>{J=W}),Y=Z.then(()=>G);MQ.set(Q,Y),await Z;try{let W=await this.liveRuns.find({threadId:Q}),K=W?this.liveRuns.get(W.runId):null;if(K)K.stop({reason:"superseded by a later turn on this thread"}),await F9.get(K);return await $()}finally{if(J(),MQ.get(Q)===Y)MQ.delete(Q)}}async attach(Q=new t){let $=await W6(Q);if($.error)return SQ($);let Z=$.body,J=typeof Z.threadId==="string"?Z.threadId:l$(Q,"threadId");if(!J)return S(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(Q,{route:"attach",threadId:J});let G=await this.liveRuns.find({threadId:J});if(!G)return S(404,{code:"no_live_run",message:`No run in progress for thread ${J} in this process.`});let Y=typeof Z.runId==="string"?Z.runId:void 0,W=Y&&Y!==G.runId?void 0:d$(Q,Z);try{return R6(this.liveRuns.replay(G.runId,W))}catch(K){if(K instanceof c)return S(410,{code:K.code,message:K.message,oldestSeq:K.oldest});if(K instanceof s)return S(404,{code:K.code,message:K.message});throw K}}async stop(Q=new t){let $=await W6(Q);if($.error)return SQ($);let Z=$.body;await this.authorizeRequest(Q,{route:"stop",threadId:typeof Z.threadId==="string"?Z.threadId:void 0});let J=typeof Z.runId==="string"?Z.runId:void 0;if(!J&&typeof Z.clientRunId==="string"){if(J=this.liveRuns.findByClientRunId(Z.clientRunId)??void 0,!J){let Y=qQ.get(Z.clientRunId);if(Y)return Y.cancelled=!0,{stopped:!0}}}if(!J&&typeof Z.threadId==="string")J=(await this.liveRuns.find({threadId:Z.threadId}))?.runId;let G=J?this.liveRuns.get(J):null;if(!G)return{stopped:!1};return G.stop({reason:typeof Z.reason==="string"?Z.reason:void 0}),{stopped:!0}}attachmentScope(Q,$,Z){let J=Q.ctx()?.user,G=J?.id??J?.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,$,Z={body:{}}){let J=await this.attachmentScope(Q,$,Z);if(!J)return null;return new i(this.attachments,this.attachmentStorage,J)}async upload(Q=new t){let $=await Q.rawRequest.formData(),Z=$.get("file");if(!(Z instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let J=Z instanceof File&&Z.name?Z.name:"upload",G=Z.type||"application/octet-stream",Y=g$($.get("body")),W=$.get("threadId");await this.authorizeRequest(Q,{route:"upload",threadId:typeof W==="string"&&W.length>0?W:void 0,body:Y});let K=typeof W==="string"&&W.length>0&&await this.store.loadThread(W)!==null?W:void 0,V=await this.attachmentDestination(Z,Q),X=i$(V,$.get("destination")),H=await this.attachmentScope(Q,K,{body:Y}),B=X!=="provider"&&!H;if(B){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()`.');o$()}if(X==="provider"||!H){let O={fileId:await this.agent.provider.upload(Z),name:J,mimeType:G,size:Z.size,destination:"provider"};if(B)O.downgraded="no_scope";return O}let z=EQ(),D=await this.attachmentStorage.put({name:xQ(z,J),body:Z,contentType:G}),F=X==="both"?await this.agent.provider.upload(Z):void 0,U={id:z,scopeKey:H.key,fileId:F,objectName:D,name:J,mimeType:G,size:Z.size,createdAt:new Date().toISOString(),destination:X};return await this.attachments.put(H,U),{fileId:F,attachmentId:z,name:J,mimeType:G,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}}async readThread(Q){let $=await this.store.loadThread(Q);return $?await this.settleThread(Q,$,{write:!1}):null}isRunLive(Q,$){return this.liveRuns.get(Q)!==null}async settleThread(Q,$,{write:Z}){let{messages:J,settled:G}=await U9($,(Y)=>this.isRunLive(Y,Q));if(Z&&G.length>0)try{await this.store.appendMessages(Q,G)}catch(Y){this.reportHookFailure(Y)}return J}follow(Q,$){(async()=>{try{for await(let Z of Q.frames())$.frame(Z)}catch(Z){this.reportHookFailure(Z)}})()}persistRun(Q,$,Z,J=null){let G=Promise.resolve(),Y=(async()=>{let K;try{K=await Q.result()}catch(X){J?.close(),await J?.settled(),G=this.safely(()=>this.onError({code:"unknown",message:X instanceof Error?X.message:String(X),retryable:!1},$));return}let V=K.messages;if(J?.close(V),await J?.settled(),$.threadId&&V.length>0)try{await this.store.appendMessages($.threadId,V)}catch(X){this.reportHookFailure(X)}G=this.notifyRun(K,V,$)})(),W=Y.then(()=>s$(Promise.all([G,Z]).then(()=>{}),this.hookHoldMs));return{stored:Y,hooks:W}}async notifyRun(Q,$,Z){for(let J of $)await this.safely(()=>this.onMessage(J,Z));await this.safely(()=>this.onStreamComplete(Q,Z))}async safely(Q){try{await Q()}catch($){this.reportHookFailure($)}}}var X6=["turn","clientRunId","threadId","messages"],u$=["text","files","toolResults"];function j9(Q,$=M9(Q)?X6:[...X6,...u$]){let Z={};for(let[J,G]of Object.entries(Q)){if($.includes(J))continue;Object.defineProperty(Z,J,{value:G,writable:!0,enumerable:!0,configurable:!0})}return Z}function g$(Q){if(Q===null)return{};let $;if(typeof Q==="string")try{$=JSON.parse(Q)}catch{throw new V6("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new V6("The upload's `body` field must be a JSON object.");return j9($,X6)}class V6 extends C9{constructor(Q){super(Q);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:Q}}},view:{}}}}async function W6(Q){let $=Q?.rawRequest;if(!$||$.method==="GET"||$.method==="HEAD"||!$.body)return{body:{}};if(!c$($.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 J;try{J=JSON.parse(Z)}catch{return{body:{},error:"The request body is not valid JSON."}}if(J===null||typeof J!=="object"||Array.isArray(J))return{body:{},error:"The request body must be a JSON object."};return{body:J}}function c$(Q){if(typeof Q!=="string")return!1;let[$]=Q.split(";",1);return $.trim().toLowerCase()==="application/json"}function SQ(Q){return S(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function M9(Q){return Boolean(Q.turn)&&typeof Q.turn==="object"}function m$(Q){let $=M9(Q)?Q.turn:Q,Z={};if(typeof $.text==="string")Z.text=$.text;if(Array.isArray($.files)){let J=p$($.files);if(typeof J==="string")return{error:J};Z.files=J}if(Array.isArray($.toolResults))Z.toolResults=$.toolResults;return Object.keys(Z).length>0?{turn:Z}:{}}function p$(Q){let $=[];for(let[Z,J]of Q.entries()){let G=`turn.files[${Z}]`;if(!J||typeof J!=="object"||Array.isArray(J))return`${G} must be an object.`;let Y={};for(let H of["fileId","attachmentId","name","mimeType"]){let B=J[H];if(B===void 0||B===null||B==="")continue;if(typeof B!=="string")return`${G}.${H} must be a string.`;Y[H]=B}let{fileId:W,attachmentId:K,name:V,mimeType:X}=Y;if(W?.startsWith(j))return`${G}.fileId holds a gemi attachment id (${W}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(K!==void 0&&!K.startsWith(j))return`${G}.attachmentId is not a gemi attachment id: it must start with "${j}".`;if(!W&&!K)return`${G} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...W?{fileId:W}:{},...K?{attachmentId:K}:{},...V!==void 0?{name:V}:{},...X!==void 0?{mimeType:X}:{}})}return $}function d$(Q,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let J=Math.floor($.cursor);if(J>=0)return J+1;return}let Z=Q?.rawRequest?.headers?.get("Last-Event-ID");if(Z){let J=Number.parseInt(Z,10);if(Number.isFinite(J))return Math.max(0,J+1)}return}function l$(Q,$){let Z=Q?.search?.get($);return typeof Z==="string"?Z:void 0}function O9(){return S(409,{code:"stopped",message:"The turn was stopped before it started."})}function S(Q,$){return new Response(JSON.stringify({error:$}),{status:Q,headers:{"Content-Type":"application/json"}})}function i$(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 L9=!1;function o$(){if(L9)return;L9=!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 n$=2147483647;function s$(Q,$){let Z=Q.then(()=>{},()=>{});if(!($<=n$))return Z;let J,G=new Promise((Y)=>{J=setTimeout(Y,$)});return Promise.race([Z,G]).finally(()=>clearTimeout(J))}export{e9 as toAgentTools,m as supportsStrict,t$ as s,Z6 as liveRuns,A9 as generate,HQ as defaultAttachmentStore,J6 as defaultAgentStore,UQ as ToolNamespace,hQ as Skill,i as ScopedAttachments,o as SKILLS_NAMESPACE,x as PendingEscalation,eQ as OpenAIProvider,dQ as OpenAIImageProvider,_Q as MemoryLiveRuns,KQ as MemoryAttachmentStore,jQ as MemoryAgentStore,s as LiveRunNotFoundError,u as InvalidAttachmentScopeError,OQ as ImageRequestError,LQ as ImageProvider,cQ as ImageModel,c as FrameCursorEvictedError,uQ as DEFAULT_MAX_RUN_DURATION_MS,Q6 as AzureOpenAIProvider,lQ as AzureOpenAIImageProvider,l as AttachmentNotFoundError,b as AgentTool,d as AgentRunError,PQ as AgentProvider,_9 as AgentController,gQ as Agent};
|
|
19
19
|
|
|
20
|
-
//# debugId=
|
|
20
|
+
//# debugId=B65134327F0FCC9764756E2164756E21
|