gemi 0.109.0 → 0.111.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 +11 -0
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/AgentController.d.ts +7 -0
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/index.js +11 -11
- package/dist/ai/index.js.map +4 -4
- package/dist/app/index.js +2 -2
- package/dist/app/index.js.map +1 -1
- package/dist/bin/gemi.js +485 -63
- package/dist/bin/gemi.js.map +12 -8
- package/dist/bun/plugin.js +2 -2
- package/dist/bun/plugin.js.map +1 -1
- package/dist/bun/preload.js +2 -2
- package/dist/bun/preload.js.map +1 -1
- package/dist/{chunk-hgz8sx40.js → chunk-09ypnhjv.js} +3 -3
- package/dist/{chunk-hgz8sx40.js.map → chunk-09ypnhjv.js.map} +1 -1
- package/dist/{chunk-qnq110tw.js → chunk-0d9qsmx2.js} +3 -3
- package/dist/{chunk-qnq110tw.js.map → chunk-0d9qsmx2.js.map} +1 -1
- package/dist/{chunk-m9609t1y.js → chunk-0sjh5v1n.js} +1 -1
- package/dist/{chunk-g5a3ptsa.js → chunk-11fsn5mr.js} +3 -3
- package/dist/{chunk-g5a3ptsa.js.map → chunk-11fsn5mr.js.map} +1 -1
- package/dist/chunk-1bkr5wnt.js +58 -0
- package/dist/chunk-1bkr5wnt.js.map +14 -0
- package/dist/{chunk-whe0x70j.js → chunk-1c1d0e60.js} +3 -3
- package/dist/{chunk-whe0x70j.js.map → chunk-1c1d0e60.js.map} +1 -1
- package/dist/{chunk-rgfzqwpg.js → chunk-1kr25rcg.js} +3 -3
- package/dist/{chunk-rgfzqwpg.js.map → chunk-1kr25rcg.js.map} +1 -1
- package/dist/{chunk-vee4j6ft.js → chunk-1pem26zc.js} +3 -3
- package/dist/{chunk-vee4j6ft.js.map → chunk-1pem26zc.js.map} +1 -1
- package/dist/{chunk-nxxx0m1a.js → chunk-1va15sfq.js} +2 -2
- package/dist/{chunk-nxxx0m1a.js.map → chunk-1va15sfq.js.map} +2 -2
- package/dist/{chunk-wvwee7dn.js → chunk-1yx2e0bh.js} +2 -2
- package/dist/{chunk-wvwee7dn.js.map → chunk-1yx2e0bh.js.map} +1 -1
- package/dist/{chunk-9r3znmqq.js → chunk-303mprnv.js} +2 -2
- package/dist/{chunk-9r3znmqq.js.map → chunk-303mprnv.js.map} +1 -1
- package/dist/{chunk-grs8dnkd.js → chunk-30xjcyzh.js} +2 -2
- package/dist/{chunk-grs8dnkd.js.map → chunk-30xjcyzh.js.map} +1 -1
- package/dist/{chunk-h15eae7g.js → chunk-358sdcx9.js} +3 -3
- package/dist/{chunk-h15eae7g.js.map → chunk-358sdcx9.js.map} +1 -1
- package/dist/{chunk-367kyrdx.js → chunk-3cg7y62b.js} +2 -2
- package/dist/{chunk-367kyrdx.js.map → chunk-3cg7y62b.js.map} +1 -1
- package/dist/{chunk-t26n9vzw.js → chunk-3y8q8x11.js} +2 -2
- package/dist/{chunk-t26n9vzw.js.map → chunk-3y8q8x11.js.map} +1 -1
- package/dist/chunk-4mfrgd5m.js +34 -0
- package/dist/chunk-4mfrgd5m.js.map +10 -0
- package/dist/chunk-5cygrbxv.js +4 -0
- package/dist/{chunk-9qw9fa6z.js.map → chunk-5cygrbxv.js.map} +2 -2
- package/dist/{chunk-tvy2fqza.js → chunk-5stgtwqw.js} +2 -2
- package/dist/{chunk-tvy2fqza.js.map → chunk-5stgtwqw.js.map} +1 -1
- package/dist/chunk-6chz1ktz.js +9 -0
- package/dist/chunk-6chz1ktz.js.map +13 -0
- package/dist/{chunk-wqsdjweb.js → chunk-6vr7f5fq.js} +4 -4
- package/dist/{chunk-wqsdjweb.js.map → chunk-6vr7f5fq.js.map} +1 -1
- package/dist/{chunk-g74qwhvf.js → chunk-7tx5y712.js} +2 -2
- package/dist/{chunk-g74qwhvf.js.map → chunk-7tx5y712.js.map} +1 -1
- package/dist/{chunk-g7fr2cy2.js → chunk-8afxrmdc.js} +3 -3
- package/dist/{chunk-g7fr2cy2.js.map → chunk-8afxrmdc.js.map} +1 -1
- package/dist/{chunk-vwkdfngg.js → chunk-8b2tw2yp.js} +1 -1
- package/dist/{chunk-t3qw9syt.js → chunk-9rchedr4.js} +2 -2
- package/dist/{chunk-t3qw9syt.js.map → chunk-9rchedr4.js.map} +1 -1
- package/dist/{chunk-jm4jn28j.js → chunk-9s851qz8.js} +2 -2
- package/dist/{chunk-jm4jn28j.js.map → chunk-9s851qz8.js.map} +1 -1
- package/dist/{chunk-jc4j61xb.js → chunk-a6453d9s.js} +3 -3
- package/dist/{chunk-jc4j61xb.js.map → chunk-a6453d9s.js.map} +1 -1
- package/dist/{chunk-9m18pknp.js → chunk-bn5yn731.js} +2 -2
- package/dist/{chunk-9m18pknp.js.map → chunk-bn5yn731.js.map} +1 -1
- package/dist/{chunk-t85rca2p.js → chunk-c098fzvk.js} +2 -2
- package/dist/{chunk-t85rca2p.js.map → chunk-c098fzvk.js.map} +1 -1
- package/dist/{chunk-mp5krm14.js → chunk-cttmy1jp.js} +4 -4
- package/dist/{chunk-mp5krm14.js.map → chunk-cttmy1jp.js.map} +2 -2
- package/dist/{chunk-eyg88bgv.js → chunk-cy5qp6mz.js} +3 -3
- package/dist/{chunk-eyg88bgv.js.map → chunk-cy5qp6mz.js.map} +1 -1
- package/dist/{chunk-zys7kecf.js → chunk-ddr4qvvt.js} +3 -3
- package/dist/{chunk-zys7kecf.js.map → chunk-ddr4qvvt.js.map} +1 -1
- package/dist/{chunk-r9gzbjc5.js → chunk-et4pv1b1.js} +1 -1
- package/dist/{chunk-a1g0bahx.js → chunk-frerzsxq.js} +2 -2
- package/dist/{chunk-a1g0bahx.js.map → chunk-frerzsxq.js.map} +1 -1
- package/dist/{chunk-qz9aaw5x.js → chunk-gb37722w.js} +3 -3
- package/dist/{chunk-qz9aaw5x.js.map → chunk-gb37722w.js.map} +1 -1
- package/dist/chunk-h3864a8z.js +17 -0
- package/dist/{chunk-s5aa4hty.js.map → chunk-h3864a8z.js.map} +13 -12
- package/dist/{chunk-zhm3qvrc.js → chunk-h4sw6nt3.js} +3 -3
- package/dist/{chunk-zhm3qvrc.js.map → chunk-h4sw6nt3.js.map} +1 -1
- package/dist/{chunk-5d6eaxab.js → chunk-he7z7y9j.js} +2 -2
- package/dist/{chunk-5d6eaxab.js.map → chunk-he7z7y9j.js.map} +1 -1
- package/dist/{chunk-d2tngs73.js → chunk-hf7a51s3.js} +2 -2
- package/dist/{chunk-d2tngs73.js.map → chunk-hf7a51s3.js.map} +1 -1
- package/dist/chunk-hn67spz6.js +5 -0
- package/dist/{chunk-z9x8x3wq.js.map → chunk-hn67spz6.js.map} +1 -1
- package/dist/{chunk-f7jhkg8x.js → chunk-jbrwt3cs.js} +4 -4
- package/dist/{chunk-f7jhkg8x.js.map → chunk-jbrwt3cs.js.map} +1 -1
- package/dist/{chunk-k1ezptt8.js → chunk-k1vw22t2.js} +2 -2
- package/dist/{chunk-k1ezptt8.js.map → chunk-k1vw22t2.js.map} +1 -1
- package/dist/chunk-k1xt2tw7.js +4 -0
- package/dist/{chunk-rjcsdazt.js.map → chunk-k1xt2tw7.js.map} +2 -2
- package/dist/{chunk-7mc5e61r.js → chunk-kf71mjxa.js} +3 -3
- package/dist/{chunk-7mc5e61r.js.map → chunk-kf71mjxa.js.map} +1 -1
- package/dist/{chunk-vna85rdq.js → chunk-m6ystvtk.js} +2 -2
- package/dist/{chunk-vna85rdq.js.map → chunk-m6ystvtk.js.map} +1 -1
- package/dist/{chunk-qyyxzy04.js → chunk-mb7q7s0a.js} +3 -3
- package/dist/{chunk-qyyxzy04.js.map → chunk-mb7q7s0a.js.map} +1 -1
- package/dist/{chunk-sp2v357a.js → chunk-mn5xw79b.js} +3 -3
- package/dist/{chunk-sp2v357a.js.map → chunk-mn5xw79b.js.map} +1 -1
- package/dist/{chunk-q8k7f11z.js → chunk-mwqg079k.js} +2 -2
- package/dist/{chunk-q8k7f11z.js.map → chunk-mwqg079k.js.map} +1 -1
- package/dist/{chunk-ga533cpz.js → chunk-nncz308h.js} +3 -3
- package/dist/{chunk-ga533cpz.js.map → chunk-nncz308h.js.map} +1 -1
- package/dist/{chunk-hf32yq23.js → chunk-nsvktvp4.js} +2 -2
- package/dist/{chunk-hf32yq23.js.map → chunk-nsvktvp4.js.map} +1 -1
- package/dist/{chunk-3x86bhfn.js → chunk-nvv9wej6.js} +3 -3
- package/dist/{chunk-3x86bhfn.js.map → chunk-nvv9wej6.js.map} +1 -1
- package/dist/chunk-p1aqq0ga.js +16 -0
- package/dist/{chunk-d5sbnzng.js.map → chunk-p1aqq0ga.js.map} +5 -9
- package/dist/chunk-p7r2w4qw.js +5 -0
- package/dist/{chunk-ehasw3qm.js.map → chunk-p7r2w4qw.js.map} +2 -2
- package/dist/{chunk-zz7h6tdr.js → chunk-pwmgqq7z.js} +2 -2
- package/dist/{chunk-zz7h6tdr.js.map → chunk-pwmgqq7z.js.map} +1 -1
- package/dist/chunk-pyj7cd9t.js +4 -0
- package/dist/{chunk-gdsby5jh.js.map → chunk-pyj7cd9t.js.map} +2 -2
- package/dist/{chunk-h6g9g8qc.js → chunk-q9s7kwgt.js} +3 -3
- package/dist/{chunk-h6g9g8qc.js.map → chunk-q9s7kwgt.js.map} +1 -1
- package/dist/{chunk-9hbwvcxn.js → chunk-qd2v93y4.js} +2 -2
- package/dist/{chunk-9hbwvcxn.js.map → chunk-qd2v93y4.js.map} +1 -1
- package/dist/{chunk-tr9mxdth.js → chunk-rfcygmf5.js} +3 -3
- package/dist/{chunk-tr9mxdth.js.map → chunk-rfcygmf5.js.map} +1 -1
- package/dist/{chunk-vsnmdtrs.js → chunk-s6jjy4y9.js} +2 -2
- package/dist/{chunk-vsnmdtrs.js.map → chunk-s6jjy4y9.js.map} +1 -1
- package/dist/{chunk-6zekebzt.js → chunk-sq2wkynk.js} +2 -2
- package/dist/{chunk-6zekebzt.js.map → chunk-sq2wkynk.js.map} +1 -1
- package/dist/{chunk-52vsdnny.js → chunk-td8tha3j.js} +3 -3
- package/dist/{chunk-52vsdnny.js.map → chunk-td8tha3j.js.map} +1 -1
- package/dist/chunk-tdsfke9q.js +6 -0
- package/dist/{chunk-fe1pcnw6.js.map → chunk-tdsfke9q.js.map} +5 -4
- package/dist/{chunk-t0bp8nrc.js → chunk-tk5q8hkv.js} +4 -4
- package/dist/{chunk-t0bp8nrc.js.map → chunk-tk5q8hkv.js.map} +2 -2
- package/dist/{chunk-dpy08xw4.js → chunk-tq85n8zh.js} +2 -2
- package/dist/{chunk-dpy08xw4.js.map → chunk-tq85n8zh.js.map} +1 -1
- package/dist/{chunk-wdpdqjr1.js → chunk-twnn7r66.js} +2 -2
- package/dist/{chunk-wdpdqjr1.js.map → chunk-twnn7r66.js.map} +1 -1
- package/dist/chunk-w7jsh3xd.js +5 -0
- package/dist/{chunk-1es50p4k.js.map → chunk-w7jsh3xd.js.map} +2 -2
- package/dist/chunk-wqvvjd5r.js +24 -0
- package/dist/{chunk-w3j53r0a.js.map → chunk-wqvvjd5r.js.map} +4 -4
- package/dist/{chunk-zh1t33nq.js → chunk-wsttx9rg.js} +2 -2
- package/dist/{chunk-zh1t33nq.js.map → chunk-wsttx9rg.js.map} +1 -1
- package/dist/{chunk-7ssjzp87.js → chunk-wvsv1jgg.js} +2 -2
- package/dist/{chunk-7ssjzp87.js.map → chunk-wvsv1jgg.js.map} +1 -1
- package/dist/chunk-x78jrs4y.js +4 -0
- package/dist/{chunk-y66ntxbg.js.map → chunk-x78jrs4y.js.map} +2 -2
- package/dist/chunk-xk930yaw.js +5 -0
- package/dist/{chunk-pa3khk46.js.map → chunk-xk930yaw.js.map} +2 -2
- package/dist/chunk-xkc7ftnq.js +9 -0
- package/dist/chunk-xkc7ftnq.js.map +10 -0
- package/dist/{chunk-564zfdd1.js → chunk-yer1r3t3.js} +2 -2
- package/dist/{chunk-564zfdd1.js.map → chunk-yer1r3t3.js.map} +1 -1
- package/dist/{chunk-c8dhvdrs.js → chunk-yqavgpwd.js} +3 -3
- package/dist/{chunk-c8dhvdrs.js.map → chunk-yqavgpwd.js.map} +1 -1
- package/dist/{chunk-hyfzw1fk.js → chunk-z10cas5r.js} +2 -2
- package/dist/{chunk-hyfzw1fk.js.map → chunk-z10cas5r.js.map} +1 -1
- package/dist/{chunk-jgtean4t.js → chunk-zhs1r1z0.js} +3 -3
- package/dist/{chunk-jgtean4t.js.map → chunk-zhs1r1z0.js.map} +1 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +106 -52
- package/dist/client/index.js.map +1 -1
- package/dist/client/islands.d.ts +99 -56
- package/dist/client/islands.d.ts.map +1 -1
- package/dist/config/index.d.ts +8 -1
- package/dist/config/index.d.ts.map +1 -1
- package/dist/config/index.js +1 -1
- package/dist/config/index.js.map +2 -2
- 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/Lang.d.ts +7 -1
- package/dist/facades/Lang.d.ts.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/CorsMiddleware.d.ts +13 -0
- package/dist/http/CorsMiddleware.d.ts.map +1 -1
- package/dist/http/Middleware.d.ts +11 -0
- package/dist/http/Middleware.d.ts.map +1 -1
- package/dist/http/ViewRouter.d.ts +29 -0
- package/dist/http/ViewRouter.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/islandRuntime.d.ts +45 -0
- package/dist/internal/islandRuntime.d.ts.map +1 -0
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/context.d.ts +24 -0
- package/dist/orm/context.d.ts.map +1 -1
- package/dist/orm/index.d.ts +1 -1
- package/dist/orm/index.d.ts.map +1 -1
- package/dist/orm/index.js +3 -3
- package/dist/orm/index.js.map +2 -2
- package/dist/server/devFetch.d.ts.map +1 -1
- package/dist/server/httpDev.d.ts.map +1 -1
- package/dist/server/httpProd.d.ts.map +1 -1
- package/dist/server/idleTimeout.d.ts +24 -0
- package/dist/server/idleTimeout.d.ts.map +1 -0
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/server/modulePreloads.d.ts +7 -6
- package/dist/server/modulePreloads.d.ts.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/middleware/MiddlewareRegistry.d.ts +13 -2
- package/dist/services/middleware/MiddlewareRegistry.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/DomainRouter.d.ts +10 -0
- package/dist/services/router/DomainRouter.d.ts.map +1 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts +3 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
- package/dist/services/router/staticCache.d.ts +23 -0
- package/dist/services/router/staticCache.d.ts.map +1 -0
- package/dist/services/router/staticDocument.d.ts +39 -17
- package/dist/services/router/staticDocument.d.ts.map +1 -1
- package/dist/stats/bundleStats.d.ts +104 -0
- package/dist/stats/bundleStats.d.ts.map +1 -0
- package/dist/stats/route-table.d.ts +2 -0
- package/dist/stats/route-table.d.ts.map +1 -0
- package/dist/stats/route-table.js +4 -0
- package/dist/stats/route-table.js.map +11 -0
- package/dist/stats/routeTable.d.ts +25 -0
- package/dist/stats/routeTable.d.ts.map +1 -0
- package/dist/stats/run.d.ts +43 -0
- package/dist/stats/run.d.ts.map +1 -0
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vite/index.mjs +125 -23
- package/dist/vitest/index.d.ts +18 -0
- package/dist/vitest/index.d.ts.map +1 -1
- package/dist/vitest/index.js +2 -2
- package/dist/vitest/index.js.map +3 -3
- package/package.json +2 -1
- package/dist/chunk-1es50p4k.js +0 -5
- package/dist/chunk-9qw9fa6z.js +0 -4
- package/dist/chunk-d5sbnzng.js +0 -18
- package/dist/chunk-ehasw3qm.js +0 -5
- package/dist/chunk-fe1pcnw6.js +0 -6
- package/dist/chunk-fj6yftm7.js +0 -58
- package/dist/chunk-fj6yftm7.js.map +0 -14
- package/dist/chunk-gdsby5jh.js +0 -4
- package/dist/chunk-ngw4xzrt.js +0 -9
- package/dist/chunk-ngw4xzrt.js.map +0 -10
- package/dist/chunk-pa3khk46.js +0 -5
- package/dist/chunk-rjcsdazt.js +0 -4
- package/dist/chunk-s5aa4hty.js +0 -17
- package/dist/chunk-w3j53r0a.js +0 -24
- package/dist/chunk-y66ntxbg.js +0 -4
- package/dist/chunk-z9x8x3wq.js +0 -5
- /package/dist/{chunk-m9609t1y.js.map → chunk-0sjh5v1n.js.map} +0 -0
- /package/dist/{chunk-vwkdfngg.js.map → chunk-8b2tw2yp.js.map} +0 -0
- /package/dist/{chunk-r9gzbjc5.js.map → chunk-et4pv1b1.js.map} +0 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Bb as T,Cb as a9,Db as I$,Eb as v$,Fb as b3}from"../chunk-t26n9vzw.js";import{Nf as x3,Pf as ZQ,Qf as l,ef as A3,hf as E3,wf as l1,xf as i1,yf as QQ,zf as zQ}from"../chunk-sp2v357a.js";import{Rf as k3,Tf as mQ,Uf as pQ}from"../chunk-zz7h6tdr.js";import{Yf as AQ}from"../chunk-6zekebzt.js";import{ch as PQ}from"../chunk-h6g9g8qc.js";import"../chunk-367kyrdx.js";import"../chunk-vna85rdq.js";import"../chunk-wvwee7dn.js";class h extends Error{status;body;requestId;constructor(Q,$,Z){super(`Provider request failed with status ${Q}: ${u3($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=Z}}class UQ extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function u3(Q){let $=e9(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function e9(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 W=J.innererror?.code??J.code;return{message:J.message,type:J.type,code:W,param:J.param}}function x(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 A(Q){if(Q instanceof UQ)return{code:"provider_error",message:Q.message,retryable:!0};if(d3(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof h)return c3(Q.status,e9(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 c3(Q,$,Z){let J=$?.message??Z,W=($?.code??"").toLowerCase(),G=($?.type??"").toLowerCase(),X=`${W} ${G} ${J}`.toLowerCase();if(Q===429){let Y=W==="insufficient_quota"||X.includes("quota");return{code:"rate_limited",message:J,retryable:!Y}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:J,retryable:!0};if(m3(X))return{code:"context_length_exceeded",message:J,retryable:!1};if(p3(X))return{code:"content_filtered",message:J,retryable:!1};if($?.param?.startsWith("tools")||X.includes("invalid schema for function"))return{code:"invalid_tool_input",message:J,retryable:!1};return{code:"provider_error",message:J,retryable:!1}}function m3(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function p3(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function d3(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}class k extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function y(Q,$){if($.aborted)return Promise.reject(new k);return new Promise((Z,J)=>{let W=()=>J(new k);$.addEventListener("abort",W,{once:!0}),Q.then(Z,J).finally(()=>$.removeEventListener("abort",W))})}function M(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function R(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 DQ(Q){if(!Q.trim())return{};try{return JSON.parse(Q)}catch{}let $=[],Z=!1,J=!1;for(let X of Q){if(Z){if(J)J=!1;else if(X==="\\")J=!0;else if(X==='"')Z=!1;continue}if(X==='"')Z=!0;else if(X==="{")$.push("}");else if(X==="[")$.push("]");else if(X==="}"||X==="]")$.pop()}let W=Q;if(Z)W+='"';W=W.replace(/[,:]\s*$/,"");let G=$.reverse().join("");try{return JSON.parse(W+G)}catch{try{return JSON.parse(W.replace(/,?\s*"[^"]*"\s*$/,"")+G)}catch{return{}}}}function FQ(Q){return{name:"output",schema:Q.toJSONSchema(),strict:QQ(Q)}}function jQ(Q,$){let Z=Q.safeParse(DQ($));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 LQ(Q){if(Q.length>0)Q[0];return Q}function $Q(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 CQ(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 l3(Q){return dQ(Q)}async function dQ(Q,$={}){let Z=`gen_${crypto.randomUUID()}`,J=await o3(Q);if($.settled?.(J),!J.ok){if(Q.logErrors!==!1&&J.error.code!=="aborted")i3(Z,J.error,$.origin);if(Q.throwOnError)throw new JQ({runId:Z,messages:J.messages,finishReason:J.finishReason,usage:J.usage,error:J.error})}return J}function i3(Q,$,Z){let J=`[gemi/ai] generate() failed (${$.code}${$.status!==void 0?` ${$.status}`:""}): ${$.message}`,W={...Z,generateId:Q,error:$},G=!1;try{ZQ.error(J,W),G=!0}catch{}if(!G||Bun.env.NODE_ENV==="development")console.error(J,W)}async function o3(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()},W=Q.signal??new AbortController().signal,G=M(),X="stop",Y,H={},V="";try{let U=Q.provider.stream({messages:[...Z],systemPrompt:Q.instructions?.trim()?Q.instructions:void 0,output:FQ(Q.output),reasoning:Q.reasoning,maxOutputTokens:Q.maxOutputTokens,temperature:Q.temperature,signal:Q.signal})[Symbol.asyncIterator]();try{for(;;){let F=await y(Promise.resolve(U.next()),W);if(F.done)break;let D=F.value;switch(D.type){case"output-delta":V+=D.delta;break;case"text-delta":$Q(J,"text",D.delta);break;case"reasoning-delta":CQ(J,D.id,D.delta);break;case"finish":if(G=R(G,D.usage),!Y)X=D.reason;break;case"error":X="error",Y=D.error,H=x(D);break}}}finally{if(W.aborted)Promise.resolve(U.return?.()).catch(()=>{})}}catch(B){if(B instanceof k||W.aborted)X="aborted",Y=n3(W);else X="error",Y=Q.provider.normalizeError(B),H=x(B)}let K=!1,z;if(!Y)if(X==="length")Y={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(!V.trim())Y={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let B=jQ(Q.output,V);if(B.ok===!0)K=!0,z=B.value;else Y=B.error}if(K)J.content.push({type:"output",value:z});else if(V)$Q(J,"text",V);for(let B of J.content)if((B.type==="text"||B.type==="reasoning")&&typeof B.text==="string")B.text=LQ(B.text);if(J.finishReason=X,J.usage=G,Z.push(J),K)return{ok:!0,output:z,messages:Z,usage:G,finishReason:X};return{ok:!1,error:{...Y,...H},messages:Z,usage:G,finishReason:X}}function n3(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 s3,hkdfSync as t3,randomBytes as Q$,timingSafeEqual as a3}from"crypto";class WQ{spent=new Map;sweepAt=1024;async consume(Q,$){return this.consumeSync(Q,$)}consumeSync(Q,$,Z=Date.now()){if(this.spent.size>=this.sweepAt)this.sweep(Z);let J=this.spent.get(Q);if(J!==void 0&&J>Z)return!1;return this.spent.set(Q,$),!0}get size(){return this.spent.size}sweep(Q){for(let[$,Z]of this.spent)if(Z<=Q)this.spent.delete($);this.sweepAt=Math.max(1024,this.spent.size*2)}}class lQ{injectedClient;prefix;constructor(Q={}){this.injectedClient=Q.client,this.prefix=Q.prefix??"gemi:ai:nonce"}async consume(Q,$){let Z=Math.max(1,Math.ceil($-Date.now()));return await this.client.send("SET",[`${this.prefix}:${Q}`,"1","PX",String(Z),"NX"])==="OK"}get client(){if(this.injectedClient)return this.injectedClient;let Q=PQ(),$=Q.bound(l)?Q.make(l).client:void 0;if(!$)throw Error("RedisNonceStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisNonceStore({ client }).");return $}}var i=new WQ;var iQ="agt2",OQ="agt1",$$=[iQ,OQ],oQ=86400000,r3=Date.now()+oQ;function Z$(Q){return Q<=r3}var J$="gemi.ai.pending-call.v1",W$="gemi.ai.nested-run.v1",e3="gemi.ai.execution-receipt.v1",QZ="gemi.ai.signing",qQ=new Map;function GQ(Q,$){let Z=nQ($),J=`${Q}\x00${Z}`,W=qQ.get(J);if(!W){if(W=Buffer.from(t3("sha256",Z,QZ,Q,32)),qQ.size>64)qQ.clear();qQ.set(J,W)}return W}function nQ(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 I(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(I).join(",")}]`;let $=Q;return`{${Object.keys($).filter((J)=>$[J]!==void 0).sort().map((J)=>`${JSON.stringify(J)}:${I($[J])}`).join(",")}}`}function $Z(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function g(Q,$){return s3("sha256",Q).update($Z($)).digest()}function G$(Q,$){let Z=Buffer.from(Q.split(".")[4],"base64url");return Z.length===$.length&&a3(Z,$)}function sQ(Q){return I(Q??null)}function X$(Q,$,Z){return[iQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),I(Q.input),I(Q.path??[]),sQ(Q.subject)]}function ZZ(Q,$,Z){let J=[OQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),I(Q.input)];if(Q.path&&Q.path.length>0)J.push(I(Q.path));return J}var V$=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),JZ=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function Y$(Q,$={}){let Z=GQ(J$,$.secret),W=($.now??Date.now())+($.ttlMs??oQ),G=Q$(12).toString("base64url"),X=g(Z,X$(Q,G,W)).toString("base64url");return[iQ,V$(Q.runId),G,W.toString(36),X].join(".")}function tQ(Q){return _Q(Q,$$)}function _Q(Q,$){let Z=Q.split(".");if(Z.length!==5||!$.includes(Z[0]))return null;let J=Number.parseInt(Z[3],36);if(!Number.isFinite(J))return null;try{return{runId:JZ(Z[1]),nonce:Z[2],expiresAt:J,version:Z[0]}}catch{return null}}function H$(Q,$,Z={}){let J=_Q(Q,$$);if(!J)return{ok:!1,reason:"malformed"};if(J.version===OQ&&!Z$(J.expiresAt))return{ok:!1,reason:"forged"};let W=J.version===OQ?g(nQ(Z.secret),ZZ($,J.nonce,J.expiresAt)):g(GQ(J$,Z.secret),X$($,J.nonce,J.expiresAt));if(!G$(Q,W))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 aQ="agn2",NQ="agn1",K$=[aQ,NQ];function B$(Q,$,Z){return[...z$(Q,$,Z,aQ),sQ(Q.subject)]}function z$(Q,$,Z,J=NQ){return[J,Q.runId,I(Q.path),Q.nestedRunId,$,String(Z),I([...Q.open].sort()),I(Q.input)]}function U$(Q,$={}){let Z=GQ(W$,$.secret),W=($.now??Date.now())+($.ttlMs??oQ),G=Q$(12).toString("base64url"),X=g(Z,B$(Q,G,W)).toString("base64url");return[aQ,V$(Q.runId),G,W.toString(36),X].join(".")}function D$(Q,$,Z={}){let J=_Q(Q,K$);if(!J)return{ok:!1,reason:"malformed"};if(J.version===NQ&&!Z$(J.expiresAt))return{ok:!1,reason:"forged"};let W={...$,runId:J.runId},G=J.version===NQ?g(nQ(Z.secret),z$(W,J.nonce,J.expiresAt)):g(GQ(W$,Z.secret),B$(W,J.nonce,J.expiresAt));if(!G$(Q,G))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}}function F$(Q,$,Z={}){let J=GQ(e3,Z.secret);return g(J,[Q,$.runId,$.toolCallId,$.name,$.kind,I($.input),I($.path??[]),sQ($.subject)]).toString("base64url")}function j$(Q,$){return C$($,tQ(Q))}function L$(Q,$){return C$($,_Q(Q,K$))}async function C$(Q,$){if(!$)return!1;return Q.consume($.nonce,$.expiresAt)}class XQ extends T{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class o extends T{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function rQ(Q){if(!Q||typeof Q.key!=="string"||Q.key.length===0)throw new o("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 f="gemi_att_";function eQ(){return`${f}${crypto.randomUUID()}`}class VQ{store;storage;scope;constructor(Q,$,Z){this.store=Q;this.storage=$;this.scope=Z;rQ(Z)}async get(Q){let $=await this.store.find(this.scope,Q);if(!$||$.scopeKey!==this.scope.key)throw new XQ(Q);return $}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,$){if(!$.objectName)throw new XQ(Q);return await this.storage.read({name:$.objectName})}async file(Q){let $=await this.get(Q),J=(await this.readRecord(Q,$)).body,W=J instanceof Blob?J:J?await new Response(J).blob():new Blob([]);return new File([W],$.name,{type:$.mimeType})}async put(Q,$={}){let Z=eQ(),J=$.mimeType??Q.type??"",W=$.name??(Q instanceof File?Q.name:Z),G=await this.storage.put({name:Q9(Z,W),body:Q,contentType:J||void 0}),X={id:Z,scopeKey:this.scope.key,objectName:G,name:W,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,X),X}}function Q9(Q,$){let Z=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Q}${Z?`.${Z[1].toLowerCase()}`:""}`}class MQ{rows=new Map;async put(Q,$){rQ(Q),this.rows.set($.id,{...$,scopeKey:Q.key})}async find(Q,$){rQ(Q);let Z=this.rows.get($);if(!Z||Z.scopeKey!==Q.key)return null;return Z}get size(){return this.rows.size}}var SQ=new MQ;var $9=new TextEncoder;function P$(Q){return`id: ${Q.seq}
|
|
2
|
+
import{Jb as A,Kb as r9,Lb as v$,Mb as f$,Nb as w3}from"../chunk-3y8q8x11.js";import{Ef as i1,Ff as o1,Gf as $Q,Hf as UQ,Vf as b3,Xf as JQ,Yf as i,mf as k3,pf as x3}from"../chunk-mn5xw79b.js";import{$f as pQ,Zf as E3,ag as dQ}from"../chunk-pwmgqq7z.js";import{eg as kQ}from"../chunk-sq2wkynk.js";import{lh as qQ}from"../chunk-q9s7kwgt.js";import"../chunk-3cg7y62b.js";import"../chunk-m6ystvtk.js";import"../chunk-1yx2e0bh.js";class y extends Error{status;body;requestId;constructor(Q,$,Z){super(`Provider request failed with status ${Q}: ${c3($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=Z}}class DQ extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function c3(Q){let $=Q$(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function Q$(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 W=J.innererror?.code??J.code;return{message:J.message,type:J.type,code:W,param:J.param}}function b(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 E(Q){if(Q instanceof DQ)return{code:"provider_error",message:Q.message,retryable:!0};if(l3(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof y)return m3(Q.status,Q$(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 m3(Q,$,Z){let J=$?.message??Z,W=($?.code??"").toLowerCase(),G=($?.type??"").toLowerCase(),X=`${W} ${G} ${J}`.toLowerCase();if(Q===429){let Y=W==="insufficient_quota"||X.includes("quota");return{code:"rate_limited",message:J,retryable:!Y}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:J,retryable:!0};if(p3(X))return{code:"context_length_exceeded",message:J,retryable:!1};if(d3(X))return{code:"content_filtered",message:J,retryable:!1};if($?.param?.startsWith("tools")||X.includes("invalid schema for function"))return{code:"invalid_tool_input",message:J,retryable:!1};return{code:"provider_error",message:J,retryable:!1}}function p3(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function d3(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function l3(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}class x extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function g(Q,$){if($.aborted)return Promise.reject(new x);return new Promise((Z,J)=>{let W=()=>J(new x);$.addEventListener("abort",W,{once:!0}),Q.then(Z,J).finally(()=>$.removeEventListener("abort",W))})}function M(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function T(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 FQ(Q){if(!Q.trim())return{};try{return JSON.parse(Q)}catch{}let $=[],Z=!1,J=!1;for(let X of Q){if(Z){if(J)J=!1;else if(X==="\\")J=!0;else if(X==='"')Z=!1;continue}if(X==='"')Z=!0;else if(X==="{")$.push("}");else if(X==="[")$.push("]");else if(X==="}"||X==="]")$.pop()}let W=Q;if(Z)W+='"';W=W.replace(/[,:]\s*$/,"");let G=$.reverse().join("");try{return JSON.parse(W+G)}catch{try{return JSON.parse(W.replace(/,?\s*"[^"]*"\s*$/,"")+G)}catch{return{}}}}function jQ(Q){return{name:"output",schema:Q.toJSONSchema(),strict:$Q(Q)}}function LQ(Q,$){let Z=Q.safeParse(FQ($));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 CQ(Q){if(Q.length>0)Q[0];return Q}function ZQ(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 PQ(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 i3(Q){return lQ(Q)}async function lQ(Q,$={}){let Z=`gen_${crypto.randomUUID()}`,J=await n3(Q);if($.settled?.(J),!J.ok){if(Q.logErrors!==!1&&J.error.code!=="aborted")o3(Z,J.error,$.origin);if(Q.throwOnError)throw new WQ({runId:Z,messages:J.messages,finishReason:J.finishReason,usage:J.usage,error:J.error})}return J}function o3(Q,$,Z){let J=`[gemi/ai] generate() failed (${$.code}${$.status!==void 0?` ${$.status}`:""}): ${$.message}`,W={...Z,generateId:Q,error:$},G=!1;try{JQ.error(J,W),G=!0}catch{}if(!G||Bun.env.NODE_ENV==="development")console.error(J,W)}async function n3(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()},W=Q.signal??new AbortController().signal,G=M(),X="stop",Y,H={},V="";try{let U=Q.provider.stream({messages:[...Z],systemPrompt:Q.instructions?.trim()?Q.instructions:void 0,output:jQ(Q.output),reasoning:Q.reasoning,maxOutputTokens:Q.maxOutputTokens,temperature:Q.temperature,signal:Q.signal})[Symbol.asyncIterator]();try{for(;;){let F=await g(Promise.resolve(U.next()),W);if(F.done)break;let D=F.value;switch(D.type){case"output-delta":V+=D.delta;break;case"text-delta":ZQ(J,"text",D.delta);break;case"reasoning-delta":PQ(J,D.id,D.delta);break;case"finish":if(G=T(G,D.usage),!Y)X=D.reason;break;case"error":X="error",Y=D.error,H=b(D);break}}}finally{if(W.aborted)Promise.resolve(U.return?.()).catch(()=>{})}}catch(B){if(B instanceof x||W.aborted)X="aborted",Y=s3(W);else X="error",Y=Q.provider.normalizeError(B),H=b(B)}let K=!1,z;if(!Y)if(X==="length")Y={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(!V.trim())Y={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let B=LQ(Q.output,V);if(B.ok===!0)K=!0,z=B.value;else Y=B.error}if(K)J.content.push({type:"output",value:z});else if(V)ZQ(J,"text",V);for(let B of J.content)if((B.type==="text"||B.type==="reasoning")&&typeof B.text==="string")B.text=CQ(B.text);if(J.finishReason=X,J.usage=G,Z.push(J),K)return{ok:!0,output:z,messages:Z,usage:G,finishReason:X};return{ok:!1,error:{...Y,...H},messages:Z,usage:G,finishReason:X}}function s3(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 t3,hkdfSync as a3,randomBytes as $$,timingSafeEqual as r3}from"crypto";class GQ{spent=new Map;sweepAt=1024;async consume(Q,$){return this.consumeSync(Q,$)}consumeSync(Q,$,Z=Date.now()){if(this.spent.size>=this.sweepAt)this.sweep(Z);let J=this.spent.get(Q);if(J!==void 0&&J>Z)return!1;return this.spent.set(Q,$),!0}get size(){return this.spent.size}sweep(Q){for(let[$,Z]of this.spent)if(Z<=Q)this.spent.delete($);this.sweepAt=Math.max(1024,this.spent.size*2)}}class iQ{injectedClient;prefix;constructor(Q={}){this.injectedClient=Q.client,this.prefix=Q.prefix??"gemi:ai:nonce"}async consume(Q,$){let Z=Math.max(1,Math.ceil($-Date.now()));return await this.client.send("SET",[`${this.prefix}:${Q}`,"1","PX",String(Z),"NX"])==="OK"}get client(){if(this.injectedClient)return this.injectedClient;let Q=qQ(),$=Q.bound(i)?Q.make(i).client:void 0;if(!$)throw Error("RedisNonceStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisNonceStore({ client }).");return $}}var o=new GQ;var oQ="agt2",NQ="agt1",Z$=[oQ,NQ],nQ=86400000,e3=Date.now()+nQ;function J$(Q){return Q<=e3}var W$="gemi.ai.pending-call.v1",G$="gemi.ai.nested-run.v1",QZ="gemi.ai.execution-receipt.v1",$Z="gemi.ai.signing",OQ=new Map;function XQ(Q,$){let Z=sQ($),J=`${Q}\x00${Z}`,W=OQ.get(J);if(!W){if(W=Buffer.from(a3("sha256",Z,$Z,Q,32)),OQ.size>64)OQ.clear();OQ.set(J,W)}return W}function sQ(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 I(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(I).join(",")}]`;let $=Q;return`{${Object.keys($).filter((J)=>$[J]!==void 0).sort().map((J)=>`${JSON.stringify(J)}:${I($[J])}`).join(",")}}`}function ZZ(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function u(Q,$){return t3("sha256",Q).update(ZZ($)).digest()}function X$(Q,$){let Z=Buffer.from(Q.split(".")[4],"base64url");return Z.length===$.length&&r3(Z,$)}function tQ(Q){return I(Q??null)}function V$(Q,$,Z){return[oQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),I(Q.input),I(Q.path??[]),tQ(Q.subject)]}function JZ(Q,$,Z){let J=[NQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),I(Q.input)];if(Q.path&&Q.path.length>0)J.push(I(Q.path));return J}var Y$=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),WZ=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function H$(Q,$={}){let Z=XQ(W$,$.secret),W=($.now??Date.now())+($.ttlMs??nQ),G=$$(12).toString("base64url"),X=u(Z,V$(Q,G,W)).toString("base64url");return[oQ,Y$(Q.runId),G,W.toString(36),X].join(".")}function aQ(Q){return MQ(Q,Z$)}function MQ(Q,$){let Z=Q.split(".");if(Z.length!==5||!$.includes(Z[0]))return null;let J=Number.parseInt(Z[3],36);if(!Number.isFinite(J))return null;try{return{runId:WZ(Z[1]),nonce:Z[2],expiresAt:J,version:Z[0]}}catch{return null}}function K$(Q,$,Z={}){let J=MQ(Q,Z$);if(!J)return{ok:!1,reason:"malformed"};if(J.version===NQ&&!J$(J.expiresAt))return{ok:!1,reason:"forged"};let W=J.version===NQ?u(sQ(Z.secret),JZ($,J.nonce,J.expiresAt)):u(XQ(W$,Z.secret),V$($,J.nonce,J.expiresAt));if(!X$(Q,W))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 rQ="agn2",_Q="agn1",B$=[rQ,_Q];function z$(Q,$,Z){return[...U$(Q,$,Z,rQ),tQ(Q.subject)]}function U$(Q,$,Z,J=_Q){return[J,Q.runId,I(Q.path),Q.nestedRunId,$,String(Z),I([...Q.open].sort()),I(Q.input)]}function D$(Q,$={}){let Z=XQ(G$,$.secret),W=($.now??Date.now())+($.ttlMs??nQ),G=$$(12).toString("base64url"),X=u(Z,z$(Q,G,W)).toString("base64url");return[rQ,Y$(Q.runId),G,W.toString(36),X].join(".")}function F$(Q,$,Z={}){let J=MQ(Q,B$);if(!J)return{ok:!1,reason:"malformed"};if(J.version===_Q&&!J$(J.expiresAt))return{ok:!1,reason:"forged"};let W={...$,runId:J.runId},G=J.version===_Q?u(sQ(Z.secret),U$(W,J.nonce,J.expiresAt)):u(XQ(G$,Z.secret),z$(W,J.nonce,J.expiresAt));if(!X$(Q,G))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}}function j$(Q,$,Z={}){let J=XQ(QZ,Z.secret);return u(J,[Q,$.runId,$.toolCallId,$.name,$.kind,I($.input),I($.path??[]),tQ($.subject)]).toString("base64url")}function L$(Q,$){return P$($,aQ(Q))}function C$(Q,$){return P$($,MQ(Q,B$))}async function P$(Q,$){if(!$)return!1;return Q.consume($.nonce,$.expiresAt)}class VQ extends A{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class n extends A{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function eQ(Q){if(!Q||typeof Q.key!=="string"||Q.key.length===0)throw new n("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 f="gemi_att_";function Q9(){return`${f}${crypto.randomUUID()}`}class YQ{store;storage;scope;constructor(Q,$,Z){this.store=Q;this.storage=$;this.scope=Z;eQ(Z)}async get(Q){let $=await this.store.find(this.scope,Q);if(!$||$.scopeKey!==this.scope.key)throw new VQ(Q);return $}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,$){if(!$.objectName)throw new VQ(Q);return await this.storage.read({name:$.objectName})}async file(Q){let $=await this.get(Q),J=(await this.readRecord(Q,$)).body,W=J instanceof Blob?J:J?await new Response(J).blob():new Blob([]);return new File([W],$.name,{type:$.mimeType})}async put(Q,$={}){let Z=Q9(),J=$.mimeType??Q.type??"",W=$.name??(Q instanceof File?Q.name:Z),G=await this.storage.put({name:$9(Z,W),body:Q,contentType:J||void 0}),X={id:Z,scopeKey:this.scope.key,objectName:G,name:W,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,X),X}}function $9(Q,$){let Z=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Q}${Z?`.${Z[1].toLowerCase()}`:""}`}class SQ{rows=new Map;async put(Q,$){eQ(Q),this.rows.set($.id,{...$,scopeKey:Q.key})}async find(Q,$){eQ(Q);let Z=this.rows.get($);if(!Z||Z.scopeKey!==Q.key)return null;return Z}get size(){return this.rows.size}}var RQ=new SQ;var Z9=new TextEncoder;function q$(Q){return`id: ${Q.seq}
|
|
3
3
|
data: ${JSON.stringify(Q.event)}
|
|
4
4
|
|
|
5
|
-
`}var
|
|
5
|
+
`}var GZ=5000,XZ=`: keepalive
|
|
6
6
|
|
|
7
|
-
`;function Z9(Q,$=WZ){let Z=null,J=!1,W=()=>{if(J)return;if(Z!==null)clearTimeout(Z);Z=setTimeout(()=>{if(Z=null,J)return;try{Q.enqueue($9.encode(GZ))}catch{G();return}W()},$)},G=()=>{if(J=!0,Z!==null)clearTimeout(Z);Z=null};return W(),{touch:W,stop:G}}function XZ(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function q$(Q,$=200){let Z=Q[Symbol.asyncIterator](),J=-1,W,G=new ReadableStream({start(X){W=Z9(X)},async pull(X){try{let Y=await Z.next();if(Y.done){W.stop(),X.close();return}J=Y.value.seq,X.enqueue($9.encode(P$(Y.value))),W.touch()}catch(Y){let H={type:"error",error:YZ(Y)};W.stop(),X.enqueue($9.encode(P$({seq:J+1,event:H}))),X.close()}},cancel(X){W.stop(),Z.return?.(X)}});return new Response(G,{status:$,headers:XZ()})}var VZ=new Set(["frame_cursor_evicted","live_run_not_found"]);function YZ(Q){let $=Q&&typeof Q==="object"?Q.code:void 0;if(Q instanceof Error&&typeof $==="string"&&VZ.has($))return{code:"unknown",message:Q.message,retryable:!1};return console.error("[gemi/ai] agent stream failed",Q),{code:"unknown",message:"The run's stream failed.",retryable:!1}}function u(Q){let $=new Set;for(let Z of Q)for(let J of Z.content??[]){if(J.type!=="tool-call")continue;for(let W of J.attachments??[])if(W&&"shown"in W&&W.shown)$.add(W.shown.messageId)}return $}function W9(Q){if(Q.length===0)return[];let $=u(Q),Z=[0];for(let J=1;J<Q.length;J++){let W=Q[J];if(W.role==="user"&&!$.has(W.id))Z.push(J)}return Z}function HZ(Q){let $=W9(Q);return $.map((Z,J)=>Q.slice(Z,$[J+1]??Q.length))}function N$(Q){try{return JSON.stringify(Q).length}catch{return 0}}var KZ=4,_$=10,M$="[Earlier turns of this conversation are not shown.]";function G9(Q,$={}){let Z=[...Q],J=W9(Z),W=BZ($),G=RQ($.maxTurns)??1/0,X=Math.max(1,Math.floor(RQ($.step)??_$));if(J.length<=1||G>=J.length&&W===1/0)return{messages:Z,start:0,omittedTurns:0,omittedMessages:0};let Y=Array.from({length:Z.length+1},()=>0);if(W!==1/0)for(let j=Z.length-1;j>=0;j--)Y[j]=Y[j+1]+N$(Z[j]);let H=(j)=>J.length-j<=G&&Y[J[j]]<=W,V=-1;for(let j=0;j<J.length;j+=X)if(H(j)){V=j;break}if(V<0){for(let j=0;j<J.length;j++)if(H(j)){V=j;break}}if(V<0)V=J.length-1;if(V===0)return{messages:Z,start:0,omittedTurns:0,omittedMessages:0};let K=J[V],z=Z.slice(0,K),B=z.filter((j)=>j.role==="system"),U=zZ(z,Z.slice(K)),F={turns:V,messages:z.length-B.length},D=typeof $.note==="function"?$.note(F):$.note===void 0?M$:$.note;if(D){let j=U[0];U[0]={...j,content:[{type:"text",text:D},...j.content]}}return{messages:[...B,...U],start:K,omittedTurns:F.turns,omittedMessages:F.messages}}function RQ(Q){return typeof Q==="number"&&Q>0?Q:void 0}function BZ(Q){let $=RQ(Q.maxBytes)??1/0,Z=RQ(Q.maxTokens);return Math.min($,Z===void 0?1/0:Z*KZ)}function O$(Q,$){let Z=Array.isArray(Q?.namespaces)?Q.namespaces:[],J=Array.isArray(Q?.loaded)?Q.loaded:[];return $.namespace?Z.includes($.namespace):J.includes(String($.name))}function J9(Q){return Array.isArray(Q.toolSearches)?Q.toolSearches:[]}function zZ(Q,$){let Z=[];for(let V of Q)for(let K of V.content??[])if(K.type==="tool-call")Z.push(...J9(K));if(Z.length===0)return $;let J=[],W=new Set,G;if($.forEach((V,K)=>{(V.content??[]).forEach((z,B)=>{if(z.type!=="tool-call"||z.partial)return;if(J.push(...J9(z)),J.some((F)=>O$(F,z)))return;let U=Z.filter((F)=>O$(F,z));if(U.length===0)return;for(let F of U)W.add(F);G??={message:K,part:B}})}),!G)return $;let X=Z.filter((V)=>W.has(V)),Y=[...$],H=Y[G.message];return Y[G.message]={...H,content:H.content.map((V,K)=>K===G.part&&V.type==="tool-call"?{...V,toolSearches:[...X,...J9(V)]}:V)},Y}class c 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 m{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(typeof Q.inputSchema!=="function")U9(Q.inputSchema,`The tool "${Q.name}"`,"inputSchema");if(Q.timeoutMs!==void 0)Y9(Q.timeoutMs,`The tool "${Q.name}"`,"timeoutMs");return new m(Q)}static ask(Q){return m.create({name:Q.name,description:Q.description,inputSchema:B9,outputSchema:Q.outputSchema,answeredBy:"client"})}}var B9={toJSONSchema:()=>({type:"object",properties:{question:{type:"string",description:"What to ask the user"}},required:["question"],additionalProperties:!1}),parse(Q){let $=B9.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 n{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 n(Q)}}class z9{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 z9(Q)}}var YQ="skills",UZ="Instructions this agent can load on demand. Load the relevant one before acting in the area it covers.";function U9(Q,$,Z){let J=Q?.toJSONSchema?.();if(J?.type==="object")return;let W=!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 ${W}, 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 Y9(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 S$(Q){if(Q===void 0)return;if(Q===null||!Number.isFinite(Q))return null;return Q}var DZ=2147483647;function R$(Q,$){if(Q===null||Q>DZ)return()=>{};let Z=setTimeout($,Q);return()=>clearTimeout(Z)}function X9(Q){if(Q<1000)return`${Q}ms`;if(Q<60000)return`${+(Q/1000).toFixed(1)}s`;return`${+(Q/60000).toFixed(1)}m`}var D9={type:"object",properties:{},required:[],additionalProperties:!1},F9=600000;class JQ 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}}var FZ=8,jZ=3;class j9{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??FZ,this.maxDepth=Q.maxDepth??jZ,this.reasoning=Q.reasoning;let $=S$(Q.maxRunDurationMs);this.maxRunDurationMs=$===void 0?F9:$;let{registry:Z,providerTools:J}=LZ(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:$,contextWindow:Q.contextWindow,prepareStep:Q.prepareStep?[Q.prepareStep]:[]}}static create(Q){if(Q.output)U9(Q.output,`The agent "${Q.name}"`,"output");if(Q.maxRunDurationMs!=null)Y9(Q.maxRunDurationMs,`The agent "${Q.name}"`,"maxRunDurationMs");return new j9(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?S$(Q.maxRunDurationMs):this.config.maxRunDurationMs,contextWindow:Q.contextWindow===!1?void 0:Q.contextWindow??this.config.contextWindow,prepareStep:Q.prepareStep?[...this.config.prepareStep,Q.prepareStep]:this.config.prepareStep};if(Q.maxRunDurationMs!=null)Y9(Q.maxRunDurationMs,`Agent.stream for "${this.name}"`,"maxRunDurationMs");return new h$($,Q)}}function H9(Q){let $=Q.inputSchema;return{name:Q.tool.name,description:Q.tool.description,parameters:$?$.toJSONSchema():D9,strict:$?QQ($):!0,deferred:Q.deferred}}function V9(Q){return typeof Q.inputSchema==="function"?void 0:Q.inputSchema}function LZ(Q,$){let Z=new Map,J=[],W=(G)=>{if(Z.has(G.tool.name))throw Error(`Two tools are named "${G.tool.name}". Tool names are global within an agent \u2014 the client discriminates a tool part by name alone.`);Z.set(G.tool.name,G)};for(let G of Q){if(G instanceof n){if(G.name===YQ)throw Error(`"${YQ}" 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 Y=[];for(let H of G.tools){let V={tool:H,namespace:G.name,deferred:G.deferred||H.deferred,inputSchema:V9(H)};W(V),Y.push(H9(V))}J.push({name:G.name,description:G.description,tools:Y});continue}let X={tool:G,deferred:G.deferred,inputSchema:V9(G)};W(X),J.push(H9(X))}if($.length>0){let G=[];for(let X of $){let Y=CZ(X);W({tool:Y,namespace:YQ,deferred:!1,inputSchema:V9(Y)}),G.push({name:X.name,description:X.description,parameters:D9,strict:!0,deferred:!1})}J.push({name:YQ,description:UZ,tools:G})}return{registry:Z,providerTools:J}}function CZ(Q){return m.create({name:Q.name,description:Q.description,inputSchema:{toJSONSchema:()=>D9,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
|
|
7
|
+
`;function J9(Q,$=GZ){let Z=null,J=!1,W=()=>{if(J)return;if(Z!==null)clearTimeout(Z);Z=setTimeout(()=>{if(Z=null,J)return;try{Q.enqueue(Z9.encode(XZ))}catch{G();return}W()},$)},G=()=>{if(J=!0,Z!==null)clearTimeout(Z);Z=null};return W(),{touch:W,stop:G}}function VZ(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function O$(Q,$=200){let Z=Q[Symbol.asyncIterator](),J=-1,W,G=new ReadableStream({start(X){W=J9(X)},async pull(X){try{let Y=await Z.next();if(Y.done){W.stop(),X.close();return}J=Y.value.seq,X.enqueue(Z9.encode(q$(Y.value))),W.touch()}catch(Y){let H={type:"error",error:HZ(Y)};W.stop(),X.enqueue(Z9.encode(q$({seq:J+1,event:H}))),X.close()}},cancel(X){W.stop(),Z.return?.(X)}});return new Response(G,{status:$,headers:VZ()})}var YZ=new Set(["frame_cursor_evicted","live_run_not_found"]);function HZ(Q){let $=Q&&typeof Q==="object"?Q.code:void 0;if(Q instanceof Error&&typeof $==="string"&&YZ.has($))return{code:"unknown",message:Q.message,retryable:!1};return console.error("[gemi/ai] agent stream failed",Q),{code:"unknown",message:"The run's stream failed.",retryable:!1}}function c(Q){let $=new Set;for(let Z of Q)for(let J of Z.content??[]){if(J.type!=="tool-call")continue;for(let W of J.attachments??[])if(W&&"shown"in W&&W.shown)$.add(W.shown.messageId)}return $}function G9(Q){if(Q.length===0)return[];let $=c(Q),Z=[0];for(let J=1;J<Q.length;J++){let W=Q[J];if(W.role==="user"&&!$.has(W.id))Z.push(J)}return Z}function KZ(Q){let $=G9(Q);return $.map((Z,J)=>Q.slice(Z,$[J+1]??Q.length))}function _$(Q){try{return JSON.stringify(Q).length}catch{return 0}}var BZ=4,M$=10,S$="[Earlier turns of this conversation are not shown.]";function X9(Q,$={}){let Z=[...Q],J=G9(Z),W=zZ($),G=TQ($.maxTurns)??1/0,X=Math.max(1,Math.floor(TQ($.step)??M$));if(J.length<=1||G>=J.length&&W===1/0)return{messages:Z,start:0,omittedTurns:0,omittedMessages:0};let Y=Array.from({length:Z.length+1},()=>0);if(W!==1/0)for(let j=Z.length-1;j>=0;j--)Y[j]=Y[j+1]+_$(Z[j]);let H=(j)=>J.length-j<=G&&Y[J[j]]<=W,V=-1;for(let j=0;j<J.length;j+=X)if(H(j)){V=j;break}if(V<0){for(let j=0;j<J.length;j++)if(H(j)){V=j;break}}if(V<0)V=J.length-1;if(V===0)return{messages:Z,start:0,omittedTurns:0,omittedMessages:0};let K=J[V],z=Z.slice(0,K),B=z.filter((j)=>j.role==="system"),U=UZ(z,Z.slice(K)),F={turns:V,messages:z.length-B.length},D=typeof $.note==="function"?$.note(F):$.note===void 0?S$:$.note;if(D){let j=U[0];U[0]={...j,content:[{type:"text",text:D},...j.content]}}return{messages:[...B,...U],start:K,omittedTurns:F.turns,omittedMessages:F.messages}}function TQ(Q){return typeof Q==="number"&&Q>0?Q:void 0}function zZ(Q){let $=TQ(Q.maxBytes)??1/0,Z=TQ(Q.maxTokens);return Math.min($,Z===void 0?1/0:Z*BZ)}function N$(Q,$){let Z=Array.isArray(Q?.namespaces)?Q.namespaces:[],J=Array.isArray(Q?.loaded)?Q.loaded:[];return $.namespace?Z.includes($.namespace):J.includes(String($.name))}function W9(Q){return Array.isArray(Q.toolSearches)?Q.toolSearches:[]}function UZ(Q,$){let Z=[];for(let V of Q)for(let K of V.content??[])if(K.type==="tool-call")Z.push(...W9(K));if(Z.length===0)return $;let J=[],W=new Set,G;if($.forEach((V,K)=>{(V.content??[]).forEach((z,B)=>{if(z.type!=="tool-call"||z.partial)return;if(J.push(...W9(z)),J.some((F)=>N$(F,z)))return;let U=Z.filter((F)=>N$(F,z));if(U.length===0)return;for(let F of U)W.add(F);G??={message:K,part:B}})}),!G)return $;let X=Z.filter((V)=>W.has(V)),Y=[...$],H=Y[G.message];return Y[G.message]={...H,content:H.content.map((V,K)=>K===G.part&&V.type==="tool-call"?{...V,toolSearches:[...X,...W9(V)]}:V)},Y}class m 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 p{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(typeof Q.inputSchema!=="function")D9(Q.inputSchema,`The tool "${Q.name}"`,"inputSchema");if(Q.timeoutMs!==void 0)H9(Q.timeoutMs,`The tool "${Q.name}"`,"timeoutMs");return new p(Q)}static ask(Q){return p.create({name:Q.name,description:Q.description,inputSchema:z9,outputSchema:Q.outputSchema,answeredBy:"client"})}}var z9={toJSONSchema:()=>({type:"object",properties:{question:{type:"string",description:"What to ask the user"}},required:["question"],additionalProperties:!1}),parse(Q){let $=z9.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 s{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 s(Q)}}class U9{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 U9(Q)}}var HQ="skills",DZ="Instructions this agent can load on demand. Load the relevant one before acting in the area it covers.";function D9(Q,$,Z){let J=Q?.toJSONSchema?.();if(J?.type==="object")return;let W=!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 ${W}, 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 H9(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 R$(Q){if(Q===void 0)return;if(Q===null||!Number.isFinite(Q))return null;return Q}var FZ=2147483647;function T$(Q,$){if(Q===null||Q>FZ)return()=>{};let Z=setTimeout($,Q);return()=>clearTimeout(Z)}function V9(Q){if(Q<1000)return`${Q}ms`;if(Q<60000)return`${+(Q/1000).toFixed(1)}s`;return`${+(Q/60000).toFixed(1)}m`}var F9={type:"object",properties:{},required:[],additionalProperties:!1},j9=600000;class WQ 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}}var jZ=8,LZ=3;class L9{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??jZ,this.maxDepth=Q.maxDepth??LZ,this.reasoning=Q.reasoning;let $=R$(Q.maxRunDurationMs);this.maxRunDurationMs=$===void 0?j9:$;let{registry:Z,providerTools:J}=CZ(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:$,contextWindow:Q.contextWindow,prepareStep:Q.prepareStep?[Q.prepareStep]:[]}}static create(Q){if(Q.output)D9(Q.output,`The agent "${Q.name}"`,"output");if(Q.maxRunDurationMs!=null)H9(Q.maxRunDurationMs,`The agent "${Q.name}"`,"maxRunDurationMs");return new L9(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?R$(Q.maxRunDurationMs):this.config.maxRunDurationMs,contextWindow:Q.contextWindow===!1?void 0:Q.contextWindow??this.config.contextWindow,prepareStep:Q.prepareStep?[...this.config.prepareStep,Q.prepareStep]:this.config.prepareStep};if(Q.maxRunDurationMs!=null)H9(Q.maxRunDurationMs,`Agent.stream for "${this.name}"`,"maxRunDurationMs");return new y$($,Q)}}function K9(Q){let $=Q.inputSchema;return{name:Q.tool.name,description:Q.tool.description,parameters:$?$.toJSONSchema():F9,strict:$?$Q($):!0,deferred:Q.deferred}}function Y9(Q){return typeof Q.inputSchema==="function"?void 0:Q.inputSchema}function CZ(Q,$){let Z=new Map,J=[],W=(G)=>{if(Z.has(G.tool.name))throw Error(`Two tools are named "${G.tool.name}". Tool names are global within an agent \u2014 the client discriminates a tool part by name alone.`);Z.set(G.tool.name,G)};for(let G of Q){if(G instanceof s){if(G.name===HQ)throw Error(`"${HQ}" 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 Y=[];for(let H of G.tools){let V={tool:H,namespace:G.name,deferred:G.deferred||H.deferred,inputSchema:Y9(H)};W(V),Y.push(K9(V))}J.push({name:G.name,description:G.description,tools:Y});continue}let X={tool:G,deferred:G.deferred,inputSchema:Y9(G)};W(X),J.push(K9(X))}if($.length>0){let G=[];for(let X of $){let Y=PZ(X);W({tool:Y,namespace:HQ,deferred:!1,inputSchema:Y9(Y)}),G.push({name:X.name,description:X.description,parameters:F9,strict:!0,deferred:!1})}J.push({name:HQ,description:DZ,tools:G})}return{registry:Z,providerTools:J}}function PZ(Q){return p.create({name:Q.name,description:Q.description,inputSchema:{toJSONSchema:()=>F9,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 qZ(J)}`);return Z.join(`
|
|
9
9
|
|
|
10
|
-
`)}})}async function
|
|
10
|
+
`)}})}async function qZ(Q){try{return await Bun.file(Q).text()}catch($){return`(could not be read: ${$.message})`}}function OZ(Q){return typeof Q==="object"&&Q!==null&&typeof Q.next==="function"&&Symbol.asyncIterator in Q}function A$(Q,$){let Z=[...Q],J=new Map(Z.map((W,G)=>[W.id,G]));for(let W of $){let G=J.get(W.id);if(G===void 0)J.set(W.id,Z.length),Z.push(W);else Z[G]=W}return Z}function AQ(Q){let $=new Set;for(let J of Q)for(let W of J.content)if(W.type==="tool-result")$.add(W.toolCallId);let Z=new Set;for(let J of Q)for(let W of J.content)if(W.type==="tool-call"&&!$.has(W.toolCallId))Z.add(W.toolCallId);return Z}function k$(Q){for(let $=Q.length-1;$>=0;$--){let Z=Q[$].content;for(let J=Z.length-1;J>=0;J--){let W=Z[J];if(W.type==="output"&&W.partial!==!0)return W.value}}return}function E$(Q,$){return $===void 0?`"${Q}"`:`"${Q}" labelled "${$}"`}function h$(Q){return Q.content.map(($)=>$.type==="text"?$.text:`<${$.type}>`).join("")}function NZ(Q){if(Q.prompt!==void 0)return`user:${Q.prompt}`;let $=Q.messages?.[0];return $?`${$.role}:${h$($)}`:null}var x$=1;function _Z(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 W=Boolean(Z.showModel);if(W!==Boolean(Q.shown))return W?"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 MZ(Q,$,Z){if(Q.agent!==$.name||Q.label!==Z.label)return`was ${E$(Q.agent,Q.label)} on the turn that escalated and is ${E$($.name,Z.label)} on the replay`;let J=NZ(Z),W=Q.messages[0],G=W?`${W.role}:${h$(W)}`:null;if(J!==null&&G!==null&&J!==G)return`was started with ${JSON.stringify(G)} on the turn that escalated and with ${JSON.stringify(J)} on the replay`;return null}function b$(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 B9{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 y${runId;config;params;context;controller=new AbortController;buffer=[];waiters=new Set;seq=0;ended=!1;history=[];lastStep;produced=[];current=null;outputTruncated=!1;amended=new Map;unreported=new Set;usage=M();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:j9;this.cancelDeadline=T$(J,()=>this.expire(J)),this.settled=this.execute(),kQ.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,W,G=new ReadableStream({start:async(X)=>{W=J9(X);try{for await(let Y of $){if(J)break;X.enqueue(Z.encode(`id: ${Y.seq}
|
|
11
11
|
data: ${JSON.stringify(Y.event)}
|
|
12
12
|
|
|
13
|
-
`)),W.touch()}}catch{}W.stop();try{X.close()}catch{}},cancel:()=>{J=!0,W.stop()}});return new Response(G,{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
|
|
13
|
+
`)),W.touch()}}catch{}W.stop();try{X.close()}catch{}},cancel:()=>{J=!0,W.stop()}});return new Response(G,{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 WQ({...$,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 ${V9(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.resolveToolSchemas(),Z=$?[]:await this.ingestTurn();if($)this.fail($),this.finishReason="error";else if(Z.length>0)this.finishReason="awaiting-input",this.emit({type:"awaiting-input",runId:this.runId,pending:Z});else await this.loop()}catch($){if($ instanceof x||this.controller.signal.aborted)await this.finalizeAborted();else this.fail(this.config.provider.normalizeError($),b($)),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}:{}}}async resolveToolSchemas(){let Q=[...this.config.registry.values()].filter((H)=>!H.inputSchema);if(Q.length===0)return;let $={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,signal:this.controller.signal},Z=new Map,J=await Promise.all(Q.map(async(H)=>{try{let V=H.tool.inputSchema,K=await V($);D9(K,`The tool "${H.tool.name}"`,"inputSchema"),Z.set(H.tool.name,K);return}catch(V){return`"${H.tool.name}": ${V instanceof Error?V.message:String(V)}`}}));if(this.controller.signal.aborted)throw new x;let W=J.filter((H)=>H!==void 0);if(W.length>0)return{code:"tool_error",message:`Could not resolve the input schema of ${W.join("; ")}`,retryable:!1};let G=new Map;for(let[H,V]of this.config.registry)G.set(H,Z.has(H)?{...V,inputSchema:Z.get(H)}:V);let X=(H)=>Z.has(H.name)?K9(G.get(H.name)):H,Y=this.config.providerTools.map((H)=>("tools"in H)?{...H,tools:H.tools.map(X)}:X(H));this.config={...this.config,registry:G,providerTools:Y};return}fail(Q,$={}){let Z={...Q,...$};this.failure=Z,this.emit({type:"error",error:this.redact(Z,{source:"run",failure:Z})})}redact(Q,$){let Z=v$(this.params.redactError,Q,$,(J)=>this.writeLog(`[gemi/ai] agent "${this.config.name}" redactError threw`,{error:J}));return f$(Z,Q),Z}logFailure(Q){let $=`[gemi/ai] agent "${this.config.name}" run failed (${Q.code}${Q.status!==void 0?` ${Q.status}`:""}): ${Q.message}`;this.writeLog($,{error:Q})}logToolFailure(Q,$){let Z=$ instanceof Error?$.message:String($);this.writeLog(`[gemi/ai] agent "${this.config.name}" tool "${String(Q.name)}" threw: ${Z}`,{toolCallId:Q.toolCallId,error:$})}writeLog(Q,$){let Z={agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},...this.depth>0?{chain:this.chain}:{},...$},J=!1;try{JQ.error(Q,Z),J=!0}catch{}if(!J||Bun.env.NODE_ENV==="development")console.error(Q,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(this.lastStep={reason:J.reason,usage:Z.usage},J.error){this.fail(J.error,J.detail),await this.finalizeMessage("error"),this.finishReason="error";return}let W=Z.content.filter((X)=>X.type==="tool-call");if(W.length===0){this.finishReason=J.reason,await this.finalizeMessage(J.reason);return}let G=await this.runTools(Z,W,$);if(G.length>0){this.finishReason="awaiting-input",await this.finalizeMessage("awaiting-input"),this.emit({type:"awaiting-input",runId:this.runId,pending:G});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=CQ(J.text)}this.emit({type:"message-end",messageId:$.id,finishReason:Q,...Z?{outputTruncated:!0}:{},...$.usage?{usage:$.usage}:{}}),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 Z=this.controller.signal,J=this.config.provider,W=await this.prepareRequest(Q,$);if("error"in W)return{reason:"error",error:W.error};let G={reason:"stop"},X=new Map,Y=[],H=()=>{if(Y.length===0)return{};let U=Y;return Y=[],{toolSearches:U}},V="",z=J.stream({messages:W.messages,systemPrompt:W.instructions,tools:this.config.providerTools.length>0?this.config.providerTools:void 0,output:this.config.output?jQ(this.config.output):void 0,reasoning:this.config.reasoning,maxOutputTokens:this.config.maxOutputTokens,temperature:this.config.temperature,signal:Z})[Symbol.asyncIterator]();for(;;){let U=await g(Promise.resolve(z.next()),Z);if(U.done)break;let F=U.value;switch(F.type){case"text-delta":{ZQ(Q,"text",F.delta),this.emit({type:"text-delta",messageId:Q.id,delta:F.delta});break}case"reasoning-delta":{PQ(Q,F.id,F.delta),this.emit({type:"reasoning-delta",messageId:Q.id,delta:F.delta,id:F.id});break}case"output-delta":{V+=F.delta,this.emit({type:"output-delta",messageId:Q.id,delta:F.delta,snapshot:FQ(V)});break}case"tool-search":{Y.push({namespaces:F.namespaces,loaded:F.loaded,...F.arguments!==void 0?{arguments:F.arguments}:{}}),this.emit({type:"tool-search",loaded:F.loaded});break}case"tool-call-delta":{let D=X.get(F.toolCallId)??{name:F.name,args:""};D.args+=F.argsDelta,D.name=F.name||D.name,D.namespace=F.namespace||D.namespace,X.set(F.toolCallId,D),this.emit({type:"tool-call",messageId:Q.id,part:{type:"tool-call",toolCallId:F.toolCallId,name:D.name,input:FQ(D.args),partial:!0,...D.namespace?{namespace:D.namespace}:{}}});break}case"tool-call":{let D=F.namespace||X.get(F.toolCallId)?.namespace;X.delete(F.toolCallId);let j={type:"tool-call",toolCallId:F.toolCallId,name:F.name,input:I$(F.args),...D?{namespace:D}:{},...H()};Q.content.push(j),this.emit({type:"tool-call",messageId:Q.id,part:j});break}case"finish":{if(this.usage=T(this.usage,F.usage),Q.usage=T(Q.usage??M(),F.usage),!G.error)G={reason:F.reason};break}case"error":{G={reason:"error",error:F.error,detail:b(F)};break}case"file-rejected":{this.markFileRejected(F.fileId,F.message,b(F));break}}}for(let[U,F]of X){let D={type:"tool-call",toolCallId:U,name:F.name,input:I$(F.args),...F.namespace?{namespace:F.namespace}:{},...H()};Q.content.push(D),this.emit({type:"tool-call",messageId:Q.id,part:D})}let B=G.reason==="length";if(B)this.outputTruncated=!0;if(this.config.output&&V&&!G.error&&!B){let U=LQ(this.config.output,V);if(U.ok===!0)this.output=U.value,Q.content.push({type:"output",value:U.value});else this.emit({type:"error",error:U.error})}return G}async prepareRequest(Q,$){let Z=this.historyForProvider(Q),J=this.config.contextWindow?X9(Z,this.config.contextWindow).messages:Z,W=await this.systemPrompt();for(let G of this.config.prepareStep){let X;try{X=await G({step:$,messages:[...J],history:[...Z],instructions:W,usage:this.usage,...this.lastStep?.usage?{lastStepUsage:this.lastStep.usage}:{},...this.lastStep?{lastFinishReason:this.lastStep.reason}:{},runId:this.runId,threadId:this.params.threadId,agent:this.config.name,depth:this.depth,context:this.context,signal:this.controller.signal})}catch(Y){if(Y instanceof x||this.controller.signal.aborted)throw Y;return{error:{code:"unknown",message:`prepareStep threw: ${Y instanceof Error?Y.message:String(Y)}`,retryable:!1}}}if(!X)continue;if(X.messages!==void 0){if(!Array.isArray(X.messages))return{error:{code:"unknown",message:"prepareStep answered `messages` that is not an array.",retryable:!1}};J=X.messages}if(X.instructions!==void 0)W=X.instructions||void 0}return{messages:J,instructions:W}}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 J=[],W=[];for(let G of $){let X=this.config.registry.get(String(G.name));if(!X){this.addResult(Q,{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"error",error:{code:"tool_error",message:`There is no tool named "${String(G.name)}".`,toolCallId:G.toolCallId,retryable:!0}});continue}let Y=X.inputSchema.safeParse(G.input);if(Y.ok===!1){this.addResult(Q,{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${String(G.name)}": ${Y.errors.join(", ")}`,toolCallId:G.toolCallId,retryable:!0}});continue}G.input=Y.value;let H=b$(X.tool);if(H){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(G));continue}J.push({toolCallId:G.toolCallId,name:G.name,input:Y.value,kind:H,signature:Y$(this.claimsFor(G.toolCallId,String(G.name),H,Y.value)),...this.pathPrefix.length>0?{path:[...this.pathPrefix]}:{}});continue}W.push(this.executeTool(X,Q.id,G,Y.value,Z).then(async(V)=>{this.addResult(Q,V),await this.settleShown(G.toolCallId)}).catch((V)=>{if(V instanceof c){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(G));return}J.push(...V.pending);return}}))}return await y(Promise.all(W).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,subject:this.params.subject??null}}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,W,G){let X=Q.tool.timeoutMs;if(X===void 0)return this.runToolBody(Q,$,Z,J,W,G,this.controller.signal,()=>!1);let Y=new AbortController,H=this.controller.signal,V=()=>Y.abort(H.reason);if(H.aborted)V();else H.addEventListener("abort",V,{once:!0});let K=!1,z=this.runToolBody(Q,$,Z,J,W,G,Y.signal,()=>K),B=()=>{},U=new Promise((F)=>{B=R$(X,()=>{let D=`"${String(Z.name)}" did not finish within ${X9(X)} (timeoutMs: ${X}) and was cancelled.`;Y.abort(new DOMException(D,"TimeoutError")),F({type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:{code:"timeout",message:D,toolCallId:Z.toolCallId,retryable:!0}})})});z.catch(()=>{});try{return await Promise.race([z,U])}finally{K=!0,B()}}async runToolBody(Q,$,Z,J,W,G,X,Y){let H=this.toolFiles(Z,X),V={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,toolCallId:Z.toolCallId,signal:X,step:W,depth:this.depth,resumed:G!==void 0,attachments:H.attachments,generateImage:H.generateImage,editImage:H.editImage,turn:this.toolTurn($),runAgent:this.nestedRunner($,Z,X,G),generate:(K)=>this.generateForTool(K,X,Z.toolCallId)};try{let K=Q.tool.execute(J,V),z;if(qZ(K)){let B=await K.next();while(!B.done){if(Y())throw K.return(void 0).catch(()=>{}),new k;this.emit({type:"tool-progress",toolCallId:Z.toolCallId,data:B.value}),B=await K.next()}z=B.value}else z=await K;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"ok",output:z}}catch(K){if(K instanceof k||this.controller.signal.aborted)throw new k;if(K instanceof c)throw K;let z=K instanceof T;if(!z&&this.config.logErrors)this.logToolFailure(Z,K);let B={code:"tool_error",message:K instanceof Error?K.message:String(K),toolCallId:Z.toolCallId,retryable:z?K.retryable:!0};return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:this.redact(B,{source:"tool",toolName:String(Z.name),cause:K})}}}async generateForTool(Q,$,Z){let J=this.controller.signal;return dQ({...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:(W)=>{if(this.usage=R(this.usage,W.usage),J.aborted)throw new k}})}nestedRunner(Q,$,Z,J){let W=new K9(()=>$.nested,()=>$.nested=[]);return async(G,X={})=>{let{at:Y,recorded:H,write:V}=W.next();if(H){let K=_Z(H,G,X);if(K)throw new T(`Nested run ${Y} of "${String($.name)}" ${K}. `+"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(H.finishReason!=="awaiting-input")return{runId:H.runId,agent:H.agent,messages:H.messages,finishReason:H.finishReason??"stop",usage:H.usage??M(),output:A$(H.messages),nested:H}}return this.runNested(Q,$,Z,G,X,V,H,J?.answers??[])}}async runNested(Q,$,Z,J,W,G,X,Y){let H=[...this.chain,J.name];if(this.chain.includes(J.name))throw new T(`"${J.name}" is already running further up this chain: ${H.join(" -> ")}. An agent cannot run itself, directly or through another agent.`);let V=this.depth+1;if(V>this.maxDepth)throw new T(`Nested agent runs are ${this.maxDepth} deep at most and this one would be ${V}: ${H.join(" -> ")}. Raise maxDepth on the agent at the root of the run if the tree is meant to be this deep.`);let K=W.label,z=[...this.pathPrefix,$.toolCallId],B=this.onPending==="deny"?"deny":W.onPending??"escalate",U=X!==void 0,F=U?TQ(X.messages):new Set,D=U?Y.filter((O)=>{let C=x$(O.path,z);if(C===null)return!1;return F.has(C.length>0?C[0]:O.toolCallId)}):[],j=J.stream({messages:U?X.messages:W.messages??[],turn:U?{toolResults:D}:W.prompt?{text:W.prompt}:void 0,context:this.context,attachments:this.params.attachments,body:this.params.body,signal:Z,threadId:this.params.threadId,redactError:this.params.redactError,nonces:this.params.nonces,receipts:this.params.receipts,subject:this.params.subject,instructions:W.instructions,maxOutputTokens:W.maxOutputTokens,temperature:W.temperature,runId:U?X.runId:void 0,nesting:{depth:V,maxDepth:this.maxDepth,chain:H,signingRunId:this.signingRunId,signingPath:z,onPending:B}}),L=[],S=(O)=>this.emit({type:"nested-event",toolCallId:$.toolCallId,runId:j.runId,agent:J.name,label:K,event:O}),N=(async()=>{for await(let O of j){if(O.type==="awaiting-input")L=O.pending;if(S(O),O.type==="run-start"&&!U)for(let C of W.messages??[])S({type:"message",message:C});if(O.type==="error")this.emit({type:"error",error:O.error,nested:{toolCallId:$.toolCallId,runId:j.runId,agent:J.name}})}})(),v=(async()=>{let O=await j.result();await N;let C=U?T$(X.messages,O.messages):T$(W.messages??[],O.messages),P={runId:j.runId,agent:J.name,label:K,messages:C,finishReason:O.finishReason,usage:U?R(X.usage??M(),O.usage):O.usage,...O.finishReason==="awaiting-input"?{signature:U$({runId:this.signingRunId,path:z,nestedRunId:j.runId,open:[...TQ(C)],input:$.input,subject:this.params.subject??null})}:{}};return G(P),this.usage=R(this.usage,O.usage),{result:O,record:P}})(),E=v.then(()=>{return},()=>{return});this.nestedSettling.add(E);let _,w;try{({result:_,record:w}=await v)}finally{this.nestedSettling.delete(E)}if(this.controller.signal.aborted)throw new k;if(_.finishReason==="awaiting-input"){if(L.length===0)throw new T(`"${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 c({pending:L,path:z,nested:w})}return{runId:w.runId,agent:J.name,messages:w.messages,finishReason:_.finishReason,usage:w.usage??M(),output:_.output??A$(w.messages),..._.error?{error:_.error}:{},nested:w}}addResult(Q,$){Q.content.push($),this.emit({type:"tool-result",messageId:Q.id,part:$})}toolFiles(Q,$){let Z=this.params.attachments??null,J=new K9(()=>Q.attachments,()=>Q.attachments=[],()=>({failed:!0})),W=()=>{if(!Z)throw new o("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},G=async(V,K,z)=>{let B=W(),U=K.mimeType||V.type||"",F=K.name??(V instanceof File?V.name:"attachment"),D;if(K.showModel){let L=this.config.provider;if(!L.capabilities.fileInput)throw new T(`"${String(Q.name)}" asked to show a file to ${L.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.`);D=await L.upload(new File([V],F,{type:U||void 0}))}return{attachment:await B.put(V,{name:F,mimeType:U,fileId:D}),...z?{generated:z}:{},...D?{shown:{fileId:D,messageId:`msg_${crypto.randomUUID()}`,createdAt:new Date().toISOString()}}:{}}},X=(V,K,z)=>{let B=V.generated?"image":"put";if(B===K)return;throw new T(`Attachment ${z} of "${String(Q.name)}" was ${B==="image"?"a generated image":"a stored file"} on the first attempt and is ${K==="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.`)},Y=async(V,K,z)=>{let{at:B,recorded:U,write:F}=J.next();if(U&&"attachment"in U){if(X(U,"image",B),U.shown)this.queueShown(Q.toolCallId,U);return{attachment:U.attachment,size:U.generated.size,mimeType:U.attachment.mimeType,usage:U.generated.usage}}let D=await z();this.usage=R(this.usage,D.usage);let j=D.mimeType==="image/jpeg"?"jpg":"png",L=await G(D.image,{name:K.name??`${V.name}.${j}`,mimeType:D.mimeType,...K.showModel?{showModel:!0}:{}},{size:D.size,usage:D.usage});if(F(L),L.shown)this.queueShown(Q.toolCallId,L);return{attachment:L.attachment,size:D.size,mimeType:D.mimeType,usage:D.usage}},H=async(V)=>typeof V==="string"?await W().file(V):V;return{generateImage:(V,K)=>Y(V,K,()=>V.generate({...K,signal:$})),editImage:(V,K)=>Y(V,K,async()=>{let{images:z,mask:B,...U}=K;return await V.edit({...U,images:await Promise.all(z.map(H)),...B?{mask:await H(B)}:{},signal:$})}),attachments:{get:(V)=>W().get(V),read:(V)=>W().read(V),file:(V)=>W().file(V),put:async(V,K={})=>{let{at:z,recorded:B,write:U}=J.next();if(B&&"attachment"in B){X(B,"put",z);let D=NZ(B,V,K);if(D)throw new T(`Attachment ${z} of "${String(Q.name)}" ${D}. `+"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(B.shown)this.queueShown(Q.toolCallId,B);return B.attachment}let F=await G(V,K);if(U(F),F.shown)this.queueShown(Q.toolCallId,F);return F.attachment}}}}toolTurn(Q){let $=this.history.findIndex((G)=>G.id===Q),Z=u(this.history),J;for(let G=$-1;G>=0;G--){let X=this.history[G];if(X.role!=="user"||Z.has(X.id))continue;J=X;break}let W=[];for(let G of J?.content??[]){if(G.type!=="file")continue;let X=G.attachmentId;if(typeof X!=="string"||!X.startsWith(f))continue;if(!W.includes(X))W.push(X)}return Object.freeze({attachments:Object.freeze(W)})}queueShown(Q,$){let Z=$.shown;if(!Z)return;let J=this.shownQueue.get(Q)??[];if(J.some((W)=>W.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((G)=>G!==Q),Z=u($),J=[];for(let G of $){if(!Z.has(G.id))continue;for(let X of G.content)if(X.type==="file")J.push(X)}if(J.length<=E$)return $;let W=new Set(J.slice(0,J.length-E$));return $.map((G)=>{if(!G.content.some((X)=>X.type==="file"&&W.has(X)))return G;return{...G,content:G.content.map((X)=>X.type==="file"&&W.has(X)?{type:"text",text:`[A ${X.mimeType||"file"} produced by a tool (attachment ${X.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.]`}:X)}})}async ingestTurn(){let Q=this.params.turn,$=this.openCalls(),Z=[];if($.length>0){let J=new Set,W=new Set,G=new Map;for(let X of Q?.toolResults??[]){let Y=`${(X.path??[]).join("/")}#${X.toolCallId}`;if(W.has(Y))continue;W.add(Y);let H=(B)=>this.emit({type:"error",error:{code:"invalid_tool_result",message:B,toolCallId:X.toolCallId,retryable:!1}}),V=x$(X.path,this.pathPrefix);if(V===null){H(`The answer for "${X.toolCallId}" is addressed to a tool call this run is not inside.`);continue}if(V.length>0){let B=V[0],U=$.find((j)=>j.call.toolCallId===B);if(!U){H(`No pending tool call with id "${B}" to deliver a nested answer to.`);continue}let F=this.parkedBelow(U.call,V,X.toolCallId);if(F.ok===!1){let j=`The answer for "${X.toolCallId}" is addressed under "${B}", which`;H(F.reason==="unparked"?`${j} has no sub-agent run waiting on that question.`:F.reason==="expired"?`${j} parked a sub-agent run that has since expired. Ask again.`:`${j} carries a record of a parked sub-agent run the server did not sign.`);continue}let D=G.get(B);if(!D){if(!await this.spend(L$,F.signature)){H(`The answer for "${X.toolCallId}" is addressed under "${B}", which has already been re-entered on that record. Ask again.`);continue}D=[],G.set(B,D),J.add(B)}D.push(X);continue}let K=$.find((B)=>B.call.toolCallId===X.toolCallId);if(!K){H(`No pending tool call with id "${X.toolCallId}".`);continue}let z=await this.resolveAnswer(K,X,Z);if(z===null)continue;if(J.add(X.toolCallId),z!=="open")this.attachToHistory(K,z),await this.settleShown(X.toolCallId)}for(let[X,Y]of G){let H=$.find((K)=>K.call.toolCallId===X),V=await this.reenter(H,Y,Z);if(V)this.attachToHistory(H,V),await this.settleShown(X)}for(let X of $){if(J.has(X.call.toolCallId))continue;this.attachToHistory(X,{type:"tool-result",toolCallId:X.call.toolCallId,name:X.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((W)=>({type:"file",...W.fileId?{fileId:W.fileId}:{},name:W.name,mimeType:W.mimeType,...W.attachmentId?{attachmentId:W.attachmentId}:{}}))],createdAt:new Date().toISOString(),finishReason:"stop"};if(this.history.push(J),this.produced.push(J),this.depth>0)this.emit({type:"message",message:J});else if(Q.localId)this.emit({type:"message-id",localId:Q.localId,messageId:J.id,message:J});await this.report(J)}return Z}parkedBelow(Q,$,Z){let J=$.length>1?$[1]:Z,W=[...this.pathPrefix,Q.toolCallId],G=(Q.nested??[]).find((Y)=>Y.finishReason==="awaiting-input"&&TQ(Y.messages).has(J));if(!G)return{ok:!1,reason:"unparked"};if(typeof G.signature!=="string")return{ok:!1,reason:"unsigned"};let X=D$(G.signature,{path:W,nestedRunId:G.runId,open:[...TQ(G.messages)],input:Q.input,subject:this.params.subject??null});if(X.ok===!1)return{ok:!1,reason:X.reason==="expired"?"expired":"unsigned"};return{ok:!0,signature:G.signature}}async reenter(Q,$,Z){let J=String(Q.call.name),W=this.config.registry.get(J);if(!W||!W.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 G=W.inputSchema.safeParse(Q.call.input);if(G.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}": ${G.errors.join(", ")}`,toolCallId:Q.call.toolCallId,retryable:!0}};let X=this.amendCall(Q);X.input=G.value;try{return await y(this.executeTool(W,Q.message.id,X,G.value,0,{answers:$}),this.controller.signal)}catch(Y){if(Y instanceof c)return Z.push(...Y.pending),null;throw Y}}amendCall(Q){let $=this.amend(Q.message),Z=$.content.indexOf(Q.call),J={...Q.call,nested:(Q.call.nested??[]).map((W)=>({...W})),...Q.call.attachments?{attachments:Q.call.attachments.map((W)=>({...W}))}:{}};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 spend(Q,$){try{return await Q($,this.params.nonces??i)}catch(Z){return this.writeLog(`[gemi/ai] agent "${this.config.name}" could not spend a nonce`,{error:Z}),!1}}async recordReceipt(Q,$){let Z=await $;try{await Q.store.complete(Q.id,Z,Q.expiresAt)}catch(J){this.writeLog(`[gemi/ai] agent "${this.config.name}" could not record a tool receipt`,{error:J})}return Z}async resolveAnswer(Q,$,Z){let J=Q.call,W=String(J.name),G=this.config.registry.get(W),X=(z)=>{return this.emit({type:"error",error:{code:"invalid_tool_result",message:z,toolCallId:J.toolCallId,retryable:!1}}),null};if(!G)return X(`The tool "${W}" no longer exists, so its answer cannot be checked.`);let Y=b$(G.tool);if(!Y)return X(`"${W}" is a server tool with no pending question.`);if(typeof $.signature!=="string"||$.signature.length===0)return X(`The answer for "${W}" carried no signature.`);let H=tQ($.signature);if(!H)return X(`The signature for "${W}" is malformed.`);let V=H$($.signature,{...this.claimsFor(J.toolCallId,W,Y,J.input),runId:H.runId});if(V.ok===!1)return X(V.reason==="expired"?`The approval for "${W}" has expired. Ask again.`:`The answer for "${W}" does not match the call the server made.`);let K;if(this.params.receipts&&Y==="approval"&&"approve"in $&&$.approve===!0){let z=this.params.receipts,B=F$(this.config.name,{...this.claimsFor(J.toolCallId,W,Y,J.input),runId:H.runId}),U;try{U=await z.claim(B,H.expiresAt)}catch(F){return this.writeLog(`[gemi/ai] agent "${this.config.name}" could not claim a tool receipt`,{error:F}),X(`The approval for "${W}" could not be checked. Ask again.`)}if(U.status==="replay")return{...U.result,toolCallId:J.toolCallId,name:J.name};if(U.status==="blocked")return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"error",error:{code:"tool_error",message:`"${W}" was already approved and started, and its result is not recorded yet: it is still running, or it stopped before finishing. It was not run again.`,toolCallId:J.toolCallId,retryable:!1}};K={store:z,id:B,expiresAt:H.expiresAt}}if(!await this.spend(j$,$.signature))return await K?.store.release(K.id).catch((z)=>{this.writeLog(`[gemi/ai] agent "${this.config.name}" could not release a tool receipt`,{error:z})}),X(`The answer for "${W}" has already been used. Ask again.`);if("approve"in $){if(Y!=="approval")return X(`"${W}" is answered by the client, not approved.`);if($.approve===!0){let z=this.amendCall(Q),B=this.executeTool(G,Q.message.id,z,z.input,0);try{return await y(K?this.recordReceipt(K,B):B,this.controller.signal)}catch(U){if(U instanceof c)return Z.push(...U.pending),"open";throw U}}return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"denied",cause:"refused",reason:$.reason}}if("output"in $){if(Y==="approval")return X(`"${W}" is approved, not answered: the server produces its result.`);let z=G.tool.outputSchema,B=z?z.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 "${W}" 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 X(`The answer for "${W}" 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:$})}markFileRejected(Q,$,Z){for(let X of this.history){if(!X.content.some((V)=>V.type==="file"&&V.fileId===Q&&!V.providerRejected))continue;let H=this.produced.includes(X)?X:this.amend(X);if(H.content=H.content.map((V)=>V.type==="file"&&V.fileId===Q&&!V.providerRejected?{...V,providerRejected:!0}:V),H!==this.current)this.unreported.add(H)}if(!this.config.logErrors)return;let J=`[gemi/ai] agent "${this.config.name}": the provider refused file ${Q}${Z.status!==void 0?` (${Z.status})`:""}; it was left out of the request and will not be sent again: ${$}`,W={agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},fileId:Q,...Z},G=!1;try{ZQ.warning(J,W),G=!0}catch{}if(!G||Bun.env.NODE_ENV==="development")console.warn(J,W)}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 ${X9(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 b$(Q){if(Q.answeredBy==="client")return Q.inputSchema===B9?"question":"client";return Q.requiresApproval?"approval":null}function w$(Q){if(!Q||!Q.trim())return{};try{return JSON.parse(Q)}catch{return Q}}var MZ=/^[A-Za-z0-9_-]{1,64}$/;function SZ(Q,$){let Z=RZ($)?$:{filter:$},J=Z.deferred===!0,W=Q.descriptors(Z.filter);if(!Z.namespaces)return W.map((K)=>L9(Q,K,J));let G=Object.entries(Z.namespaces),X=new Set(Q.descriptors().flatMap((K)=>K.tags));for(let[K,z]of G){if(!MZ.test(K))throw Error(`toAgentTools: "${K}" is not a valid namespace name. A namespace is named by its tag and sent to the provider as a tool name is \u2014 letters, digits, "_" and "-", at most 64.`);if(typeof z?.description!=="string"||z.description.trim()==="")throw Error(`toAgentTools: the namespace "${K}" needs a description. It is what the model reads to decide whether to look inside.`);if(!X.has(K))throw Error(`toAgentTools: no tool is tagged "${K}", so its namespace would be empty.`)}let Y=new Map(G.map(([K])=>[K,[]])),H=[];for(let K of W){let z=G.find(([B])=>K.tags.includes(B))?.[0];if(z===void 0)H.push(L9(Q,K,J));else Y.get(z).push(L9(Q,K,!1))}let V=[];for(let[K,z]of G){let B=Y.get(K);if(B.length===0)continue;V.push(n.create({name:K,description:z.description,tools:B,deferred:z.deferred??J}))}return[...V,...H]}function RZ(Q){return typeof Q==="object"&&Q!==null&&(("filter"in Q)||("namespaces"in Q)||("deferred"in Q))}function L9(Q,$,Z){return m.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:$.requiresApproval,deferred:Z,execute:(J,W)=>{let G=AQ.getStore()?.req;if(!G)throw new T(`"${$.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:G},$.name,J,W)}})}function TZ(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 y$(Q,$){if(Q.size!==void 0)try{TZ(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 g$(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 C9{name;provider;settings;constructor(Q){let{name:$,provider:Z,...J}=Q;y$(J,`ImageModel "${$}"`),this.name=$,this.provider=Z,this.settings=J}static create(Q){return new C9(Q)}async generate(Q){let $=this.merge(Q);return u$(await this.provider.generate({prompt:Q.prompt,...$,signal:Q.signal}))}async edit(Q){let $=this.merge(Q);return u$(await this.provider.edit({prompt:Q.prompt,...$,images:Q.images.map((Z,J)=>g$(Z,`image-${J}`)),...Q.mask?{mask:g$(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 y$($,`ImageModel "${this.name}"`),$}}function u$(Q){return{image:new Blob([Q.bytes],{type:Q.mimeType}),mimeType:Q.mimeType,size:Q.size,usage:Q.usage}}function p(Q){return typeof process>"u"?void 0:process.env?.[Q]}var AZ="preview";function c$(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function kZ(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}function kQ(Q,$={}){return{base:(Q.baseURL??p("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let J=Q.apiKey??p("OPENAI_API_KEY");return{...J?{authorization:`Bearer ${J}`}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,maxRetries:Q.maxRetries??2}}function EZ(Q){let $=Q.baseURL??Q.endpoint??p("AZURE_OPENAI_ENDPOINT");if($)return c$($);let Z=Q.resourceName??p("AZURE_OPENAI_RESOURCE_NAME")??p("AZURE_RESOURCE_NAME");return Z?c$(`https://${Z.trim()}.cognitiveservices.azure.com`):""}function EQ(Q,$={}){let Z=Q.apiVersion??p("AZURE_OPENAI_API_VERSION")??AZ;return{base:`${EZ(Q)}${kZ(Z)}`,query:`?api-version=${encodeURIComponent(Z)}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let J=Q.apiKey??p("AZURE_OPENAI_API_KEY");return{...J?{"api-key":J}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,maxRetries:Q.maxRetries??2}}var xZ=500,p$=20000;function bZ(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 m$(Q,$){let Z=Math.min(p$,xZ*2**Q);return Math.round(Z*(0.5+$()*0.5))}function wZ(Q){return Q===429||Q===408||Q===409||Q>=500}function IZ(Q,$){return wZ(Q)&&A($).retryable}function d$(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function vZ(Q,$){return new Promise((Z,J)=>{let W=setTimeout(Z,Q);$?.addEventListener("abort",()=>{clearTimeout(W),J(d$($))},{once:!0})})}async function HQ(Q,$,Z){let J=Z.fetchImpl??((K,z)=>fetch(K,z)),W=Z.sleep??vZ,G=Z.random??Math.random,X=Z.now??Date.now,Y=Math.max(0,Z.maxRetries),H=async(K)=>{let z=Z.signal;if(!z)return await W(K);z.throwIfAborted();let B;try{await Promise.race([W(K,z),new Promise((U,F)=>{B=()=>F(d$(z)),z.addEventListener("abort",B,{once:!0})})])}finally{if(B)z.removeEventListener("abort",B)}},V;for(let K=0;K<=Y;K++){Z.signal?.throwIfAborted();let z=new AbortController,B=()=>z.abort(Z.signal?.reason);Z.signal?.addEventListener("abort",B,{once:!0});let U=!1,F=Z.timeoutMs>0?setTimeout(()=>{U=!0,z.abort()},Z.timeoutMs):void 0,D;try{D=await J(Q,{...$,signal:z.signal})}catch(N){if(F!==void 0)clearTimeout(F);if(Z.signal?.removeEventListener("abort",B),Z.signal?.aborted)throw N;if(V=U?new UQ(Z.timeoutMs):N,U&&Z.retryTimeouts===!1)throw V;if(K===Y)throw V;await H(m$(K,G));continue}if(F!==void 0)clearTimeout(F);if(D.ok)return D;Z.signal?.removeEventListener("abort",B);let j=await fZ(D),L=new h(D.status,j,D.headers.get("x-request-id")??void 0);if(K===Y||!IZ(D.status,L))throw L;let S=bZ(D.headers.get("retry-after"),X());await H(S===void 0?m$(K,G):Math.min(S,p$)),V=L}throw V??Error("Provider request failed with no response.")}async function fZ(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}var P9=300000;function q9(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 xQ extends Error{code;retryable;constructor(Q,$={}){super(Q.message,$);this.name="ImageRequestError",this.code=Q.code,this.retryable=Q.retryable}}var hZ={png:"image/png",jpeg:"image/jpeg"};function yZ(Q){let $=Number(Q?.input_tokens??0),Z=Number(Q?.output_tokens??0),J={inputTokens:$,outputTokens:Z,totalTokens:Number(Q?.total_tokens??$+Z)},W=Q?.input_tokens_details?.image_tokens;if(typeof W==="number")J.imageInputTokens=W;let G=Q?.output_tokens_details?.image_tokens;if(typeof G==="number")J.imageOutputTokens=G;return J}function gZ(Q){let $=atob(Q),Z=new Uint8Array($.length);for(let J=0;J<$.length;J++)Z[J]=$.charCodeAt(J);return Z}function uZ(Q){let Z=Q?.data?.[0]?.b64_json;if(typeof Z!=="string"||Z.length===0)throw new xQ({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:gZ(Z),mimeType:hZ[J]??`image/${J}`,size:typeof Q.size==="string"?Q.size:"",...typeof Q.background==="string"?{background:Q.background}:{},usage:yZ(Q.usage)}}async function l$(Q,$,Z,J){let W;try{W=await HQ(Q,$,{maxRetries:Z.maxRetries,timeoutMs:Z.timeoutMs,retryTimeouts:!1,signal:J.signal,fetchImpl:Z.fetchImpl})}catch(G){if(J.signal?.aborted)throw G;throw new xQ(A(G),{cause:G})}return uZ(await W.json())}async function i$(Q,$,Z={}){return await l$(Q.generationsUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify($)},Q,Z)}async function o$(Q,$,Z={}){return await l$(Q.editsUrl,{method:"POST",headers:await Q.headers(),body:$},Q,Z)}class bQ{static models(){return[]}modelName(){return this.model}async generate(Q){return await i$(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 o$(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 A(Q)}}var n$=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class O9 extends bQ{model;config;constructor(Q,$={}){super();this.model=Q,this.config=$}static model(Q,$){return new O9(Q,$)}static models(){return n$}endpoint(){return q9(kQ(this.config,{timeoutMs:P9}))}}class N9 extends bQ{model;config;constructor(Q,$={}){super();this.model=Q,this.config=$}static model(Q,$){return new N9(Q,$)}static models(){return n$}modelName(){return this.config.deployment??this.model}endpoint(){return q9(EQ(this.config,{timeoutMs:P9}))}}var a$=3;function _9(Q){let $=new Map;for(let Z of Q)for(let J of Z.content??[]){if(J.type!=="file"||!J.fileId||$.has(J.fileId))continue;$.set(J.fileId,{name:J.name,mimeType:J.mimeType})}return $}function r$(Q,$,Z=new Map){if(!($ instanceof h))return[];if($.status!==400&&$.status!==404)return[];let J=mZ($.body);if(!J)return[];let W=cZ(Q.input);if(W.length===0)return[];let G=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(J.param??"");if(G){let V=Q.input[Number(G[1])],K=S9(V)[Number(G[2])],z=K&&typeof K.file_id==="string"?K.file_id:void 0;if(z)return[z]}let X=J.message??"",Y=t$(W.map((V)=>V.fileId).filter((V)=>pZ(X,V)));if(Y.length>0)return Y;let H=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(X);if(H){let V=H[1].toLowerCase()==="image type"?"input_image":"input_file",K=H[2].toLowerCase(),z=t$(W.filter((U)=>U.type===V).map((U)=>U.fileId)),B=z.filter((U)=>(Z.get(U)?.name??"").trim().toLowerCase().endsWith(`.${K}`));if(B.length===1)return B;if(B.length===0&&z.length===1)return z}return[]}function e$(Q,$,Z=new Map){return{...Q,input:Q.input.map((J)=>{let W=S9(J);if(!W.some((G)=>s$(G,$)))return J;return{...J,content:W.map((G)=>s$(G,$)?{type:"input_text",text:M9(Z.get(String(G.file_id))?.name)}:G)}})}}function M9(Q){return`[${Q?`attachment ${JSON.stringify(Q)}`:"an attachment"} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`}function s$(Q,$){return typeof Q.file_id==="string"&&$.has(Q.file_id)}function S9(Q){let $=Q?.content;return Array.isArray($)?$:[]}function cZ(Q){let $=[];for(let Z of Q)for(let J of S9(Z))if(typeof J.file_id==="string"&&J.file_id)$.push({type:String(J.type),fileId:J.file_id});return $}function mZ(Q){if(!Q||typeof Q!=="object")return null;let $=Q,Z=$.error&&typeof $.error==="object"?$.error:Q;return{message:typeof Z.message==="string"?Z.message:void 0,param:typeof Z.param==="string"?Z.param:void 0}}function pZ(Q,$){let Z=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${Z}($|[^A-Za-z0-9_-])`).test(Q)}function t$(Q){return[...new Set(Q)]}async function*dZ(Q){let $="",Z="",J=[],W,G=()=>{if(J.length===0&&!Z)return null;let H={event:Z,data:J.join(`
|
|
15
|
+
`):void 0}async runTools(Q,$,Z){let J=[],W=[];for(let G of $){let X=this.config.registry.get(String(G.name));if(!X){this.addResult(Q,{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"error",error:{code:"tool_error",message:`There is no tool named "${String(G.name)}".`,toolCallId:G.toolCallId,retryable:!0}});continue}let Y=X.inputSchema.safeParse(G.input);if(Y.ok===!1){this.addResult(Q,{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${String(G.name)}": ${Y.errors.join(", ")}`,toolCallId:G.toolCallId,retryable:!0}});continue}G.input=Y.value;let H=w$(X.tool);if(H){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(G));continue}J.push({toolCallId:G.toolCallId,name:G.name,input:Y.value,kind:H,signature:H$(this.claimsFor(G.toolCallId,String(G.name),H,Y.value)),...this.pathPrefix.length>0?{path:[...this.pathPrefix]}:{}});continue}W.push(this.executeTool(X,Q.id,G,Y.value,Z).then(async(V)=>{this.addResult(Q,V),await this.settleShown(G.toolCallId)}).catch((V)=>{if(V instanceof m){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(G));return}J.push(...V.pending);return}}))}return await g(Promise.all(W).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,subject:this.params.subject??null}}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,W,G){let X=Q.tool.timeoutMs;if(X===void 0)return this.runToolBody(Q,$,Z,J,W,G,this.controller.signal,()=>!1);let Y=new AbortController,H=this.controller.signal,V=()=>Y.abort(H.reason);if(H.aborted)V();else H.addEventListener("abort",V,{once:!0});let K=!1,z=this.runToolBody(Q,$,Z,J,W,G,Y.signal,()=>K),B=()=>{},U=new Promise((F)=>{B=T$(X,()=>{let D=`"${String(Z.name)}" did not finish within ${V9(X)} (timeoutMs: ${X}) and was cancelled.`;Y.abort(new DOMException(D,"TimeoutError")),F({type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:{code:"timeout",message:D,toolCallId:Z.toolCallId,retryable:!0}})})});z.catch(()=>{});try{return await Promise.race([z,U])}finally{K=!0,B()}}async runToolBody(Q,$,Z,J,W,G,X,Y){let H=this.toolFiles(Z,X),V={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,toolCallId:Z.toolCallId,signal:X,step:W,depth:this.depth,resumed:G!==void 0,attachments:H.attachments,generateImage:H.generateImage,editImage:H.editImage,turn:this.toolTurn($),runAgent:this.nestedRunner($,Z,X,G),generate:(K)=>this.generateForTool(K,X,Z.toolCallId)};try{let K=Q.tool.execute(J,V),z;if(OZ(K)){let B=await K.next();while(!B.done){if(Y())throw K.return(void 0).catch(()=>{}),new x;this.emit({type:"tool-progress",toolCallId:Z.toolCallId,data:B.value}),B=await K.next()}z=B.value}else z=await K;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"ok",output:z}}catch(K){if(K instanceof x||this.controller.signal.aborted)throw new x;if(K instanceof m)throw K;let z=K instanceof A;if(!z&&this.config.logErrors)this.logToolFailure(Z,K);let B={code:"tool_error",message:K instanceof Error?K.message:String(K),toolCallId:Z.toolCallId,retryable:z?K.retryable:!0};return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:this.redact(B,{source:"tool",toolName:String(Z.name),cause:K})}}}async generateForTool(Q,$,Z){let J=this.controller.signal;return lQ({...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:(W)=>{if(this.usage=T(this.usage,W.usage),J.aborted)throw new x}})}nestedRunner(Q,$,Z,J){let W=new B9(()=>$.nested,()=>$.nested=[]);return async(G,X={})=>{let{at:Y,recorded:H,write:V}=W.next();if(H){let K=MZ(H,G,X);if(K)throw new A(`Nested run ${Y} of "${String($.name)}" ${K}. `+"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(H.finishReason!=="awaiting-input")return{runId:H.runId,agent:H.agent,messages:H.messages,finishReason:H.finishReason??"stop",usage:H.usage??M(),output:k$(H.messages),nested:H}}return this.runNested(Q,$,Z,G,X,V,H,J?.answers??[])}}async runNested(Q,$,Z,J,W,G,X,Y){let H=[...this.chain,J.name];if(this.chain.includes(J.name))throw new A(`"${J.name}" is already running further up this chain: ${H.join(" -> ")}. An agent cannot run itself, directly or through another agent.`);let V=this.depth+1;if(V>this.maxDepth)throw new A(`Nested agent runs are ${this.maxDepth} deep at most and this one would be ${V}: ${H.join(" -> ")}. Raise maxDepth on the agent at the root of the run if the tree is meant to be this deep.`);let K=W.label,z=[...this.pathPrefix,$.toolCallId],B=this.onPending==="deny"?"deny":W.onPending??"escalate",U=X!==void 0,F=U?AQ(X.messages):new Set,D=U?Y.filter((q)=>{let P=b$(q.path,z);if(P===null)return!1;return F.has(P.length>0?P[0]:q.toolCallId)}):[],j=J.stream({messages:U?X.messages:W.messages??[],turn:U?{toolResults:D}:W.prompt?{text:W.prompt}:void 0,context:this.context,attachments:this.params.attachments,body:this.params.body,signal:Z,threadId:this.params.threadId,redactError:this.params.redactError,nonces:this.params.nonces,receipts:this.params.receipts,subject:this.params.subject,instructions:W.instructions,maxOutputTokens:W.maxOutputTokens,temperature:W.temperature,runId:U?X.runId:void 0,nesting:{depth:V,maxDepth:this.maxDepth,chain:H,signingRunId:this.signingRunId,signingPath:z,onPending:B}}),L=[],S=(q)=>this.emit({type:"nested-event",toolCallId:$.toolCallId,runId:j.runId,agent:J.name,label:K,event:q}),O=(async()=>{for await(let q of j){if(q.type==="awaiting-input")L=q.pending;if(S(q),q.type==="run-start"&&!U)for(let P of W.messages??[])S({type:"message",message:P});if(q.type==="error")this.emit({type:"error",error:q.error,nested:{toolCallId:$.toolCallId,runId:j.runId,agent:J.name}})}})(),v=(async()=>{let q=await j.result();await O;let P=U?A$(X.messages,q.messages):A$(W.messages??[],q.messages),_={runId:j.runId,agent:J.name,label:K,messages:P,finishReason:q.finishReason,usage:U?T(X.usage??M(),q.usage):q.usage,...q.finishReason==="awaiting-input"?{signature:D$({runId:this.signingRunId,path:z,nestedRunId:j.runId,open:[...AQ(P)],input:$.input,subject:this.params.subject??null})}:{}};return G(_),this.usage=T(this.usage,q.usage),{result:q,record:_}})(),k=v.then(()=>{return},()=>{return});this.nestedSettling.add(k);let R,N;try{({result:R,record:N}=await v)}finally{this.nestedSettling.delete(k)}if(this.controller.signal.aborted)throw new x;if(R.finishReason==="awaiting-input"){if(L.length===0)throw new A(`"${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 m({pending:L,path:z,nested:N})}return{runId:N.runId,agent:J.name,messages:N.messages,finishReason:R.finishReason,usage:N.usage??M(),output:R.output??k$(N.messages),...R.error?{error:R.error}:{},nested:N}}addResult(Q,$){Q.content.push($),this.emit({type:"tool-result",messageId:Q.id,part:$})}toolFiles(Q,$){let Z=this.params.attachments??null,J=new B9(()=>Q.attachments,()=>Q.attachments=[],()=>({failed:!0})),W=()=>{if(!Z)throw new n("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},G=async(V,K,z)=>{let B=W(),U=K.mimeType||V.type||"",F=K.name??(V instanceof File?V.name:"attachment"),D;if(K.showModel){let L=this.config.provider;if(!L.capabilities.fileInput)throw new A(`"${String(Q.name)}" asked to show a file to ${L.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.`);D=await L.upload(new File([V],F,{type:U||void 0}))}return{attachment:await B.put(V,{name:F,mimeType:U,fileId:D}),...z?{generated:z}:{},...D?{shown:{fileId:D,messageId:`msg_${crypto.randomUUID()}`,createdAt:new Date().toISOString()}}:{}}},X=(V,K,z)=>{let B=V.generated?"image":"put";if(B===K)return;throw new A(`Attachment ${z} of "${String(Q.name)}" was ${B==="image"?"a generated image":"a stored file"} on the first attempt and is ${K==="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.`)},Y=async(V,K,z)=>{let{at:B,recorded:U,write:F}=J.next();if(U&&"attachment"in U){if(X(U,"image",B),U.shown)this.queueShown(Q.toolCallId,U);return{attachment:U.attachment,size:U.generated.size,mimeType:U.attachment.mimeType,usage:U.generated.usage}}let D=await z();this.usage=T(this.usage,D.usage);let j=D.mimeType==="image/jpeg"?"jpg":"png",L=await G(D.image,{name:K.name??`${V.name}.${j}`,mimeType:D.mimeType,...K.showModel?{showModel:!0}:{}},{size:D.size,usage:D.usage});if(F(L),L.shown)this.queueShown(Q.toolCallId,L);return{attachment:L.attachment,size:D.size,mimeType:D.mimeType,usage:D.usage}},H=async(V)=>typeof V==="string"?await W().file(V):V;return{generateImage:(V,K)=>Y(V,K,()=>V.generate({...K,signal:$})),editImage:(V,K)=>Y(V,K,async()=>{let{images:z,mask:B,...U}=K;return await V.edit({...U,images:await Promise.all(z.map(H)),...B?{mask:await H(B)}:{},signal:$})}),attachments:{get:(V)=>W().get(V),read:(V)=>W().read(V),file:(V)=>W().file(V),put:async(V,K={})=>{let{at:z,recorded:B,write:U}=J.next();if(B&&"attachment"in B){X(B,"put",z);let D=_Z(B,V,K);if(D)throw new A(`Attachment ${z} of "${String(Q.name)}" ${D}. `+"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(B.shown)this.queueShown(Q.toolCallId,B);return B.attachment}let F=await G(V,K);if(U(F),F.shown)this.queueShown(Q.toolCallId,F);return F.attachment}}}}toolTurn(Q){let $=this.history.findIndex((G)=>G.id===Q),Z=c(this.history),J;for(let G=$-1;G>=0;G--){let X=this.history[G];if(X.role!=="user"||Z.has(X.id))continue;J=X;break}let W=[];for(let G of J?.content??[]){if(G.type!=="file")continue;let X=G.attachmentId;if(typeof X!=="string"||!X.startsWith(f))continue;if(!W.includes(X))W.push(X)}return Object.freeze({attachments:Object.freeze(W)})}queueShown(Q,$){let Z=$.shown;if(!Z)return;let J=this.shownQueue.get(Q)??[];if(J.some((W)=>W.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((G)=>G!==Q),Z=c($),J=[];for(let G of $){if(!Z.has(G.id))continue;for(let X of G.content)if(X.type==="file")J.push(X)}if(J.length<=x$)return $;let W=new Set(J.slice(0,J.length-x$));return $.map((G)=>{if(!G.content.some((X)=>X.type==="file"&&W.has(X)))return G;return{...G,content:G.content.map((X)=>X.type==="file"&&W.has(X)?{type:"text",text:`[A ${X.mimeType||"file"} produced by a tool (attachment ${X.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.]`}:X)}})}async ingestTurn(){let Q=this.params.turn,$=this.openCalls(),Z=[];if($.length>0){let J=new Set,W=new Set,G=new Map;for(let X of Q?.toolResults??[]){let Y=`${(X.path??[]).join("/")}#${X.toolCallId}`;if(W.has(Y))continue;W.add(Y);let H=(B)=>this.emit({type:"error",error:{code:"invalid_tool_result",message:B,toolCallId:X.toolCallId,retryable:!1}}),V=b$(X.path,this.pathPrefix);if(V===null){H(`The answer for "${X.toolCallId}" is addressed to a tool call this run is not inside.`);continue}if(V.length>0){let B=V[0],U=$.find((j)=>j.call.toolCallId===B);if(!U){H(`No pending tool call with id "${B}" to deliver a nested answer to.`);continue}let F=this.parkedBelow(U.call,V,X.toolCallId);if(F.ok===!1){let j=`The answer for "${X.toolCallId}" is addressed under "${B}", which`;H(F.reason==="unparked"?`${j} has no sub-agent run waiting on that question.`:F.reason==="expired"?`${j} parked a sub-agent run that has since expired. Ask again.`:`${j} carries a record of a parked sub-agent run the server did not sign.`);continue}let D=G.get(B);if(!D){if(!await this.spend(C$,F.signature)){H(`The answer for "${X.toolCallId}" is addressed under "${B}", which has already been re-entered on that record. Ask again.`);continue}D=[],G.set(B,D),J.add(B)}D.push(X);continue}let K=$.find((B)=>B.call.toolCallId===X.toolCallId);if(!K){H(`No pending tool call with id "${X.toolCallId}".`);continue}let z=await this.resolveAnswer(K,X,Z);if(z===null)continue;if(J.add(X.toolCallId),z!=="open")this.attachToHistory(K,z),await this.settleShown(X.toolCallId)}for(let[X,Y]of G){let H=$.find((K)=>K.call.toolCallId===X),V=await this.reenter(H,Y,Z);if(V)this.attachToHistory(H,V),await this.settleShown(X)}for(let X of $){if(J.has(X.call.toolCallId))continue;this.attachToHistory(X,{type:"tool-result",toolCallId:X.call.toolCallId,name:X.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((W)=>({type:"file",...W.fileId?{fileId:W.fileId}:{},name:W.name,mimeType:W.mimeType,...W.attachmentId?{attachmentId:W.attachmentId}:{}}))],createdAt:new Date().toISOString(),finishReason:"stop"};if(this.history.push(J),this.produced.push(J),this.depth>0)this.emit({type:"message",message:J});else if(Q.localId)this.emit({type:"message-id",localId:Q.localId,messageId:J.id,message:J});if(await this.report(J),this.params.onTurn)try{await this.params.onTurn(J)}catch{}}return Z}parkedBelow(Q,$,Z){let J=$.length>1?$[1]:Z,W=[...this.pathPrefix,Q.toolCallId],G=(Q.nested??[]).find((Y)=>Y.finishReason==="awaiting-input"&&AQ(Y.messages).has(J));if(!G)return{ok:!1,reason:"unparked"};if(typeof G.signature!=="string")return{ok:!1,reason:"unsigned"};let X=F$(G.signature,{path:W,nestedRunId:G.runId,open:[...AQ(G.messages)],input:Q.input,subject:this.params.subject??null});if(X.ok===!1)return{ok:!1,reason:X.reason==="expired"?"expired":"unsigned"};return{ok:!0,signature:G.signature}}async reenter(Q,$,Z){let J=String(Q.call.name),W=this.config.registry.get(J);if(!W||!W.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 G=W.inputSchema.safeParse(Q.call.input);if(G.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}": ${G.errors.join(", ")}`,toolCallId:Q.call.toolCallId,retryable:!0}};let X=this.amendCall(Q);X.input=G.value;try{return await g(this.executeTool(W,Q.message.id,X,G.value,0,{answers:$}),this.controller.signal)}catch(Y){if(Y instanceof m)return Z.push(...Y.pending),null;throw Y}}amendCall(Q){let $=this.amend(Q.message),Z=$.content.indexOf(Q.call),J={...Q.call,nested:(Q.call.nested??[]).map((W)=>({...W})),...Q.call.attachments?{attachments:Q.call.attachments.map((W)=>({...W}))}:{}};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 spend(Q,$){try{return await Q($,this.params.nonces??o)}catch(Z){return this.writeLog(`[gemi/ai] agent "${this.config.name}" could not spend a nonce`,{error:Z}),!1}}async recordReceipt(Q,$){let Z=await $;try{await Q.store.complete(Q.id,Z,Q.expiresAt)}catch(J){this.writeLog(`[gemi/ai] agent "${this.config.name}" could not record a tool receipt`,{error:J})}return Z}async resolveAnswer(Q,$,Z){let J=Q.call,W=String(J.name),G=this.config.registry.get(W),X=(z)=>{return this.emit({type:"error",error:{code:"invalid_tool_result",message:z,toolCallId:J.toolCallId,retryable:!1}}),null};if(!G)return X(`The tool "${W}" no longer exists, so its answer cannot be checked.`);let Y=w$(G.tool);if(!Y)return X(`"${W}" is a server tool with no pending question.`);if(typeof $.signature!=="string"||$.signature.length===0)return X(`The answer for "${W}" carried no signature.`);let H=aQ($.signature);if(!H)return X(`The signature for "${W}" is malformed.`);let V=K$($.signature,{...this.claimsFor(J.toolCallId,W,Y,J.input),runId:H.runId});if(V.ok===!1)return X(V.reason==="expired"?`The approval for "${W}" has expired. Ask again.`:`The answer for "${W}" does not match the call the server made.`);let K;if(this.params.receipts&&Y==="approval"&&"approve"in $&&$.approve===!0){let z=this.params.receipts,B=j$(this.config.name,{...this.claimsFor(J.toolCallId,W,Y,J.input),runId:H.runId}),U;try{U=await z.claim(B,H.expiresAt)}catch(F){return this.writeLog(`[gemi/ai] agent "${this.config.name}" could not claim a tool receipt`,{error:F}),X(`The approval for "${W}" could not be checked. Ask again.`)}if(U.status==="replay")return{...U.result,toolCallId:J.toolCallId,name:J.name};if(U.status==="blocked")return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"error",error:{code:"tool_error",message:`"${W}" was already approved and started, and its result is not recorded yet: it is still running, or it stopped before finishing. It was not run again.`,toolCallId:J.toolCallId,retryable:!1}};K={store:z,id:B,expiresAt:H.expiresAt}}if(!await this.spend(L$,$.signature))return await K?.store.release(K.id).catch((z)=>{this.writeLog(`[gemi/ai] agent "${this.config.name}" could not release a tool receipt`,{error:z})}),X(`The answer for "${W}" has already been used. Ask again.`);if("approve"in $){if(Y!=="approval")return X(`"${W}" is answered by the client, not approved.`);if($.approve===!0){let z=this.amendCall(Q),B=this.executeTool(G,Q.message.id,z,z.input,0);try{return await g(K?this.recordReceipt(K,B):B,this.controller.signal)}catch(U){if(U instanceof m)return Z.push(...U.pending),"open";throw U}}return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"denied",cause:"refused",reason:$.reason}}if("output"in $){if(Y==="approval")return X(`"${W}" is approved, not answered: the server produces its result.`);let z=G.tool.outputSchema,B=z?z.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 "${W}" 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 X(`The answer for "${W}" 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:$})}markFileRejected(Q,$,Z){for(let X of this.history){if(!X.content.some((V)=>V.type==="file"&&V.fileId===Q&&!V.providerRejected))continue;let H=this.produced.includes(X)?X:this.amend(X);if(H.content=H.content.map((V)=>V.type==="file"&&V.fileId===Q&&!V.providerRejected?{...V,providerRejected:!0}:V),H!==this.current)this.unreported.add(H)}if(!this.config.logErrors)return;let J=`[gemi/ai] agent "${this.config.name}": the provider refused file ${Q}${Z.status!==void 0?` (${Z.status})`:""}; it was left out of the request and will not be sent again: ${$}`,W={agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},fileId:Q,...Z},G=!1;try{JQ.warning(J,W),G=!0}catch{}if(!G||Bun.env.NODE_ENV==="development")console.warn(J,W)}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 ${V9(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 w$(Q){if(Q.answeredBy==="client")return Q.inputSchema===z9?"question":"client";return Q.requiresApproval?"approval":null}function I$(Q){if(!Q||!Q.trim())return{};try{return JSON.parse(Q)}catch{return Q}}var SZ=/^[A-Za-z0-9_-]{1,64}$/;function RZ(Q,$){let Z=TZ($)?$:{filter:$},J=Z.deferred===!0,W=Q.descriptors(Z.filter);if(!Z.namespaces)return W.map((K)=>C9(Q,K,J));let G=Object.entries(Z.namespaces),X=new Set(Q.descriptors().flatMap((K)=>K.tags));for(let[K,z]of G){if(!SZ.test(K))throw Error(`toAgentTools: "${K}" is not a valid namespace name. A namespace is named by its tag and sent to the provider as a tool name is \u2014 letters, digits, "_" and "-", at most 64.`);if(typeof z?.description!=="string"||z.description.trim()==="")throw Error(`toAgentTools: the namespace "${K}" needs a description. It is what the model reads to decide whether to look inside.`);if(!X.has(K))throw Error(`toAgentTools: no tool is tagged "${K}", so its namespace would be empty.`)}let Y=new Map(G.map(([K])=>[K,[]])),H=[];for(let K of W){let z=G.find(([B])=>K.tags.includes(B))?.[0];if(z===void 0)H.push(C9(Q,K,J));else Y.get(z).push(C9(Q,K,!1))}let V=[];for(let[K,z]of G){let B=Y.get(K);if(B.length===0)continue;V.push(s.create({name:K,description:z.description,tools:B,deferred:z.deferred??J}))}return[...V,...H]}function TZ(Q){return typeof Q==="object"&&Q!==null&&(("filter"in Q)||("namespaces"in Q)||("deferred"in Q))}function C9(Q,$,Z){return p.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:$.requiresApproval,deferred:Z,execute:(J,W)=>{let G=kQ.getStore()?.req;if(!G)throw new A(`"${$.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:G},$.name,J,W)}})}function AZ(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 g$(Q,$){if(Q.size!==void 0)try{AZ(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 u$(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 P9{name;provider;settings;constructor(Q){let{name:$,provider:Z,...J}=Q;g$(J,`ImageModel "${$}"`),this.name=$,this.provider=Z,this.settings=J}static create(Q){return new P9(Q)}async generate(Q){let $=this.merge(Q);return c$(await this.provider.generate({prompt:Q.prompt,...$,signal:Q.signal}))}async edit(Q){let $=this.merge(Q);return c$(await this.provider.edit({prompt:Q.prompt,...$,images:Q.images.map((Z,J)=>u$(Z,`image-${J}`)),...Q.mask?{mask:u$(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 g$($,`ImageModel "${this.name}"`),$}}function c$(Q){return{image:new Blob([Q.bytes],{type:Q.mimeType}),mimeType:Q.mimeType,size:Q.size,usage:Q.usage}}function d(Q){return typeof process>"u"?void 0:process.env?.[Q]}var kZ="preview";function m$(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function EZ(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}function EQ(Q,$={}){return{base:(Q.baseURL??d("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let J=Q.apiKey??d("OPENAI_API_KEY");return{...J?{authorization:`Bearer ${J}`}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,maxRetries:Q.maxRetries??2}}function xZ(Q){let $=Q.baseURL??Q.endpoint??d("AZURE_OPENAI_ENDPOINT");if($)return m$($);let Z=Q.resourceName??d("AZURE_OPENAI_RESOURCE_NAME")??d("AZURE_RESOURCE_NAME");return Z?m$(`https://${Z.trim()}.cognitiveservices.azure.com`):""}function xQ(Q,$={}){let Z=Q.apiVersion??d("AZURE_OPENAI_API_VERSION")??kZ;return{base:`${xZ(Q)}${EZ(Z)}`,query:`?api-version=${encodeURIComponent(Z)}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let J=Q.apiKey??d("AZURE_OPENAI_API_KEY");return{...J?{"api-key":J}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,maxRetries:Q.maxRetries??2}}var bZ=500,d$=20000;function wZ(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 p$(Q,$){let Z=Math.min(d$,bZ*2**Q);return Math.round(Z*(0.5+$()*0.5))}function IZ(Q){return Q===429||Q===408||Q===409||Q>=500}function vZ(Q,$){return IZ(Q)&&E($).retryable}function l$(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function fZ(Q,$){return new Promise((Z,J)=>{let W=setTimeout(Z,Q);$?.addEventListener("abort",()=>{clearTimeout(W),J(l$($))},{once:!0})})}async function KQ(Q,$,Z){let J=Z.fetchImpl??((K,z)=>fetch(K,z)),W=Z.sleep??fZ,G=Z.random??Math.random,X=Z.now??Date.now,Y=Math.max(0,Z.maxRetries),H=async(K)=>{let z=Z.signal;if(!z)return await W(K);z.throwIfAborted();let B;try{await Promise.race([W(K,z),new Promise((U,F)=>{B=()=>F(l$(z)),z.addEventListener("abort",B,{once:!0})})])}finally{if(B)z.removeEventListener("abort",B)}},V;for(let K=0;K<=Y;K++){Z.signal?.throwIfAborted();let z=new AbortController,B=()=>z.abort(Z.signal?.reason);Z.signal?.addEventListener("abort",B,{once:!0});let U=!1,F=Z.timeoutMs>0?setTimeout(()=>{U=!0,z.abort()},Z.timeoutMs):void 0,D;try{D=await J(Q,{...$,signal:z.signal})}catch(O){if(F!==void 0)clearTimeout(F);if(Z.signal?.removeEventListener("abort",B),Z.signal?.aborted)throw O;if(V=U?new DQ(Z.timeoutMs):O,U&&Z.retryTimeouts===!1)throw V;if(K===Y)throw V;await H(p$(K,G));continue}if(F!==void 0)clearTimeout(F);if(D.ok)return D;Z.signal?.removeEventListener("abort",B);let j=await hZ(D),L=new y(D.status,j,D.headers.get("x-request-id")??void 0);if(K===Y||!vZ(D.status,L))throw L;let S=wZ(D.headers.get("retry-after"),X());await H(S===void 0?p$(K,G):Math.min(S,d$)),V=L}throw V??Error("Provider request failed with no response.")}async function hZ(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}var q9=300000;function O9(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 bQ extends Error{code;retryable;constructor(Q,$={}){super(Q.message,$);this.name="ImageRequestError",this.code=Q.code,this.retryable=Q.retryable}}var yZ={png:"image/png",jpeg:"image/jpeg"};function gZ(Q){let $=Number(Q?.input_tokens??0),Z=Number(Q?.output_tokens??0),J={inputTokens:$,outputTokens:Z,totalTokens:Number(Q?.total_tokens??$+Z)},W=Q?.input_tokens_details?.image_tokens;if(typeof W==="number")J.imageInputTokens=W;let G=Q?.output_tokens_details?.image_tokens;if(typeof G==="number")J.imageOutputTokens=G;return J}function uZ(Q){let $=atob(Q),Z=new Uint8Array($.length);for(let J=0;J<$.length;J++)Z[J]=$.charCodeAt(J);return Z}function cZ(Q){let Z=Q?.data?.[0]?.b64_json;if(typeof Z!=="string"||Z.length===0)throw new bQ({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:uZ(Z),mimeType:yZ[J]??`image/${J}`,size:typeof Q.size==="string"?Q.size:"",...typeof Q.background==="string"?{background:Q.background}:{},usage:gZ(Q.usage)}}async function i$(Q,$,Z,J){let W;try{W=await KQ(Q,$,{maxRetries:Z.maxRetries,timeoutMs:Z.timeoutMs,retryTimeouts:!1,signal:J.signal,fetchImpl:Z.fetchImpl})}catch(G){if(J.signal?.aborted)throw G;throw new bQ(E(G),{cause:G})}return cZ(await W.json())}async function o$(Q,$,Z={}){return await i$(Q.generationsUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify($)},Q,Z)}async function n$(Q,$,Z={}){return await i$(Q.editsUrl,{method:"POST",headers:await Q.headers(),body:$},Q,Z)}class wQ{static models(){return[]}modelName(){return this.model}async generate(Q){return await o$(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 n$(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 E(Q)}}var s$=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class N9 extends wQ{model;config;constructor(Q,$={}){super();this.model=Q,this.config=$}static model(Q,$){return new N9(Q,$)}static models(){return s$}endpoint(){return O9(EQ(this.config,{timeoutMs:q9}))}}class _9 extends wQ{model;config;constructor(Q,$={}){super();this.model=Q,this.config=$}static model(Q,$){return new _9(Q,$)}static models(){return s$}modelName(){return this.config.deployment??this.model}endpoint(){return O9(xQ(this.config,{timeoutMs:q9}))}}var r$=3;function M9(Q){let $=new Map;for(let Z of Q)for(let J of Z.content??[]){if(J.type!=="file"||!J.fileId||$.has(J.fileId))continue;$.set(J.fileId,{name:J.name,mimeType:J.mimeType})}return $}function e$(Q,$,Z=new Map){if(!($ instanceof y))return[];if($.status!==400&&$.status!==404)return[];let J=pZ($.body);if(!J)return[];let W=mZ(Q.input);if(W.length===0)return[];let G=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(J.param??"");if(G){let V=Q.input[Number(G[1])],K=R9(V)[Number(G[2])],z=K&&typeof K.file_id==="string"?K.file_id:void 0;if(z)return[z]}let X=J.message??"",Y=a$(W.map((V)=>V.fileId).filter((V)=>dZ(X,V)));if(Y.length>0)return Y;let H=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(X);if(H){let V=H[1].toLowerCase()==="image type"?"input_image":"input_file",K=H[2].toLowerCase(),z=a$(W.filter((U)=>U.type===V).map((U)=>U.fileId)),B=z.filter((U)=>(Z.get(U)?.name??"").trim().toLowerCase().endsWith(`.${K}`));if(B.length===1)return B;if(B.length===0&&z.length===1)return z}return[]}function Q3(Q,$,Z=new Map){return{...Q,input:Q.input.map((J)=>{let W=R9(J);if(!W.some((G)=>t$(G,$)))return J;return{...J,content:W.map((G)=>t$(G,$)?{type:"input_text",text:S9(Z.get(String(G.file_id))?.name)}:G)}})}}function S9(Q){return`[${Q?`attachment ${JSON.stringify(Q)}`:"an attachment"} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`}function t$(Q,$){return typeof Q.file_id==="string"&&$.has(Q.file_id)}function R9(Q){let $=Q?.content;return Array.isArray($)?$:[]}function mZ(Q){let $=[];for(let Z of Q)for(let J of R9(Z))if(typeof J.file_id==="string"&&J.file_id)$.push({type:String(J.type),fileId:J.file_id});return $}function pZ(Q){if(!Q||typeof Q!=="object")return null;let $=Q,Z=$.error&&typeof $.error==="object"?$.error:Q;return{message:typeof Z.message==="string"?Z.message:void 0,param:typeof Z.param==="string"?Z.param:void 0}}function dZ(Q,$){let Z=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${Z}($|[^A-Za-z0-9_-])`).test(Q)}function a$(Q){return[...new Set(Q)]}async function*lZ(Q){let $="",Z="",J=[],W,G=()=>{if(J.length===0&&!Z)return null;let H={event:Z,data:J.join(`
|
|
16
16
|
`),id:W};return Z="",J=[],W=void 0,H.data?H:null},X=(H)=>{let V=H.endsWith("\r")?H.slice(0,-1):H;if(V==="")return G();if(V.startsWith(":"))return null;let K=V.indexOf(":"),z=K===-1?V:V.slice(0,K),B=K===-1?"":V.slice(K+1);if(B.startsWith(" "))B=B.slice(1);if(z==="event")Z=B;else if(z==="data")J.push(B);else if(z==="id")W=B;return null};for await(let H of Q){$+=H;let V=$.indexOf(`
|
|
17
17
|
`);while(V!==-1){let K=$.slice(0,V);$=$.slice(V+1);let z=X(K);if(z)yield z;V=$.indexOf(`
|
|
18
|
-
`)}}if($.length>0){let H=X($);if(H)yield H}let Y=G();if(Y)yield Y}async function*Q3(Q,$={}){let Z=new Map,J=new Set,W,G=!1,X,Y=(H,V)=>({type:"finish",reason:H,usage:V,...X?{model:X}:{}});for await(let H of dZ(Q)){if(H.data==="[DONE]")break;let V;try{V=JSON.parse(H.data)}catch{continue}let K=typeof V.type==="string"?V.type:H.event,z=V.response?.model;if(typeof z==="string"&&z)X=z;switch(K){case"response.output_text.delta":{let B=String(V.delta??"");if(!B)break;yield $.structuredOutput?{type:"output-delta",delta:B}:{type:"text-delta",delta:B};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let B=String(V.delta??"");if(!B)break;yield{type:"reasoning-delta",delta:B,id:V.item_id};break}case"response.output_item.added":{let B=V.item;if(!B)break;if(B.type==="function_call"){let U=String(B.id??V.item_id??B.call_id??"");Z.set(U,{callId:String(B.call_id??U),name:String(B.name??""),namespace:typeof B.namespace==="string"&&B.namespace?B.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let B=Z.get(String(V.item_id??""));if(!B)break;let U=String(V.delta??"");if(!U)break;yield{type:"tool-call-delta",toolCallId:B.callId,name:B.name,argsDelta:U,...B.namespace?{namespace:B.namespace}:{}};break}case"response.function_call_arguments.done":{let B=String(V.item_id??""),U=Z.get(B);if(!U)break;U.done=!0,yield{type:"tool-call",toolCallId:U.callId,name:U.name,args:String(V.arguments??""),...U.namespace?{namespace:U.namespace}:{}};break}case"response.output_item.done":{let B=V.item;if(!B)break;if(B.type==="function_call"){let U=String(B.id??V.item_id??B.call_id??""),F=Z.get(U);if(F?.done)break;let D=(typeof B.namespace==="string"?B.namespace:"")||F?.namespace;if(yield{type:"tool-call",toolCallId:String(B.call_id??U),name:String(B.name??F?.name??""),args:String(B.arguments??""),...D?{namespace:D}:{}},F)F.done=!0;break}if(B.type==="tool_search_call"||B.type==="tool_search_output"){if(B.type==="tool_search_call"&&B.arguments!==void 0)W=B.arguments;let U=lZ(B);if(U.loaded.length===0&&U.namespaces.length===0)break;let F=String(B.tool_search_call_id??B.id??"");if(J.has(F))break;J.add(F);let D=W;W=void 0,yield{type:"tool-search",...U,...D!==void 0&&D!==null?{arguments:D}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(V.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{G=!0,yield Y("stop",R9(V.response?.usage));break}case"response.incomplete":{G=!0;let B=R9(V.response?.usage),U=V.response?.incomplete_details?.reason;if(U==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:iZ(V.response?.content_filters),retryable:!1}},yield Y("error",B);break}yield Y(U==="max_output_tokens"?"length":"stop",B);break}case"response.failed":case"error":{G=!0;let B=V.response?.error??V.error??V;yield{type:"error",error:oZ(B)},yield Y("error",R9(V.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 Y("error",s())}function lZ(Q){let $=[],Z=[];return $3(Q.results??Q.tools??Q.loaded??Q.output,$,Z,0),{loaded:T9($),namespaces:T9(Z)}}function $3(Q,$,Z,J){if(!Array.isArray(Q)||J>4)return;for(let W of Q){if(typeof W==="string"){$.push(W);continue}if(!W||typeof W!=="object")continue;let G=W,X=typeof G.name==="string"?G.name:typeof G.tool_name==="string"?G.tool_name:"",Y=G.tools??G.functions;if(Array.isArray(Y)){if(X)Z.push(X);$3(Y,$,Z,J+1);continue}if(X)$.push(X)}}function T9(Q){return Q.filter(($,Z)=>Q.indexOf($)===Z)}function iZ(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 W=J,G=W.content_filter_results;if(!G||typeof G!=="object")continue;for(let[X,Y]of Object.entries(G))if(Y&&typeof Y==="object"&&Y.filtered===!0)Z.push(`${X} (${String(W.source_type??"unknown")})`)}return Z.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${T9(Z).join(", ")}.`}function oZ(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 s(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function R9(Q){if(!Q)return s();let $=Number(Q.input_tokens??0),Z=Number(Q.output_tokens??0),J={inputTokens:$,outputTokens:Z,totalTokens:Number(Q.total_tokens??$+Z)},W=Q.output_tokens_details?.reasoning_tokens;if(typeof W==="number")J.reasoningTokens=W;let G=Q.input_tokens_details?.cached_tokens;if(typeof G==="number")J.cachedInputTokens=G;return J}async function*Z3(Q){if(!Q)return;let $=Q.getReader(),Z=new TextDecoder;try{while(!0){let{done:W,value:G}=await $.read();if(W)break;if(G)yield Z.decode(G,{stream:!0})}let J=Z.decode();if(J)yield J}finally{$.releaseLock()}}function A9(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*k9(Q,$,Z){let J,W=$,G=new Set;for(let X=0;J===void 0;X++)try{J=await HQ(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify(W)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(Y){let H=X<a$?r$(W,Y,Z.files).filter((K)=>!G.has(K)):[];if(H.length>0){let K=A(Y).message;for(let z of H)G.add(z),yield{type:"file-rejected",fileId:z,message:K,...x(Y)};W=e$(W,new Set(H),Z.files);continue}let V=A(Y);if(V.code!=="aborted")yield{type:"error",error:V,...x(Y)};yield{type:"finish",reason:V.code==="aborted"?"aborted":"error",usage:s()};return}try{yield*Q3(Z3(J.body),{structuredOutput:Z.structuredOutput})}catch(X){let Y=A(X);if(Y.code==="aborted"){yield{type:"finish",reason:"aborted",usage:s()};return}yield{type:"error",error:Y},yield{type:"finish",reason:"error",usage:s()}}}async function E9(Q,$,Z="user_data"){let J=new FormData;J.set("purpose",Z),J.set("file",$);let G=await(await HQ(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:J},{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 x9(Q){let $=nZ(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Z=sZ($);if(Z?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Z.major>1,toolSearch:J3(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:J3(Z)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function J3(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function nZ(Q){return Q.trim().toLowerCase()}function sZ(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 w9(Q,$){let{capabilities:Z}=$,J={model:$.model,input:tZ(Q.messages,Z,Q.tools),stream:!0};if(Q.systemPrompt)J.instructions=Q.systemPrompt;let W=X1(Q.tools,Z);if(W.length>0){if(J.tools=W,!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 tZ(Q,$,Z){let J=[],W=new Map;if($.toolSearch){for(let G of Z??[])if(wQ(G))W.set(G.name,G)}for(let G of Q){let X=G.role,Y=[],H=()=>{if(Y.length===0)return;J.push({type:"message",role:X,content:Y}),Y=[]};for(let V of G.content??[])switch(V.type){case"text":{if(!V.text)break;Y.push(t(X,V.text));break}case"output":{if(V.partial)break;Y.push(t(X,JSON.stringify(V.value)));break}case"file":{if(X==="assistant")break;let K=eZ(V);if(!$.fileInput){if(K)Y.push(t(X,b9(V,!1)));break}if(V.fileId?.startsWith(f))throw Error(`FilePart.fileId holds a gemi attachment id (${V.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!V.fileId&&!K)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.providerRejected){if(K)Y.push(t(X,b9(V,!1)));Y.push(t(X,M9(V.name)));break}if(K)Y.push(t(X,b9(V,!!V.fileId)));if(V.fileId)Y.push(Q1(V));break}case"reasoning":{H();let K=J1(V);if(K)J.push(K);break}case"tool-call":{if(V.partial)break;if(H(),$.toolSearch&&Array.isArray(V.toolSearches))for(let z of V.toolSearches)J.push(...G1(z,Z??[]));let K={type:"function_call",call_id:V.toolCallId,name:String(V.name),arguments:JSON.stringify(V.input??{})};if(V.namespace&&W.has(V.namespace))K.namespace=V.namespace;J.push(K);break}case"tool-result":{H(),J.push({type:"function_call_output",call_id:V.toolCallId,output:W1(V)});break}}H()}return rZ(J)}var aZ="No result was recorded for this tool call. Assume it did not complete.";function rZ(Q){let $=new Set,Z=new Set,J=[];for(let G of Q){if(G.type==="function_call"){let X=String(G.call_id);if($.has(X))continue;$.add(X)}else if(G.type==="function_call_output"){let X=String(G.call_id);if(!$.has(X)||Z.has(X))continue;Z.add(X)}J.push(G)}if(Z.size===$.size)return J;let W=[];for(let G of J){if(W.push(G),G.type!=="function_call")continue;let X=String(G.call_id);if(Z.has(X))continue;Z.add(X),W.push({type:"function_call_output",call_id:X,output:aZ})}return W}function t(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function eZ(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(f)?$:void 0}function b9(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 Q1(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":$1(Q.name))?"input_image":"input_file",file_id:Q.fileId}}function $1(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&Z1.has($[1])}var Z1=new Set(["jpeg","jpg","png","gif","webp"]);function J1(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function W1(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 G1(Q,$){let Z=new Set(W3(Q?.loaded)),J=W3(Q?.namespaces),W=new Set(J),G=[];for(let Y of $)if(wQ(Y)){if(!W.has(Y.name))continue;let H=Y.tools.filter((V)=>Z.size===0||Z.has(V.name));if(H.length===0)continue;G.push({type:"namespace",name:Y.name,description:Y.description,tools:H.map((V)=>a(V,!0))})}else if(Y.deferred&&Z.has(Y.name))G.push(a(Y,!0));if(G.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:Q.arguments&&typeof Q.arguments==="object"?Q.arguments:{paths:J.length>0?J:[...Z]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:G}]}function W3(Q){return Array.isArray(Q)?Q.filter(($)=>typeof $==="string"):[]}function wQ(Q){return Array.isArray(Q.tools)}function X1(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let W=[];for(let G of Q)if(wQ(G))for(let X of G.tools)W.push(a(X,!1));else W.push(a(G,!1));return W}let Z=[],J=!1;for(let W of Q)if(wQ(W)){let G=W.tools.map((X)=>{if(X.deferred)J=!0;return a(X,!0)});Z.push({type:"namespace",name:W.name,description:W.description,tools:G})}else{if(W.deferred)J=!0;Z.push(a(W,!0))}if(J)Z.push({type:"tool_search"});return Z}function a(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 r{static models(){return[]}normalizeError(Q){return A(Q)}}var G3=["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 I9 extends r{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=x9(Q),this.config=$}static model(Q,$){return new I9(Q,$)}static models(){return G3}stream(Q){let $=w9(Q,{model:this.model,capabilities:this.capabilities});return k9(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output),files:_9(Q.messages)})}upload(Q){return E9(this.endpoint(),Q)}endpoint(){return A9(kQ(this.config))}}class v9 extends r{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=x9(Q),this.config=$}static model(Q,$){return new v9(Q,$)}static models(){return G3}stream(Q){let $=w9(Q,{model:this.deployment(),capabilities:this.capabilities});return k9(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output),files:_9(Q.messages)})}upload(Q){return E9(this.endpoint(),Q,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return A9(EQ(this.config))}}class IQ{now;entries=new Map;constructor(Q=Date.now){this.now=Q}allow(Q,$){let Z=this.entries.get(Q);if(Z?.openUntil===void 0)return!0;let J=this.now();if(J<Z.openUntil)return!1;if(Z.probeUntil!==void 0&&J<Z.probeUntil)return!1;return Z.probeUntil=J+$.cooldownMs,!0}record(Q,$,Z){let J=this.entries.get(Q)??{failures:0},W=J.openUntil!==void 0;if($==="success")return this.entries.delete(Q),W?"closed":void 0;if($==="none"){delete J.probeUntil;return}if(J.failures+=1,this.entries.set(Q,J),W||J.failures>=Z.failures)return J.openUntil=this.now()+Z.cooldownMs,delete J.probeUntil,W?void 0:"open";return}state(Q){let $=this.entries.get(Q);if($?.openUntil===void 0)return"closed";return this.now()<$.openUntil?"open":"half-open"}}function V1(Q){switch(Q.type){case"text-delta":case"reasoning-delta":case"tool-call-delta":case"tool-call":case"tool-search":case"output-delta":return!0;default:return!1}}var X3=Symbol("timed-out");class KQ extends r{model;capabilities;entries;options;circuit;constructor(Q,$={}){super();if(Q.length===0)throw Error("FallbackProvider needs at least one provider.");for(let J of Q)if(J.timeoutMs!==void 0&&!(J.timeoutMs>0))throw Error(`FallbackProvider: timeoutMs for ${J.provider.model} must be a positive number, got ${J.timeoutMs}.`);this.entries=[...Q];let Z=$.circuit;if(Z){let J=Z.failures??3,W=Z.cooldownMs??30000;if(!Number.isInteger(J)||J<1)throw Error(`FallbackProvider: circuit.failures must be a positive integer, got ${J}.`);if(!(W>0))throw Error(`FallbackProvider: circuit.cooldownMs must be a positive number, got ${W}.`);let G=new Set;for(let Y of Q){let H=f9(Y);if(G.has(H))throw Error(`FallbackProvider: two legs share the circuit key "${H}". Give one of them a \`circuitKey\`.`);G.add(H)}let X=Z.store??new IQ;this.options={...$,circuit:{...Z,store:X}},this.circuit={policy:{failures:J,cooldownMs:W},store:X,...Z.onStateChange?{onStateChange:Z.onStateChange}:{}}}else this.options=$,this.circuit=void 0;this.model=Q[0].provider.model,this.capabilities=Y1(Q.map((J)=>J.provider.capabilities))}static chain(Q,$){return new KQ(Q,$)}from(Q){if(!Number.isInteger(Q)||Q<0||Q>=this.entries.length)throw RangeError(`FallbackProvider.from(${Q}): the chain has ${this.entries.length} entries.`);return new KQ(this.entries.slice(Q),this.options)}leg(Q){let $=this.from(Q).entries[0];return new KQ([$],this.options)}upload(Q){return this.entries[0].provider.upload(Q)}normalizeError(Q){return this.entries[0].provider.normalizeError(Q)}stream(Q){return this.run(Q)}async*run(Q){let $,Z=Q.signal,J=0;for(let W=0;W<this.entries.length;W++){let G=this.entries[W],X=W===this.entries.length-1,Y=G.provider.model;if(this.circuit&&!X&&!await this.allow(G))continue;J+=1;let H=!1,V=async(C)=>{if(H)return;H=!0,await this.record(W,G,C)},K=new AbortController,z=()=>K.abort(Z?.reason);if(Z?.aborted)K.abort(Z.reason);else Z?.addEventListener("abort",z,{once:!0});let B=[],U=!1,F=!1,D,j,L,S=!1,N,v=!1,E=(C)=>{let P=$?R(R(M(),$),C.usage):C.usage;return $=void 0,{...C,usage:P}};try{N=G.provider.stream({...Q,...G.reasoning!==void 0?{reasoning:G.reasoning}:{},signal:K.signal})[Symbol.asyncIterator]();let C=!0;for(;;){let P=C&&G.timeoutMs!==void 0?await H1(N.next(),G.timeoutMs):await N.next();if(P===X3){S=!0,L={error:{code:"provider_error",message:`${Y} sent nothing within ${G.timeoutMs}ms.`,retryable:!0}};break}if(C=!1,P.done){v=!0;break}let q=P.value;if(q.type==="finish"&&q.model)j=q.model;if(U){if(q.type==="finish")D=R(D??M(),q.usage),F=!0,yield E(q);else{if(q.type==="error")L={error:q.error};yield q}continue}if(V1(q)){U=!0,await V("success"),yield*B.splice(0),yield q;continue}if(q.type==="error")L={error:q.error,...q.status!==void 0?{status:q.status}:{},...q.requestId!==void 0?{requestId:q.requestId}:{}};else if(q.type==="finish"){if(D=R(D??M(),q.usage),q.reason==="error"&&!L)L={error:{code:"provider_error",message:`${Y} ended the call with an error and did not say which.`,retryable:!1}}}B.push(q)}}catch(C){let P=G.provider.normalizeError(C);if(U){if(P.code!=="aborted")yield{type:"error",error:P,...x(C)};this.report({index:W,model:Y,responseModel:j,attempt:J,usage:D,outcome:h9(P),error:P}),yield E({type:"finish",reason:P.code==="aborted"?"aborted":"error",usage:M(),...j?{model:j}:{}});return}L={error:P,...x(C)}}finally{if(Z?.removeEventListener("abort",z),!v)K.abort(),N?.return?.()?.catch(()=>{})}if(U){if(!F&&$)yield{type:"finish",reason:L?"error":"stop",usage:$},$=void 0;this.report({index:W,model:Y,responseModel:j,attempt:J,usage:D,outcome:L?h9(L.error):"ok",...L?{error:L.error}:{}});return}if(Z?.aborted){await V("none"),this.report({index:W,model:Y,responseModel:j,attempt:J,usage:D,outcome:"aborted"}),yield E({type:"finish",reason:"aborted",usage:D??M(),...j?{model:j}:{}});return}if(!L){await V("success"),this.report({index:W,model:Y,responseModel:j,attempt:J,usage:D,outcome:"ok"});for(let C of B)yield C.type==="finish"?E(C):C;return}let _=!X&&L.error.code!=="aborted"&&this.shouldFallBack(L.error,{index:W,model:Y,timedOut:S,...L.status!==void 0?{status:L.status}:{},...L.requestId!==void 0?{requestId:L.requestId}:{}});if(await V(_?"failure":"none"),this.report({index:W,model:Y,responseModel:j,attempt:J,usage:D,outcome:_?"fallback":h9(L.error),error:L.error}),_){if(D)$=R($??M(),D);continue}let w=!1,O;for(let C of B){if(C.type==="finish"){O=C;continue}if(C.type==="error")w=!0;yield C}if(!w&&L.error.code!=="aborted")yield{type:"error",error:L.error,...L.status!==void 0?{status:L.status}:{},...L.requestId!==void 0?{requestId:L.requestId}:{}};yield E({type:"finish",reason:L.error.code==="aborted"?"aborted":O?.reason??"error",usage:D??M(),...j?{model:j}:{}});return}}async allow(Q){if(!this.circuit)return!0;try{return await this.circuit.store.allow(f9(Q),this.circuit.policy)}catch{return!0}}async record(Q,$,Z){if(!this.circuit)return;let J=f9($),W;try{W=await this.circuit.store.record(J,Z,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:Q,model:$.provider.model,key:J,state:W})}catch{}}shouldFallBack(Q,$){let Z=this.options.fallbackOn??((J)=>J.retryable);try{return Z(Q,$)}catch{return!1}}report(Q){if(Q.usage===void 0)delete Q.usage;if(Q.responseModel===void 0)delete Q.responseModel;try{this.options.onUsage?.(Q)}catch{}}}function f9(Q){return Q.circuitKey??Q.provider.model}function h9(Q){return Q.code==="aborted"?"aborted":"failed"}function Y1(Q){return{reasoning:Q.every(($)=>$.reasoning),structuredOutput:Q.every(($)=>$.structuredOutput),fileInput:Q.every(($)=>$.fileInput),parallelToolCalls:Q.every(($)=>$.parallelToolCalls),toolSearch:Q.every(($)=>$.toolSearch)}}function H1(Q,$){let Z,J=new Promise((W)=>{Z=setTimeout(()=>W(X3),$)});return Promise.race([Q,J]).finally(()=>clearTimeout(Z))}async function K1(Q,$,Z={}){let J=Z.samples??1;if(!Number.isInteger(J)||J<1)throw RangeError(`evalChain: samples must be a positive integer, got ${J}.`);let W=[];for(let G=0;G<Q.entries.length;G++){let X=Q.leg(G),Y={index:G,model:X.model,results:[],errors:[]};for(let H=0;H<J;H++)try{Y.results.push(await $(X,{index:G,sample:H}))}catch(V){Y.errors.push({sample:H,error:V})}W.push(Y)}return W}class e 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 BQ extends Error{runId;code="live_run_not_found";constructor(Q){super(`No live run ${Q} in this process.`);this.runId=Q}}class vQ{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,owner:$.owner??null,clientRunId:$.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evicted:!1,evictAt:null,expireAt:null,wake:new Set,version:0};if(this.runs.set(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}ownerOf(Q){return this.runs.get(Q)?.owner??null}mayAccess(Q,$){let Z=this.ownerOf(Q);return Z===null||Z===$}isRunning(Q){let $=this.runs.get(Q);return!!$&&!$.ended&&!$.evicted}replay(Q,$){let Z=this.runs.get(Q);if(!Z)throw new BQ(Q);if($!==void 0&&$<Z.lostBefore)throw new e(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 G=$.onEvent;if(G)Z=Z.then(()=>G(J.event)).catch((X)=>y9($,X));continue}if(Q.frames.push(J),Q.lastSeq=J.seq,Q.frames.length>this.maxFrames){let G=Q.frames.shift();if(G)Q.lostBefore=G.seq+1}this.notify(Q);let W=$.onEvent;if(W)Z=Z.then(()=>W(J.event)).catch((G)=>y9($,G))}}catch(J){y9($,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 W=Q.version;for(;;){if(J<Q.lostBefore)throw new e($,J,Q.lostBefore);let G=Q.frames,X=G[0]?.seq;if(X===void 0)break;let Y=Math.max(0,J-X);if(Y>=G.length)break;let H=G[Y];yield H,J=H.seq+1}if(Q.ended&&J>Q.lastSeq||Q.evicted)return;await this.wait(Q,W)}}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 g9=new vQ;function y9(Q,$){try{Q.onInternalError?.($)}catch{}}class fQ{maxEntries;records=new Map;constructor(Q=1e5){this.maxEntries=Q}async record(Q,$){if(this.records.has(Q))return;this.records.set(Q,{...$});while(this.records.size>this.maxEntries){let Z=this.records.keys().next().value;if(Z===void 0)break;this.records.delete(Z)}}async get(Q){let $=this.records.get(Q);return $?{...$}:null}}var u9=new fQ;class m9{now;receipts=new Map;sweepAt=1024;constructor(Q=Date.now){this.now=Q}async claim(Q,$){let Z=this.now();if(this.receipts.size>=this.sweepAt)this.sweep(Z);let J=this.receipts.get(Q);if(J&&J.expiresAt>Z)return J.result?{status:"replay",result:structuredClone(J.result)}:{status:"blocked"};return this.receipts.set(Q,{expiresAt:$}),{status:"claimed"}}async complete(Q,$,Z){this.receipts.set(Q,{result:structuredClone($),expiresAt:Z})}async release(Q){let $=this.receipts.get(Q);if($&&!$.result)this.receipts.delete(Q)}get size(){return this.receipts.size}sweep(Q){for(let[$,Z]of this.receipts)if(Z.expiresAt<=Q)this.receipts.delete($);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var V3="pending",c9="done:",B1=`
|
|
18
|
+
`)}}if($.length>0){let H=X($);if(H)yield H}let Y=G();if(Y)yield Y}async function*$3(Q,$={}){let Z=new Map,J=new Set,W,G=!1,X,Y=(H,V)=>({type:"finish",reason:H,usage:V,...X?{model:X}:{}});for await(let H of lZ(Q)){if(H.data==="[DONE]")break;let V;try{V=JSON.parse(H.data)}catch{continue}let K=typeof V.type==="string"?V.type:H.event,z=V.response?.model;if(typeof z==="string"&&z)X=z;switch(K){case"response.output_text.delta":{let B=String(V.delta??"");if(!B)break;yield $.structuredOutput?{type:"output-delta",delta:B}:{type:"text-delta",delta:B};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let B=String(V.delta??"");if(!B)break;yield{type:"reasoning-delta",delta:B,id:V.item_id};break}case"response.output_item.added":{let B=V.item;if(!B)break;if(B.type==="function_call"){let U=String(B.id??V.item_id??B.call_id??"");Z.set(U,{callId:String(B.call_id??U),name:String(B.name??""),namespace:typeof B.namespace==="string"&&B.namespace?B.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let B=Z.get(String(V.item_id??""));if(!B)break;let U=String(V.delta??"");if(!U)break;yield{type:"tool-call-delta",toolCallId:B.callId,name:B.name,argsDelta:U,...B.namespace?{namespace:B.namespace}:{}};break}case"response.function_call_arguments.done":{let B=String(V.item_id??""),U=Z.get(B);if(!U)break;U.done=!0,yield{type:"tool-call",toolCallId:U.callId,name:U.name,args:String(V.arguments??""),...U.namespace?{namespace:U.namespace}:{}};break}case"response.output_item.done":{let B=V.item;if(!B)break;if(B.type==="function_call"){let U=String(B.id??V.item_id??B.call_id??""),F=Z.get(U);if(F?.done)break;let D=(typeof B.namespace==="string"?B.namespace:"")||F?.namespace;if(yield{type:"tool-call",toolCallId:String(B.call_id??U),name:String(B.name??F?.name??""),args:String(B.arguments??""),...D?{namespace:D}:{}},F)F.done=!0;break}if(B.type==="tool_search_call"||B.type==="tool_search_output"){if(B.type==="tool_search_call"&&B.arguments!==void 0)W=B.arguments;let U=iZ(B);if(U.loaded.length===0&&U.namespaces.length===0)break;let F=String(B.tool_search_call_id??B.id??"");if(J.has(F))break;J.add(F);let D=W;W=void 0,yield{type:"tool-search",...U,...D!==void 0&&D!==null?{arguments:D}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(V.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{G=!0,yield Y("stop",T9(V.response?.usage));break}case"response.incomplete":{G=!0;let B=T9(V.response?.usage),U=V.response?.incomplete_details?.reason;if(U==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:oZ(V.response?.content_filters),retryable:!1}},yield Y("error",B);break}yield Y(U==="max_output_tokens"?"length":"stop",B);break}case"response.failed":case"error":{G=!0;let B=V.response?.error??V.error??V;yield{type:"error",error:nZ(B)},yield Y("error",T9(V.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 Y("error",t())}function iZ(Q){let $=[],Z=[];return Z3(Q.results??Q.tools??Q.loaded??Q.output,$,Z,0),{loaded:A9($),namespaces:A9(Z)}}function Z3(Q,$,Z,J){if(!Array.isArray(Q)||J>4)return;for(let W of Q){if(typeof W==="string"){$.push(W);continue}if(!W||typeof W!=="object")continue;let G=W,X=typeof G.name==="string"?G.name:typeof G.tool_name==="string"?G.tool_name:"",Y=G.tools??G.functions;if(Array.isArray(Y)){if(X)Z.push(X);Z3(Y,$,Z,J+1);continue}if(X)$.push(X)}}function A9(Q){return Q.filter(($,Z)=>Q.indexOf($)===Z)}function oZ(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 W=J,G=W.content_filter_results;if(!G||typeof G!=="object")continue;for(let[X,Y]of Object.entries(G))if(Y&&typeof Y==="object"&&Y.filtered===!0)Z.push(`${X} (${String(W.source_type??"unknown")})`)}return Z.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${A9(Z).join(", ")}.`}function nZ(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 t(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function T9(Q){if(!Q)return t();let $=Number(Q.input_tokens??0),Z=Number(Q.output_tokens??0),J={inputTokens:$,outputTokens:Z,totalTokens:Number(Q.total_tokens??$+Z)},W=Q.output_tokens_details?.reasoning_tokens;if(typeof W==="number")J.reasoningTokens=W;let G=Q.input_tokens_details?.cached_tokens;if(typeof G==="number")J.cachedInputTokens=G;return J}async function*J3(Q){if(!Q)return;let $=Q.getReader(),Z=new TextDecoder;try{while(!0){let{done:W,value:G}=await $.read();if(W)break;if(G)yield Z.decode(G,{stream:!0})}let J=Z.decode();if(J)yield J}finally{$.releaseLock()}}function k9(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*E9(Q,$,Z){let J,W=$,G=new Set;for(let X=0;J===void 0;X++)try{J=await KQ(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify(W)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(Y){let H=X<r$?e$(W,Y,Z.files).filter((K)=>!G.has(K)):[];if(H.length>0){let K=E(Y).message;for(let z of H)G.add(z),yield{type:"file-rejected",fileId:z,message:K,...b(Y)};W=Q3(W,new Set(H),Z.files);continue}let V=E(Y);if(V.code!=="aborted")yield{type:"error",error:V,...b(Y)};yield{type:"finish",reason:V.code==="aborted"?"aborted":"error",usage:t()};return}try{yield*$3(J3(J.body),{structuredOutput:Z.structuredOutput})}catch(X){let Y=E(X);if(Y.code==="aborted"){yield{type:"finish",reason:"aborted",usage:t()};return}yield{type:"error",error:Y},yield{type:"finish",reason:"error",usage:t()}}}async function x9(Q,$,Z="user_data"){let J=new FormData;J.set("purpose",Z),J.set("file",$);let G=await(await KQ(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:J},{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 b9(Q){let $=sZ(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Z=tZ($);if(Z?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Z.major>1,toolSearch:W3(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:W3(Z)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function W3(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function sZ(Q){return Q.trim().toLowerCase()}function tZ(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 I9(Q,$){let{capabilities:Z}=$,J={model:$.model,input:aZ(Q.messages,Z,Q.tools),stream:!0};if(Q.systemPrompt)J.instructions=Q.systemPrompt;let W=V1(Q.tools,Z);if(W.length>0){if(J.tools=W,!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 aZ(Q,$,Z){let J=[],W=new Map;if($.toolSearch){for(let G of Z??[])if(IQ(G))W.set(G.name,G)}for(let G of Q){let X=G.role,Y=[],H=()=>{if(Y.length===0)return;J.push({type:"message",role:X,content:Y}),Y=[]};for(let V of G.content??[])switch(V.type){case"text":{if(!V.text)break;Y.push(a(X,V.text));break}case"output":{if(V.partial)break;Y.push(a(X,JSON.stringify(V.value)));break}case"file":{if(X==="assistant")break;let K=Q1(V);if(!$.fileInput){if(K)Y.push(a(X,w9(V,!1)));break}if(V.fileId?.startsWith(f))throw Error(`FilePart.fileId holds a gemi attachment id (${V.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!V.fileId&&!K)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.providerRejected){if(K)Y.push(a(X,w9(V,!1)));Y.push(a(X,S9(V.name)));break}if(K)Y.push(a(X,w9(V,!!V.fileId)));if(V.fileId)Y.push($1(V));break}case"reasoning":{H();let K=W1(V);if(K)J.push(K);break}case"tool-call":{if(V.partial)break;if(H(),$.toolSearch&&Array.isArray(V.toolSearches))for(let z of V.toolSearches)J.push(...X1(z,Z??[]));let K={type:"function_call",call_id:V.toolCallId,name:String(V.name),arguments:JSON.stringify(V.input??{})};if(V.namespace&&W.has(V.namespace))K.namespace=V.namespace;J.push(K);break}case"tool-result":{H(),J.push({type:"function_call_output",call_id:V.toolCallId,output:G1(V)});break}}H()}return eZ(J)}var rZ="No result was recorded for this tool call. Assume it did not complete.";function eZ(Q){let $=new Set,Z=new Set,J=[];for(let G of Q){if(G.type==="function_call"){let X=String(G.call_id);if($.has(X))continue;$.add(X)}else if(G.type==="function_call_output"){let X=String(G.call_id);if(!$.has(X)||Z.has(X))continue;Z.add(X)}J.push(G)}if(Z.size===$.size)return J;let W=[];for(let G of J){if(W.push(G),G.type!=="function_call")continue;let X=String(G.call_id);if(Z.has(X))continue;Z.add(X),W.push({type:"function_call_output",call_id:X,output:rZ})}return W}function a(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function Q1(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(f)?$:void 0}function w9(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 $1(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":Z1(Q.name))?"input_image":"input_file",file_id:Q.fileId}}function Z1(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&J1.has($[1])}var J1=new Set(["jpeg","jpg","png","gif","webp"]);function W1(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function G1(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 X1(Q,$){let Z=new Set(G3(Q?.loaded)),J=G3(Q?.namespaces),W=new Set(J),G=[];for(let Y of $)if(IQ(Y)){if(!W.has(Y.name))continue;let H=Y.tools.filter((V)=>Z.size===0||Z.has(V.name));if(H.length===0)continue;G.push({type:"namespace",name:Y.name,description:Y.description,tools:H.map((V)=>r(V,!0))})}else if(Y.deferred&&Z.has(Y.name))G.push(r(Y,!0));if(G.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:Q.arguments&&typeof Q.arguments==="object"?Q.arguments:{paths:J.length>0?J:[...Z]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:G}]}function G3(Q){return Array.isArray(Q)?Q.filter(($)=>typeof $==="string"):[]}function IQ(Q){return Array.isArray(Q.tools)}function V1(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let W=[];for(let G of Q)if(IQ(G))for(let X of G.tools)W.push(r(X,!1));else W.push(r(G,!1));return W}let Z=[],J=!1;for(let W of Q)if(IQ(W)){let G=W.tools.map((X)=>{if(X.deferred)J=!0;return r(X,!0)});Z.push({type:"namespace",name:W.name,description:W.description,tools:G})}else{if(W.deferred)J=!0;Z.push(r(W,!0))}if(J)Z.push({type:"tool_search"});return Z}function r(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 e{static models(){return[]}normalizeError(Q){return E(Q)}}var X3=["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 v9 extends e{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=b9(Q),this.config=$}static model(Q,$){return new v9(Q,$)}static models(){return X3}stream(Q){let $=I9(Q,{model:this.model,capabilities:this.capabilities});return E9(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output),files:M9(Q.messages)})}upload(Q){return x9(this.endpoint(),Q)}endpoint(){return k9(EQ(this.config))}}class f9 extends e{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=b9(Q),this.config=$}static model(Q,$){return new f9(Q,$)}static models(){return X3}stream(Q){let $=I9(Q,{model:this.deployment(),capabilities:this.capabilities});return E9(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output),files:M9(Q.messages)})}upload(Q){return x9(this.endpoint(),Q,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return k9(xQ(this.config))}}class vQ{now;entries=new Map;constructor(Q=Date.now){this.now=Q}allow(Q,$){let Z=this.entries.get(Q);if(Z?.openUntil===void 0)return!0;let J=this.now();if(J<Z.openUntil)return!1;if(Z.probeUntil!==void 0&&J<Z.probeUntil)return!1;return Z.probeUntil=J+$.cooldownMs,!0}record(Q,$,Z){let J=this.entries.get(Q)??{failures:0},W=J.openUntil!==void 0;if($==="success")return this.entries.delete(Q),W?"closed":void 0;if($==="none"){delete J.probeUntil;return}if(J.failures+=1,this.entries.set(Q,J),W||J.failures>=Z.failures)return J.openUntil=this.now()+Z.cooldownMs,delete J.probeUntil,W?void 0:"open";return}state(Q){let $=this.entries.get(Q);if($?.openUntil===void 0)return"closed";return this.now()<$.openUntil?"open":"half-open"}}function Y1(Q){switch(Q.type){case"text-delta":case"reasoning-delta":case"tool-call-delta":case"tool-call":case"tool-search":case"output-delta":return!0;default:return!1}}var V3=Symbol("timed-out");class BQ extends e{model;capabilities;entries;options;circuit;constructor(Q,$={}){super();if(Q.length===0)throw Error("FallbackProvider needs at least one provider.");for(let J of Q)if(J.timeoutMs!==void 0&&!(J.timeoutMs>0))throw Error(`FallbackProvider: timeoutMs for ${J.provider.model} must be a positive number, got ${J.timeoutMs}.`);this.entries=[...Q];let Z=$.circuit;if(Z){let J=Z.failures??3,W=Z.cooldownMs??30000;if(!Number.isInteger(J)||J<1)throw Error(`FallbackProvider: circuit.failures must be a positive integer, got ${J}.`);if(!(W>0))throw Error(`FallbackProvider: circuit.cooldownMs must be a positive number, got ${W}.`);let G=new Set;for(let Y of Q){let H=h9(Y);if(G.has(H))throw Error(`FallbackProvider: two legs share the circuit key "${H}". Give one of them a \`circuitKey\`.`);G.add(H)}let X=Z.store??new vQ;this.options={...$,circuit:{...Z,store:X}},this.circuit={policy:{failures:J,cooldownMs:W},store:X,...Z.onStateChange?{onStateChange:Z.onStateChange}:{}}}else this.options=$,this.circuit=void 0;this.model=Q[0].provider.model,this.capabilities=H1(Q.map((J)=>J.provider.capabilities))}static chain(Q,$){return new BQ(Q,$)}from(Q){if(!Number.isInteger(Q)||Q<0||Q>=this.entries.length)throw RangeError(`FallbackProvider.from(${Q}): the chain has ${this.entries.length} entries.`);return new BQ(this.entries.slice(Q),this.options)}leg(Q){let $=this.from(Q).entries[0];return new BQ([$],this.options)}upload(Q){return this.entries[0].provider.upload(Q)}normalizeError(Q){return this.entries[0].provider.normalizeError(Q)}stream(Q){return this.run(Q)}async*run(Q){let $,Z=Q.signal,J=0;for(let W=0;W<this.entries.length;W++){let G=this.entries[W],X=W===this.entries.length-1,Y=G.provider.model;if(this.circuit&&!X&&!await this.allow(G))continue;J+=1;let H=!1,V=async(P)=>{if(H)return;H=!0,await this.record(W,G,P)},K=new AbortController,z=()=>K.abort(Z?.reason);if(Z?.aborted)K.abort(Z.reason);else Z?.addEventListener("abort",z,{once:!0});let B=[],U=!1,F=!1,D,j,L,S=!1,O,v=!1,k=(P)=>{let _=$?T(T(M(),$),P.usage):P.usage;return $=void 0,{...P,usage:_}};try{O=G.provider.stream({...Q,...G.reasoning!==void 0?{reasoning:G.reasoning}:{},signal:K.signal})[Symbol.asyncIterator]();let P=!0;for(;;){let _=P&&G.timeoutMs!==void 0?await K1(O.next(),G.timeoutMs):await O.next();if(_===V3){S=!0,L={error:{code:"provider_error",message:`${Y} sent nothing within ${G.timeoutMs}ms.`,retryable:!0}};break}if(P=!1,_.done){v=!0;break}let C=_.value;if(C.type==="finish"&&C.model)j=C.model;if(U){if(C.type==="finish")D=T(D??M(),C.usage),F=!0,yield k(C);else{if(C.type==="error")L={error:C.error};yield C}continue}if(Y1(C)){U=!0,await V("success"),yield*B.splice(0),yield C;continue}if(C.type==="error")L={error:C.error,...C.status!==void 0?{status:C.status}:{},...C.requestId!==void 0?{requestId:C.requestId}:{}};else if(C.type==="finish"){if(D=T(D??M(),C.usage),C.reason==="error"&&!L)L={error:{code:"provider_error",message:`${Y} ended the call with an error and did not say which.`,retryable:!1}}}B.push(C)}}catch(P){let _=G.provider.normalizeError(P);if(U){if(_.code!=="aborted")yield{type:"error",error:_,...b(P)};this.report({index:W,model:Y,responseModel:j,attempt:J,usage:D,outcome:y9(_),error:_}),yield k({type:"finish",reason:_.code==="aborted"?"aborted":"error",usage:M(),...j?{model:j}:{}});return}L={error:_,...b(P)}}finally{if(Z?.removeEventListener("abort",z),!v)K.abort(),O?.return?.()?.catch(()=>{})}if(U){if(!F&&$)yield{type:"finish",reason:L?"error":"stop",usage:$},$=void 0;this.report({index:W,model:Y,responseModel:j,attempt:J,usage:D,outcome:L?y9(L.error):"ok",...L?{error:L.error}:{}});return}if(Z?.aborted){await V("none"),this.report({index:W,model:Y,responseModel:j,attempt:J,usage:D,outcome:"aborted"}),yield k({type:"finish",reason:"aborted",usage:D??M(),...j?{model:j}:{}});return}if(!L){await V("success"),this.report({index:W,model:Y,responseModel:j,attempt:J,usage:D,outcome:"ok"});for(let P of B)yield P.type==="finish"?k(P):P;return}let R=!X&&L.error.code!=="aborted"&&this.shouldFallBack(L.error,{index:W,model:Y,timedOut:S,...L.status!==void 0?{status:L.status}:{},...L.requestId!==void 0?{requestId:L.requestId}:{}});if(await V(R?"failure":"none"),this.report({index:W,model:Y,responseModel:j,attempt:J,usage:D,outcome:R?"fallback":y9(L.error),error:L.error}),R){if(D)$=T($??M(),D);continue}let N=!1,q;for(let P of B){if(P.type==="finish"){q=P;continue}if(P.type==="error")N=!0;yield P}if(!N&&L.error.code!=="aborted")yield{type:"error",error:L.error,...L.status!==void 0?{status:L.status}:{},...L.requestId!==void 0?{requestId:L.requestId}:{}};yield k({type:"finish",reason:L.error.code==="aborted"?"aborted":q?.reason??"error",usage:D??M(),...j?{model:j}:{}});return}}async allow(Q){if(!this.circuit)return!0;try{return await this.circuit.store.allow(h9(Q),this.circuit.policy)}catch{return!0}}async record(Q,$,Z){if(!this.circuit)return;let J=h9($),W;try{W=await this.circuit.store.record(J,Z,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:Q,model:$.provider.model,key:J,state:W})}catch{}}shouldFallBack(Q,$){let Z=this.options.fallbackOn??((J)=>J.retryable);try{return Z(Q,$)}catch{return!1}}report(Q){if(Q.usage===void 0)delete Q.usage;if(Q.responseModel===void 0)delete Q.responseModel;try{this.options.onUsage?.(Q)}catch{}}}function h9(Q){return Q.circuitKey??Q.provider.model}function y9(Q){return Q.code==="aborted"?"aborted":"failed"}function H1(Q){return{reasoning:Q.every(($)=>$.reasoning),structuredOutput:Q.every(($)=>$.structuredOutput),fileInput:Q.every(($)=>$.fileInput),parallelToolCalls:Q.every(($)=>$.parallelToolCalls),toolSearch:Q.every(($)=>$.toolSearch)}}function K1(Q,$){let Z,J=new Promise((W)=>{Z=setTimeout(()=>W(V3),$)});return Promise.race([Q,J]).finally(()=>clearTimeout(Z))}async function B1(Q,$,Z={}){let J=Z.samples??1;if(!Number.isInteger(J)||J<1)throw RangeError(`evalChain: samples must be a positive integer, got ${J}.`);let W=[];for(let G=0;G<Q.entries.length;G++){let X=Q.leg(G),Y={index:G,model:X.model,results:[],errors:[]};for(let H=0;H<J;H++)try{Y.results.push(await $(X,{index:G,sample:H}))}catch(V){Y.errors.push({sample:H,error:V})}W.push(Y)}return W}class QQ 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 zQ extends Error{runId;code="live_run_not_found";constructor(Q){super(`No live run ${Q} in this process.`);this.runId=Q}}class fQ{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,owner:$.owner??null,clientRunId:$.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evicted:!1,evictAt:null,expireAt:null,wake:new Set,version:0};if(this.runs.set(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}ownerOf(Q){return this.runs.get(Q)?.owner??null}mayAccess(Q,$){let Z=this.ownerOf(Q);return Z===null||Z===$}isRunning(Q){let $=this.runs.get(Q);return!!$&&!$.ended&&!$.evicted}replay(Q,$){let Z=this.runs.get(Q);if(!Z)throw new zQ(Q);if($!==void 0&&$<Z.lostBefore)throw new QQ(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 G=$.onEvent;if(G)Z=Z.then(()=>G(J.event)).catch((X)=>g9($,X));continue}if(Q.frames.push(J),Q.lastSeq=J.seq,Q.frames.length>this.maxFrames){let G=Q.frames.shift();if(G)Q.lostBefore=G.seq+1}this.notify(Q);let W=$.onEvent;if(W)Z=Z.then(()=>W(J.event)).catch((G)=>g9($,G))}}catch(J){g9($,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 W=Q.version;for(;;){if(J<Q.lostBefore)throw new QQ($,J,Q.lostBefore);let G=Q.frames,X=G[0]?.seq;if(X===void 0)break;let Y=Math.max(0,J-X);if(Y>=G.length)break;let H=G[Y];yield H,J=H.seq+1}if(Q.ended&&J>Q.lastSeq||Q.evicted)return;await this.wait(Q,W)}}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 u9=new fQ;function g9(Q,$){try{Q.onInternalError?.($)}catch{}}class hQ{maxEntries;records=new Map;constructor(Q=1e5){this.maxEntries=Q}async record(Q,$){if(this.records.has(Q))return;this.records.set(Q,{...$});while(this.records.size>this.maxEntries){let Z=this.records.keys().next().value;if(Z===void 0)break;this.records.delete(Z)}}async get(Q){let $=this.records.get(Q);return $?{...$}:null}}var c9=new hQ;class p9{now;receipts=new Map;sweepAt=1024;constructor(Q=Date.now){this.now=Q}async claim(Q,$){let Z=this.now();if(this.receipts.size>=this.sweepAt)this.sweep(Z);let J=this.receipts.get(Q);if(J&&J.expiresAt>Z)return J.result?{status:"replay",result:structuredClone(J.result)}:{status:"blocked"};return this.receipts.set(Q,{expiresAt:$}),{status:"claimed"}}async complete(Q,$,Z){this.receipts.set(Q,{result:structuredClone($),expiresAt:Z})}async release(Q){let $=this.receipts.get(Q);if($&&!$.result)this.receipts.delete(Q)}get size(){return this.receipts.size}sweep(Q){for(let[$,Z]of this.receipts)if(Z.expiresAt<=Q)this.receipts.delete($);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var Y3="pending",m9="done:",z1=`
|
|
19
19
|
if redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2], 'NX') then return 'claimed' end
|
|
20
20
|
local held = redis.call('GET', KEYS[1])
|
|
21
21
|
if not held then return ARGV[1] end
|
|
22
|
-
return held`,
|
|
22
|
+
return held`,U1=`
|
|
23
23
|
if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end
|
|
24
|
-
return 0`;class p9{injectedClient;prefix;constructor(Q={}){this.injectedClient=Q.client,this.prefix=Q.prefix??"gemi:ai:receipt"}async claim(Q,$){let Z=await this.client.send("EVAL",[B1,"1",this.key(Q),V3,Y3($)]);if(Z==="claimed")return{status:"claimed"};let J=String(Z??"");if(J.startsWith(c9))return{status:"replay",result:JSON.parse(J.slice(c9.length))};return{status:"blocked"}}async complete(Q,$,Z){await this.client.send("SET",[this.key(Q),c9+JSON.stringify($),"PX",Y3(Z)])}async release(Q){await this.client.send("EVAL",[z1,"1",this.key(Q),V3])}key(Q){return`${this.prefix}:${Q}`}get client(){if(this.injectedClient)return this.injectedClient;let Q=PQ(),$=Q.bound(l)?Q.make(l).client:void 0;if(!$)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return $}}function Y3(Q){return String(Math.max(1,Math.ceil(Q-Date.now())))}class hQ{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 W=Z.messages.findIndex((G)=>G.id===J.id);if(W===-1)Z.messages.push(J);else Z.messages[W]=J}Z.touchedAt=Date.now()}async removeMessages(Q,$){this.sweep();let Z=this.threads.get(Q);if(!Z)return;let J=new Set($);Z.messages=Z.messages.filter((W)=>!J.has(W.id)),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 d9=new hQ;function z3(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 U3(Q,$,Z=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==Q.cursorRunId)&&$.seq<=Q.seq)return Q;return{...D3(Q,$.event,Z),seq:$.seq}}function D3(Q,$,Z){switch($.type){case"run-start":return{...Q,messages:U1(Q.messages,$.runId),runId:$.runId,cursorRunId:$.runId,threadId:$.threadId??Q.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return d(Q,$.messageId,Z,(J)=>({...J,role:$.role}));case"text-delta":if(K3(Q,$.messageId))return Q;return d(Q,$.messageId,Z,(J)=>({...J,content:C1(J.content,$.delta)}));case"reasoning-delta":if(K3(Q,$.messageId))return Q;return d(Q,$.messageId,Z,(J)=>({...J,content:P1(J.content,$.delta,$.id)}));case"output-delta":return d(Q,$.messageId,Z,(J)=>({...J,content:B3(J.content,{type:"output",value:$.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return d(Q,$.messageId,Z,(J)=>{let W=J.content.findIndex((z)=>z.type==="tool-call"&&z.toolCallId===$.part.toolCallId),G=W===-1?void 0:J.content[W],X=$.part.progress??G?.progress,Y=$.part.nested??G?.nested,H=$.part.attachments??G?.attachments,V={...$.part,...X?{progress:X}:{},...Y?{nested:Y}:{},...H?{attachments:H}:{}},K=J.content.slice();if(W===-1)K.push(V);else K[W]=V;return{...J,content:K}});case"tool-search":{let J=$.loaded.filter((W)=>!Q.loadedTools.includes(W));if(J.length===0)return Q;return{...Q,loadedTools:[...Q.loadedTools,...J]}}case"tool-progress":return H3(Q,$.toolCallId,(J)=>({...J,progress:[...J.progress??[],$.data]}));case"nested-event":{let J=$;return H3(Q,$.toolCallId,(W)=>{let G=W.nested??[],X=G.findIndex((K)=>K.runId===J.runId),Y=G[X]??{runId:J.runId,agent:J.agent,messages:[]},H=j1(Y,J,Z),V=X===-1?[...G,H]:G.map((K,z)=>z===X?H:K);return{...W,nested:V}})}case"tool-result":{let J=d(Q,$.messageId,Z,(W)=>({...W,content:B3(W.content,$.part,(G)=>G.type==="tool-result"&&G.toolCallId===$.part.toolCallId)}));return{...J,pending:J.pending.filter((W)=>W.toolCallId!==$.part.toolCallId)}}case"message":{let J=Q.messages.findIndex((X)=>X.id===$.message.id),W=Q.messages.slice();if(J===-1)W.push($.message);else W[J]=$.message;let G=Q.runMessageIds.includes($.message.id)?Q.runMessageIds:[...Q.runMessageIds,$.message.id];return{...Q,messages:W,runMessageIds:G}}case"message-id":{let J=Q.messages.findIndex((G)=>G.id===$.localId);if(J===-1){if(!$.message||Q.messages.some((G)=>G.id===$.messageId))return Q;return{...Q,messages:[...Q.messages,$.message]}}let W=Q.messages.some((G)=>G.id===$.messageId)?Q.messages.filter((G,X)=>X!==J):Q.messages.map((G,X)=>X===J?{...G,id:$.messageId}:G);return{...Q,messages:W}}case"awaiting-input":return{...Q,runId:$.runId,pending:[...$.pending]};case"message-end":return d(Q,$.messageId,Z,(J)=>({...J,finishReason:$.finishReason,...$.outputTruncated?{outputTruncated:!0}:{},...$.usage?{usage:$.usage}:{},content:$.outputTruncated||$.finishReason==="length"?J.content.filter((W)=>!(W.type==="output"&&W.partial)):J.content.map((W)=>W.type==="output"&&W.partial?{...W,partial:!1}:W)}));case"usage":return{...Q,usage:$.usage};case"error":return{...Q,error:$.error,pending:[]};case"run-end":return{...Q,runId:void 0,finishReason:$.finishReason,messages:F3(Q,$.finishReason)};default:return Q}}function U1(Q,$){if(!Q.some((Z)=>Z.runId===$&&Z.finishReason===void 0))return Q;return Q.map((Z)=>{if(Z.runId!==$||Z.finishReason!==void 0)return Z;let{runId:J,...W}=Z;return{...W,content:[]}})}function F3(Q,$){return Q.messages.map((Z)=>Z.role==="assistant"&&Q.runMessageIds.includes(Z.id)?D1(Z,$):Z)}function D1(Q,$){let Z=Q.content.map((W)=>W.type==="tool-call"&&W.nested?.some((G)=>G.finishReason===void 0)?{...W,nested:W.nested.map((G)=>G.finishReason===void 0?F1(G,$):G)}:W);if(Q.finishReason===void 0)return{...Q,finishReason:$,content:Z};return Z.some((W,G)=>W!==Q.content[G])?{...Q,content:Z}:Q}function F1(Q,$){let Z={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((J)=>J.id),loadedTools:[]};return{...Q,finishReason:$,messages:F3(Z,$)}}function H3(Q,$,Z){for(let J=Q.messages.length-1;J>=0;J--){let W=Q.messages[J],G=W.content.findIndex((V)=>V.type==="tool-call"&&V.toolCallId===$);if(G===-1)continue;if(W.finishReason!==void 0&&!L1(Q,W,$))return Q;let X=W.content.slice();X[G]=Z(X[G]);let Y=Q.messages.slice();Y[J]={...W,content:X};let H=Q.runMessageIds.includes(W.id)?Q.runMessageIds:[...Q.runMessageIds,W.id];return{...Q,runMessageIds:H,messages:Y}}return Q}function j1(Q,$,Z){let J={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((G)=>G.id),loadedTools:[],finishReason:Q.finishReason},W=D3(J,$.event,Z);return{...Q,...$.label!==void 0?{label:$.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function L1(Q,$,Z){if($.finishReason!=="awaiting-input")return!1;return!Q.messages.some((J)=>J.content.some((W)=>W.type==="tool-result"&&W.toolCallId===Z))}function K3(Q,$){let Z=Q.messages.find((J)=>J.id===$);return Z!==void 0&&Z.finishReason!==void 0}function d(Q,$,Z,J){let W=Q.messages.findIndex((Y)=>Y.id===$),G=Q.runMessageIds.includes($)?Q.runMessageIds:[...Q.runMessageIds,$];if(W===-1){let Y={id:$,role:"assistant",content:[],createdAt:Z};return{...Q,runMessageIds:G,messages:[...Q.messages,J(Y)]}}let X=Q.messages.slice();return X[W]=J(X[W]),{...Q,runMessageIds:G,messages:X}}function C1(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 P1(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 B3(Q,$,Z){let J=Q.findIndex(Z);if(J===-1)return[...Q,$];let W=Q.slice();return W[J]=$,W}class i9{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=z3({messages:Z})}finish(Q){if(this.closed)return;this.done.add(Q.id),this.write(()=>[l9(Q)])}frame(Q){if(this.closed)return;let $=Q.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=U3(this.state,Q),$.type){case"message":this.write(()=>[l9($.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=l9($);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 l9(Q){return structuredClone(Q)}async function j3(Q,$){let Z=[],J=null,W=Q.slice();for(let G=0;G<W.length;G++){let X=W[G];if(X.role!=="assistant"||X.finishReason!==void 0)continue;if(X.runId&&await $(X.runId))continue;J??=new Set(Q.flatMap((V)=>V.content.flatMap((K)=>K.type==="tool-result"?[K.toolCallId]:[])));let Y=X.content.map((V)=>V.type==="tool-call"?L3(V):V);for(let V of X.content){if(V.type!=="tool-call"||J.has(V.toolCallId))continue;let K={type:"tool-result",toolCallId:V.toolCallId,name:V.name,status:"denied",cause:"interrupted"};Y.push(K)}let H={...X,content:Y,finishReason:"interrupted"};W[G]=H,Z.push(H)}return{messages:W,settled:Z}}function L3(Q){let{partial:$,...Z}=Q;if(!Z.nested?.some((J)=>J.finishReason===void 0))return Z;return{...Z,nested:Z.nested.map(q1)}}function q1(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"?L3(Z):Z)}:$)}}var O1=A3,yQ=new Map,C3=new WeakMap,gQ=new Map,N1=4194304,_1=1000,M1=5,P3=65536,w3=()=>{};class I3{byKey=new Map;take(Q,$,Z){let J=this.byKey.get(Q);if(!J?.has($)&&(J?.size??0)>=Z)return null;if(!J)J=new Map,this.byKey.set(Q,J);J.set($,(J.get($)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let G=this.byKey.get(Q),X=(G?.get($)??1)-1;if(!G)return;if(X>0)G.set($,X);else if(G.delete($),G.size===0)this.byKey.delete(Q)}}}var q3=new WeakMap;function S1(Q){let $=q3.get(Q);if(!$)$=new I3,q3.set(Q,$);return $}class r9 extends O1{static kind="agent-controller";store=d9;liveRuns=g9;attachments=SQ;attachmentStorage=x3;fileOwners=u9;nonces=i;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions(Q,$){}context(Q,$){return{}}requireThread=!1;maxBodyBytes=N1;maxHistoryMessages=_1;contextWindow=void 0;prepareStep(Q,$){}maxConcurrentRuns=M1;runLimitKey(Q,$){return $.owner}authorizeRequest(Q,$){}runOwner(Q){let $=Q.ctx?.()?.user,Z=$?.id??$?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}async stream(Q=new zQ){let $=await o9(Q,this.maxBodyBytes);if($.error)return uQ($);let Z=$.body,J=typeof Z.threadId==="string"?Z.threadId:void 0,W=w1(Z);if(W.error)return uQ({body:{},error:W.error});let G=W.turn,X=J!==void 0&&Z.regenerate===!0,Y=typeof Z.clientRunId==="string"?Z.clientRunId:void 0,H=v3(Z);if(this.requireThread&&!J)return b(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(X&&!this.store.removeMessages)return b(501,{code:"regenerate_unsupported",message:"This agent's store cannot remove messages, so a thread's answer cannot be regenerated. Implement `removeMessages` on the AgentStore."});if(!J&&Array.isArray(Z.messages)&&Z.messages.length>this.maxHistoryMessages)return t9(413,"history_too_long",`The conversation has ${Z.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let V=await this.runOwner(Q),K=Y?{cancelled:!1,owner:V}:null;if(K)gQ.set(Y,K);let z=null,B=[],U=async()=>{try{return await F()}finally{if(J&&B.length>0&&z===null)await this.store.appendMessages(J,B).catch((D)=>this.reportHookFailure(D))}},F=async()=>{let D;if(J){let P=await this.store.loadThread(J);if(!P)return b(404,{code:"thread_not_found",message:`Thread ${J} does not exist here, or has expired.`});if(D=await this.settleThread(J,P,{write:!0}),X){let q=h1(D);if(!q)return b(409,{code:"nothing_to_regenerate",message:`Thread ${J} has no user turn to answer again.`});B=D.slice(q.index),await this.store.removeMessages(J,B.map((g3)=>g3.id)),D=D.slice(0,q.index),G=G?.localId?{...q.turn,localId:G.localId}:q.turn}}else D=Array.isArray(Z.messages)?Z.messages:[],d1(this.nonces);let j=await this.instructions(Q,{body:H})||void 0,L=await this.context(Q,{body:H}),S=await this.attachmentsFor(Q,J,{body:H});if(K?.cancelled)return S3();let N=J?new i9(this.store,J,D,(P)=>this.reportHookFailure(P)):null,v=`run_${crypto.randomUUID()}`,E={req:Q,runId:v,threadId:J},_=this.agent.stream({runId:v,messages:D,turn:G,threadId:J,...N?{onMessage:(P)=>N.finish(P)}:{},instructions:j,context:L,attachments:S,body:H,redactError:(P,q)=>this.redactError(P,q,E),nonces:this.nonces,receipts:this.receipts,subject:V,...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...this.prepareStep!==r9.prototype.prepareStep?{prepareStep:(P)=>this.prepareStep(P,E)}:{}}),w=this.liveRuns.register(_,{threadId:J,owner:V,clientRunId:Y,onEvent:(P)=>this.dispatchEvent(P,E),onInternalError:(P)=>this.reportHookFailure(P),maxRunDurationMs:this.agent.maxRunDurationMs});if(z=_,N)this.follow(_,N);let{stored:O,hooks:C}=this.persistRun(_,E,w,N);return C3.set(_,O),Q.ctx?.()?.waitUntil(C),_.toResponse()};try{await this.authorizeRequest(Q,{route:"stream",threadId:J,body:H});let D=await this.foreignFile([...G?.files??[],...J?[]:g1(Z.messages)],V);if(D)return D;if(K?.cancelled)return S3();let j=await this.runLimitKey(Q,{owner:V,threadId:J}),L=j===null?w3:S1(this.liveRuns).take(j,J?`thread:${J}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!L)return t9(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);try{return J?await this.withThread(J,V,U):await U()}finally{let S=z;if(S)S.result().then(L,L);else L()}}finally{if(K&&gQ.get(Y)===K)gQ.delete(Y)}}async withThread(Q,$,Z){let J=yQ.get(Q)??Promise.resolve(),W,G=new Promise((Y)=>{W=Y}),X=J.then(()=>G);yQ.set(Q,X),await J;try{let Y=await this.liveRuns.find({threadId:Q});if(Y&&this.liveRuns.isRunning(Y.runId)&&!this.liveRuns.mayAccess(Y.runId,$))return cQ();let H=Y?this.liveRuns.get(Y.runId):null;if(H)H.stop({reason:"superseded by a later turn on this thread"}),await C3.get(H);return await Z()}finally{if(W(),yQ.get(Q)===X)yQ.delete(Q)}}async attach(Q=new zQ){let $=await o9(Q,P3);if($.error)return uQ($);let Z=$.body,J=typeof Z.threadId==="string"?Z.threadId:f1(Q,"threadId");if(!J)return b(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 W=await this.liveRuns.find({threadId:J});if(W&&!this.liveRuns.mayAccess(W.runId,await this.runOwner(Q)))return cQ();if(!W)return b(404,{code:"no_live_run",message:`No run in progress for thread ${J} in this process.`});let G=typeof Z.runId==="string"?Z.runId:void 0,X=G&&G!==W.runId?void 0:v1(Q,Z);try{return q$(this.liveRuns.replay(W.runId,X))}catch(Y){if(Y instanceof e)return b(410,{code:Y.code,message:Y.message,oldestSeq:Y.oldest});if(Y instanceof BQ)return b(404,{code:Y.code,message:Y.message});throw Y}}async stop(Q=new zQ){let $=await o9(Q,P3);if($.error)return uQ($);let Z=$.body;await this.authorizeRequest(Q,{route:"stop",threadId:typeof Z.threadId==="string"?Z.threadId:void 0});let J=await this.runOwner(Q),W=typeof Z.runId==="string"?Z.runId:void 0;if(!W&&typeof Z.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId(Z.clientRunId)??void 0,!W){let X=gQ.get(Z.clientRunId);if(X){if(X.owner!==null&&X.owner!==J)return cQ();return X.cancelled=!0,{stopped:!0}}}}if(!W&&typeof Z.threadId==="string")W=(await this.liveRuns.find({threadId:Z.threadId}))?.runId;let G=W?this.liveRuns.get(W):null;if(!G)return{stopped:!1};if(!this.liveRuns.mayAccess(G.runId,J))return cQ();return G.stop({reason:typeof Z.reason==="string"?Z.reason:void 0}),{stopped:!0}}attachmentScope(Q,$,Z){let J=Q.ctx()?.user,W=J?.id??J?.publicId;if(W!==void 0&&W!==null&&String(W)!=="")return{key:`user:${String(W)}`};if($)return{key:`thread:${$}`};return null}attachmentLimits(Q){return null}attachmentDestination(Q,$){return"both"}async attachmentsFor(Q,$,Z={body:{}}){let J=await this.attachmentScope(Q,$,Z);if(!J)return null;return new VQ(this.attachments,this.attachmentStorage,J)}async upload(Q=new zQ){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",W=Z.type||"application/octet-stream",G=T1($.get("body")),X=$.get("threadId");await this.authorizeRequest(Q,{route:"upload",threadId:typeof X==="string"&&X.length>0?X:void 0,body:G});let Y=k1(await this.attachmentLimits(Q),Z,J,W);if(Y)throw new f3(Y.code,Y.message);let H=typeof X==="string"&&X.length>0&&await this.store.loadThread(X)!==null?X:void 0,V=await this.runOwner(Q),K=(N)=>this.fileOwners.record(N,{owner:V,name:J,mimeType:W,size:Z.size,createdAt:new Date().toISOString()}),z=await this.attachmentDestination(Z,Q),B=u1(z,$.get("destination")),U=await this.attachmentScope(Q,H,{body:G}),F=B!=="provider"&&!U;if(F){if(B==="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()`.');c1()}if(B==="provider"||!U){let N=await O3(this.agent.provider,Z);await K(N);let v={fileId:N,name:J,mimeType:W,size:Z.size,destination:"provider"};if(F)v.downgraded="no_scope";return v}let D=eQ(),j=await this.attachmentStorage.put({name:Q9(D,J),body:Z,contentType:W}),L=B==="both"?await O3(this.agent.provider,Z):void 0;if(L)await K(L);let S={id:D,scopeKey:U.key,fileId:L,objectName:j,name:J,mimeType:W,size:Z.size,createdAt:new Date().toISOString(),destination:B};return await this.attachments.put(U,S),{fileId:L,attachmentId:D,name:J,mimeType:W,size:Z.size,destination:B}}async foreignFile(Q,$){let Z=new Set(Q.map((J)=>J.fileId).filter((J)=>typeof J==="string"));for(let J of Z){let W=await this.fileOwners.get(J);if(W?W.owner!==null&&W.owner!==$:this.requireKnownFiles)return y1()}return null}onMessage(Q,$){}onToolCall(Q,$){}onAwaitingInput(Q,$){}redactError(Q,$,Z){return a9(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(b3(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:W}=await j3($,(G)=>this.isRunLive(G,Q));if(Z&&W.length>0)try{await this.store.appendMessages(Q,W)}catch(G){this.reportHookFailure(G)}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 W=Promise.resolve(),G=(async()=>{let Y;try{Y=await Q.result()}catch(V){J?.close(),await J?.settled(),W=this.safely(()=>this.onError({code:"unknown",message:V instanceof Error?V.message:String(V),retryable:!1},$));return}let H=Y.messages;if(J?.close(H),await J?.settled(),$.threadId&&H.length>0)try{await this.store.appendMessages($.threadId,H)}catch(V){this.reportHookFailure(V)}W=this.notifyRun(Y,H,$)})(),X=G.then(()=>p1(Promise.all([W,Z]).then(()=>{}),this.hookHoldMs));return{stored:G,hooks:X}}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 n9=["turn","clientRunId","threadId","messages","regenerate"],R1=["text","files","toolResults"];function v3(Q,$=y3(Q)?n9:[...n9,...R1]){let Z={};for(let[J,W]of Object.entries(Q)){if($.includes(J))continue;Object.defineProperty(Z,J,{value:W,writable:!0,enumerable:!0,configurable:!0})}return Z}function T1(Q){if(Q===null)return{};let $;if(typeof Q==="string")try{$=JSON.parse(Q)}catch{throw new s9("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new s9("The upload's `body` field must be a JSON object.");return v3($,n9)}class s9 extends mQ{constructor(Q){super(Q);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:Q}}},view:{}}}}async function O3(Q,$){try{return await Q.upload($)}catch(Z){if(Z instanceof h&&A1.has(Z.status))throw new h3(A(Z).message);throw Z}}var A1=new Set([400,413,415,422]);class f3 extends mQ{constructor(Q,$){super($);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:Q,message:$}}},view:{}}}}function k1(Q,$,Z,J){if(!Q)return null;let{maxBytes:W,accept:G}=Q;if(typeof W==="number"&&$.size>W)return{code:"file_too_large",message:`${JSON.stringify(Z)} is ${N3($.size)}; the limit is ${N3(W)}.`};if(G&&G.length>0&&!G.some((X)=>E1(X,Z,J)))return{code:"unsupported_file_type",message:`${JSON.stringify(Z)} is not a type this chat accepts. Accepted: ${G.join(", ")}.`};return null}function E1(Q,$,Z){let J=Q.trim().toLowerCase();if(!J)return!1;if(J.startsWith("."))return $.toLowerCase().endsWith(J);let W=Z.toLowerCase().split(";")[0].trim();if(J.endsWith("/*"))return W.startsWith(J.slice(0,-1));return W===J}function N3(Q){if(Q<1024)return`${Q} B`;let $=["KB","MB","GB"],Z=Q/1024,J=0;while(Z>=1024&&J<$.length-1)Z/=1024,J++;return`${Math.round(Z*10)/10} ${$[J]}`}class h3 extends mQ{constructor(Q){super(Q);this.name="RejectedUploadError";let $=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test(Q)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:$,message:Q}}},view:{}}}}async function o9(Q,$){let Z=Q?.rawRequest;if(!Z||Z.method==="GET"||Z.method==="HEAD"||!Z.body)return{body:{}};if(!x1(Z.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let J=Number(Z.headers.get("Content-Length"));if(Number.isFinite(J)&&J>$)return _3($);let W;try{let X=await b1(Z,$);if(X===null)return _3($);W=X}catch{return{body:{},error:"The request body could not be read."}}if(!W.trim())return{body:{}};let G;try{G=JSON.parse(W)}catch{return{body:{},error:"The request body is not valid JSON."}}if(G===null||typeof G!=="object"||Array.isArray(G))return{body:{},error:"The request body must be a JSON object."};return{body:G}}function x1(Q){return E3(Q)==="application/json"}async function b1(Q,$){if(!Number.isFinite($)||!Q.body)return await Q.text();let Z=Q.body.getReader(),J=[],W=0;for(;;){let{done:Y,value:H}=await Z.read();if(Y)break;if(W+=H.byteLength,W>$)return await Z.cancel().catch(w3),null;J.push(H)}let G=new Uint8Array(W),X=0;for(let Y of J)G.set(Y,X),X+=Y.byteLength;return new TextDecoder().decode(G)}function _3(Q){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${Q} bytes).`}}function t9(Q,$,Z){return b(Q,{...pQ(k3(Q),Z,Q),code:$})}function uQ(Q){if(Q.status===413)return t9(413,Q.code??"body_too_large",Q.error??"");return b(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function y3(Q){return Boolean(Q.turn)&&typeof Q.turn==="object"}function w1(Q){let $=y3(Q)?Q.turn:Q,Z={};if(typeof $.text==="string")Z.text=$.text;if(Array.isArray($.files)){let J=I1($.files);if(typeof J==="string")return{error:J};Z.files=J}if(Array.isArray($.toolResults))Z.toolResults=$.toolResults;if(Object.keys(Z).length===0)return{};if($===Q.turn&&$.localId!==void 0&&$.localId!==null&&$.localId!==""){let{localId:J}=$;if(typeof J!=="string")return{error:"turn.localId must be a string."};if(J.length>M3)return{error:`turn.localId is longer than ${M3} characters.`};Z.localId=J}return{turn:Z}}var M3=200;function I1(Q){let $=[];for(let[Z,J]of Q.entries()){let W=`turn.files[${Z}]`;if(!J||typeof J!=="object"||Array.isArray(J))return`${W} must be an object.`;let G={};for(let K of["fileId","attachmentId","name","mimeType"]){let z=J[K];if(z===void 0||z===null||z==="")continue;if(typeof z!=="string")return`${W}.${K} must be a string.`;G[K]=z}let{fileId:X,attachmentId:Y,name:H,mimeType:V}=G;if(X?.startsWith(f))return`${W}.fileId holds a gemi attachment id (${X}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(Y!==void 0&&!Y.startsWith(f))return`${W}.attachmentId is not a gemi attachment id: it must start with "${f}".`;if(!X&&!Y)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...X?{fileId:X}:{},...Y?{attachmentId:Y}:{},...H!==void 0?{name:H}:{},...V!==void 0?{mimeType:V}:{}})}return $}function v1(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 f1(Q,$){let Z=Q?.search?.get($);return typeof Z==="string"?Z:void 0}function h1(Q){let $=u(Q);for(let Z=Q.length-1;Z>=0;Z--){let J=Q[Z];if(J.role!=="user"||$.has(J.id))continue;let W="",G=[];for(let X of J.content){if(X.type==="text")W+=X.text;if(X.type==="file")G.push({...X.fileId?{fileId:X.fileId}:{},...X.attachmentId?{attachmentId:X.attachmentId}:{},...X.name?{name:X.name}:{},...X.mimeType?{mimeType:X.mimeType}:{}})}if(!W&&G.length===0)continue;return{index:Z,turn:{...W?{text:W}:{},...G.length>0?{files:G}:{}}}}return null}function S3(){return b(409,{code:"stopped",message:"The turn was stopped before it started."})}function cQ(){return b(403,pQ("permission","This run belongs to someone else.",403))}function y1(){return b(403,pQ("permission","A file in this turn was uploaded by someone else.",403))}function g1(Q){if(!Array.isArray(Q))return[];let $=[];for(let Z of Q){let J=Z?.content;if(!Array.isArray(J))continue;for(let W of J)if(W&&typeof W==="object"&&typeof W.fileId==="string")$.push({fileId:W.fileId})}return $}function b(Q,$){return new Response(JSON.stringify({error:$}),{status:Q,headers:{"Content-Type":"application/json"}})}function u1(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 R3=!1;function c1(){if(R3)return;R3=!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 m1=2147483647;function p1(Q,$){let Z=Q.then(()=>{},()=>{});if(!($<=m1))return Z;let J,W=new Promise((G)=>{J=setTimeout(G,$)});return Promise.race([Z,W]).finally(()=>clearTimeout(J))}var T3=!1;function d1(Q){if(T3||Bun.env.NODE_ENV!=="production")return;if(!(Q instanceof WQ))return;T3=!0,console.warn("[gemi/ai] A stateless agent chat is spending approval nonces in process memory. With more than one instance a replayed approval is accepted once per instance. Set `nonces = new RedisNonceStore()` (or your own NonceStore) on the AgentController.")}export{G9 as windowMessages,W9 as turnStarts,SZ as toAgentTools,QQ as supportsStrict,HZ as splitTurns,i1 as s,a9 as redactError,N$ as messageSize,g9 as liveRuns,u as injectedMessageIds,l3 as generate,K1 as evalChain,i as defaultNonceStore,u9 as defaultFileOwners,SQ as defaultAttachmentStore,d9 as defaultAgentStore,n as ToolNamespace,T as ToolError,z9 as Skill,VQ as ScopedAttachments,YQ as SKILLS_NAMESPACE,p9 as RedisReceiptStore,lQ as RedisNonceStore,c as PendingEscalation,I9 as OpenAIProvider,O9 as OpenAIImageProvider,m9 as MemoryReceiptStore,WQ as MemoryNonceStore,vQ as MemoryLiveRuns,fQ as MemoryFileOwners,IQ as MemoryCircuitStore,MQ as MemoryAttachmentStore,hQ as MemoryAgentStore,BQ as LiveRunNotFoundError,l1 as JSONSchemaError,o as InvalidAttachmentScopeError,xQ as ImageRequestError,bQ as ImageProvider,C9 as ImageModel,e as FrameCursorEvictedError,KQ as FallbackProvider,F9 as DEFAULT_MAX_RUN_DURATION_MS,_$ as DEFAULT_CONTEXT_WINDOW_STEP,M$ as DEFAULT_CONTEXT_WINDOW_NOTE,v9 as AzureOpenAIProvider,N9 as AzureOpenAIImageProvider,XQ as AttachmentNotFoundError,m as AgentTool,JQ as AgentRunError,r as AgentProvider,r9 as AgentController,j9 as Agent};
|
|
24
|
+
return 0`;class d9{injectedClient;prefix;constructor(Q={}){this.injectedClient=Q.client,this.prefix=Q.prefix??"gemi:ai:receipt"}async claim(Q,$){let Z=await this.client.send("EVAL",[z1,"1",this.key(Q),Y3,H3($)]);if(Z==="claimed")return{status:"claimed"};let J=String(Z??"");if(J.startsWith(m9))return{status:"replay",result:JSON.parse(J.slice(m9.length))};return{status:"blocked"}}async complete(Q,$,Z){await this.client.send("SET",[this.key(Q),m9+JSON.stringify($),"PX",H3(Z)])}async release(Q){await this.client.send("EVAL",[U1,"1",this.key(Q),Y3])}key(Q){return`${this.prefix}:${Q}`}get client(){if(this.injectedClient)return this.injectedClient;let Q=qQ(),$=Q.bound(i)?Q.make(i).client:void 0;if(!$)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return $}}function H3(Q){return String(Math.max(1,Math.ceil(Q-Date.now())))}class yQ{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 W=Z.messages.findIndex((G)=>G.id===J.id);if(W===-1)Z.messages.push(J);else Z.messages[W]=J}Z.touchedAt=Date.now()}async removeMessages(Q,$){this.sweep();let Z=this.threads.get(Q);if(!Z)return;let J=new Set($);Z.messages=Z.messages.filter((W)=>!J.has(W.id)),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 l9=new yQ;function U3(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 D3(Q,$,Z=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==Q.cursorRunId)&&$.seq<=Q.seq)return Q;return{...F3(Q,$.event,Z),seq:$.seq}}function F3(Q,$,Z){switch($.type){case"run-start":return{...Q,messages:D1(Q.messages,$.runId),runId:$.runId,cursorRunId:$.runId,threadId:$.threadId??Q.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return l(Q,$.messageId,Z,(J)=>({...J,role:$.role}));case"text-delta":if(B3(Q,$.messageId))return Q;return l(Q,$.messageId,Z,(J)=>({...J,content:P1(J.content,$.delta)}));case"reasoning-delta":if(B3(Q,$.messageId))return Q;return l(Q,$.messageId,Z,(J)=>({...J,content:q1(J.content,$.delta,$.id)}));case"output-delta":return l(Q,$.messageId,Z,(J)=>({...J,content:z3(J.content,{type:"output",value:$.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return l(Q,$.messageId,Z,(J)=>{let W=J.content.findIndex((z)=>z.type==="tool-call"&&z.toolCallId===$.part.toolCallId),G=W===-1?void 0:J.content[W],X=$.part.progress??G?.progress,Y=$.part.nested??G?.nested,H=$.part.attachments??G?.attachments,V={...$.part,...X?{progress:X}:{},...Y?{nested:Y}:{},...H?{attachments:H}:{}},K=J.content.slice();if(W===-1)K.push(V);else K[W]=V;return{...J,content:K}});case"tool-search":{let J=$.loaded.filter((W)=>!Q.loadedTools.includes(W));if(J.length===0)return Q;return{...Q,loadedTools:[...Q.loadedTools,...J]}}case"tool-progress":return K3(Q,$.toolCallId,(J)=>({...J,progress:[...J.progress??[],$.data]}));case"nested-event":{let J=$;return K3(Q,$.toolCallId,(W)=>{let G=W.nested??[],X=G.findIndex((K)=>K.runId===J.runId),Y=G[X]??{runId:J.runId,agent:J.agent,messages:[]},H=L1(Y,J,Z),V=X===-1?[...G,H]:G.map((K,z)=>z===X?H:K);return{...W,nested:V}})}case"tool-result":{let J=l(Q,$.messageId,Z,(W)=>({...W,content:z3(W.content,$.part,(G)=>G.type==="tool-result"&&G.toolCallId===$.part.toolCallId)}));return{...J,pending:J.pending.filter((W)=>W.toolCallId!==$.part.toolCallId)}}case"message":{let J=Q.messages.findIndex((X)=>X.id===$.message.id),W=Q.messages.slice();if(J===-1)W.push($.message);else W[J]=$.message;let G=Q.runMessageIds.includes($.message.id)?Q.runMessageIds:[...Q.runMessageIds,$.message.id];return{...Q,messages:W,runMessageIds:G}}case"message-id":{let J=Q.messages.findIndex((G)=>G.id===$.localId);if(J===-1){if(!$.message||Q.messages.some((G)=>G.id===$.messageId))return Q;return{...Q,messages:[...Q.messages,$.message]}}let W=Q.messages.some((G)=>G.id===$.messageId)?Q.messages.filter((G,X)=>X!==J):Q.messages.map((G,X)=>X===J?{...G,id:$.messageId}:G);return{...Q,messages:W}}case"awaiting-input":return{...Q,runId:$.runId,pending:[...$.pending]};case"message-end":return l(Q,$.messageId,Z,(J)=>({...J,finishReason:$.finishReason,...$.outputTruncated?{outputTruncated:!0}:{},...$.usage?{usage:$.usage}:{},content:$.outputTruncated||$.finishReason==="length"?J.content.filter((W)=>!(W.type==="output"&&W.partial)):J.content.map((W)=>W.type==="output"&&W.partial?{...W,partial:!1}:W)}));case"usage":return{...Q,usage:$.usage};case"error":return{...Q,error:$.error,pending:[]};case"run-end":return{...Q,runId:void 0,finishReason:$.finishReason,messages:j3(Q,$.finishReason)};default:return Q}}function D1(Q,$){if(!Q.some((Z)=>Z.runId===$&&Z.finishReason===void 0))return Q;return Q.map((Z)=>{if(Z.runId!==$||Z.finishReason!==void 0)return Z;let{runId:J,...W}=Z;return{...W,content:[]}})}function j3(Q,$){return Q.messages.map((Z)=>Z.role==="assistant"&&Q.runMessageIds.includes(Z.id)?F1(Z,$):Z)}function F1(Q,$){let Z=Q.content.map((W)=>W.type==="tool-call"&&W.nested?.some((G)=>G.finishReason===void 0)?{...W,nested:W.nested.map((G)=>G.finishReason===void 0?j1(G,$):G)}:W);if(Q.finishReason===void 0)return{...Q,finishReason:$,content:Z};return Z.some((W,G)=>W!==Q.content[G])?{...Q,content:Z}:Q}function j1(Q,$){let Z={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((J)=>J.id),loadedTools:[]};return{...Q,finishReason:$,messages:j3(Z,$)}}function K3(Q,$,Z){for(let J=Q.messages.length-1;J>=0;J--){let W=Q.messages[J],G=W.content.findIndex((V)=>V.type==="tool-call"&&V.toolCallId===$);if(G===-1)continue;if(W.finishReason!==void 0&&!C1(Q,W,$))return Q;let X=W.content.slice();X[G]=Z(X[G]);let Y=Q.messages.slice();Y[J]={...W,content:X};let H=Q.runMessageIds.includes(W.id)?Q.runMessageIds:[...Q.runMessageIds,W.id];return{...Q,runMessageIds:H,messages:Y}}return Q}function L1(Q,$,Z){let J={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((G)=>G.id),loadedTools:[],finishReason:Q.finishReason},W=F3(J,$.event,Z);return{...Q,...$.label!==void 0?{label:$.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function C1(Q,$,Z){if($.finishReason!=="awaiting-input")return!1;return!Q.messages.some((J)=>J.content.some((W)=>W.type==="tool-result"&&W.toolCallId===Z))}function B3(Q,$){let Z=Q.messages.find((J)=>J.id===$);return Z!==void 0&&Z.finishReason!==void 0}function l(Q,$,Z,J){let W=Q.messages.findIndex((Y)=>Y.id===$),G=Q.runMessageIds.includes($)?Q.runMessageIds:[...Q.runMessageIds,$];if(W===-1){let Y={id:$,role:"assistant",content:[],createdAt:Z};return{...Q,runMessageIds:G,messages:[...Q.messages,J(Y)]}}let X=Q.messages.slice();return X[W]=J(X[W]),{...Q,runMessageIds:G,messages:X}}function P1(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 q1(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 z3(Q,$,Z){let J=Q.findIndex(Z);if(J===-1)return[...Q,$];let W=Q.slice();return W[J]=$,W}class o9{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=U3({messages:Z})}finish(Q){if(this.closed)return;this.done.add(Q.id),this.write(()=>[i9(Q)])}frame(Q){if(this.closed)return;let $=Q.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=D3(this.state,Q),$.type){case"message":this.write(()=>[i9($.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=i9($);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 i9(Q){return structuredClone(Q)}async function L3(Q,$){let Z=[],J=null,W=Q.slice();for(let G=0;G<W.length;G++){let X=W[G];if(X.role!=="assistant"||X.finishReason!==void 0)continue;if(X.runId&&await $(X.runId))continue;J??=new Set(Q.flatMap((V)=>V.content.flatMap((K)=>K.type==="tool-result"?[K.toolCallId]:[])));let Y=X.content.map((V)=>V.type==="tool-call"?C3(V):V);for(let V of X.content){if(V.type!=="tool-call"||J.has(V.toolCallId))continue;let K={type:"tool-result",toolCallId:V.toolCallId,name:V.name,status:"denied",cause:"interrupted"};Y.push(K)}let H={...X,content:Y,finishReason:"interrupted"};W[G]=H,Z.push(H)}return{messages:W,settled:Z}}function C3(Q){let{partial:$,...Z}=Q;if(!Z.nested?.some((J)=>J.finishReason===void 0))return Z;return{...Z,nested:Z.nested.map(O1)}}function O1(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"?C3(Z):Z)}:$)}}var N1=k3,gQ=new Map,P3=new WeakMap,uQ=new Map,_1=4194304,M1=1000,S1=5,q3=65536,I3=()=>{};class v3{byKey=new Map;take(Q,$,Z){let J=this.byKey.get(Q);if(!J?.has($)&&(J?.size??0)>=Z)return null;if(!J)J=new Map,this.byKey.set(Q,J);J.set($,(J.get($)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let G=this.byKey.get(Q),X=(G?.get($)??1)-1;if(!G)return;if(X>0)G.set($,X);else if(G.delete($),G.size===0)this.byKey.delete(Q)}}}var O3=new WeakMap;function R1(Q){let $=O3.get(Q);if(!$)$=new v3,O3.set(Q,$);return $}class e9 extends N1{static kind="agent-controller";store=l9;liveRuns=u9;attachments=RQ;attachmentStorage=b3;fileOwners=c9;nonces=o;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions(Q,$){}context(Q,$){return{}}requireThread=!1;maxBodyBytes=_1;maxHistoryMessages=M1;contextWindow=void 0;prepareStep(Q,$){}maxConcurrentRuns=S1;runLimitKey(Q,$){return $.owner}authorizeRequest(Q,$){}runOwner(Q){let $=Q.ctx?.()?.user,Z=$?.id??$?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}async stream(Q=new UQ){let $=await n9(Q,this.maxBodyBytes);if($.error)return cQ($);let Z=$.body,J=typeof Z.threadId==="string"?Z.threadId:void 0,W=I1(Z);if(W.error)return cQ({body:{},error:W.error});let G=W.turn,X=J!==void 0&&Z.regenerate===!0,Y=typeof Z.clientRunId==="string"?Z.clientRunId:void 0,H=f3(Z);if(this.requireThread&&!J)return w(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(X&&!this.store.removeMessages)return w(501,{code:"regenerate_unsupported",message:"This agent's store cannot remove messages, so a thread's answer cannot be regenerated. Implement `removeMessages` on the AgentStore."});if(!J&&Array.isArray(Z.messages)&&Z.messages.length>this.maxHistoryMessages)return a9(413,"history_too_long",`The conversation has ${Z.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let V=await this.runOwner(Q),K=Y?{cancelled:!1,owner:V}:null;if(K)uQ.set(Y,K);let z=null,B=[],U=async()=>{try{return await F()}finally{if(J&&B.length>0&&z===null)await this.store.appendMessages(J,B).catch((D)=>this.reportHookFailure(D))}},F=async()=>{let D;if(J){let C=await this.store.loadThread(J);if(!C)return w(404,{code:"thread_not_found",message:`Thread ${J} does not exist here, or has expired.`});if(D=await this.settleThread(J,C,{write:!0}),X){let h=y1(D);if(!h)return w(409,{code:"nothing_to_regenerate",message:`Thread ${J} has no user turn to answer again.`});B=D.slice(h.index),await this.store.removeMessages(J,B.map((u3)=>u3.id)),D=D.slice(0,h.index),G=G?.localId?{...h.turn,localId:G.localId}:h.turn}}else D=Array.isArray(Z.messages)?Z.messages:[],l1(this.nonces);let j=await this.instructions(Q,{body:H})||void 0,L=await this.context(Q,{body:H}),S=await this.attachmentsFor(Q,J,{body:H});if(K?.cancelled)return R3();let O=J?new o9(this.store,J,D,(C)=>this.reportHookFailure(C)):null,v=`run_${crypto.randomUUID()}`,k={req:Q,runId:v,threadId:J},R={id:null,notified:Promise.resolve()},N=this.agent.stream({runId:v,messages:D,turn:G,threadId:J,...O?{onMessage:(C)=>O.finish(C)}:{},onTurn:(C)=>{if(R.id!==null)return;R.id=C.id;let h=O?O.settled():Promise.resolve();R.notified=h.then(()=>this.safely(()=>this.onMessage(C,k)))},instructions:j,context:L,attachments:S,body:H,redactError:(C,h)=>this.redactError(C,h,k),nonces:this.nonces,receipts:this.receipts,subject:V,...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...this.prepareStep!==e9.prototype.prepareStep?{prepareStep:(C)=>this.prepareStep(C,k)}:{}}),q=this.liveRuns.register(N,{threadId:J,owner:V,clientRunId:Y,onEvent:(C)=>this.dispatchEvent(C,k),onInternalError:(C)=>this.reportHookFailure(C),maxRunDurationMs:this.agent.maxRunDurationMs});if(z=N,O)this.follow(N,O);let{stored:P,hooks:_}=this.persistRun(N,k,q,O,R);return P3.set(N,P),Q.ctx?.()?.waitUntil(_),N.toResponse()};try{await this.authorizeRequest(Q,{route:"stream",threadId:J,body:H});let D=await this.foreignFile([...G?.files??[],...J?[]:u1(Z.messages)],V);if(D)return D;if(K?.cancelled)return R3();let j=await this.runLimitKey(Q,{owner:V,threadId:J}),L=j===null?I3:R1(this.liveRuns).take(j,J?`thread:${J}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!L)return a9(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);try{return J?await this.withThread(J,V,U):await U()}finally{let S=z;if(S)S.result().then(L,L);else L()}}finally{if(K&&uQ.get(Y)===K)uQ.delete(Y)}}async withThread(Q,$,Z){let J=gQ.get(Q)??Promise.resolve(),W,G=new Promise((Y)=>{W=Y}),X=J.then(()=>G);gQ.set(Q,X),await J;try{let Y=await this.liveRuns.find({threadId:Q});if(Y&&this.liveRuns.isRunning(Y.runId)&&!this.liveRuns.mayAccess(Y.runId,$))return mQ();let H=Y?this.liveRuns.get(Y.runId):null;if(H)H.stop({reason:"superseded by a later turn on this thread"}),await P3.get(H);return await Z()}finally{if(W(),gQ.get(Q)===X)gQ.delete(Q)}}async attach(Q=new UQ){let $=await n9(Q,q3);if($.error)return cQ($);let Z=$.body,J=typeof Z.threadId==="string"?Z.threadId:h1(Q,"threadId");if(!J)return w(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 W=await this.liveRuns.find({threadId:J});if(W&&!this.liveRuns.mayAccess(W.runId,await this.runOwner(Q)))return mQ();if(!W)return w(404,{code:"no_live_run",message:`No run in progress for thread ${J} in this process.`});let G=typeof Z.runId==="string"?Z.runId:void 0,X=G&&G!==W.runId?void 0:f1(Q,Z);try{return O$(this.liveRuns.replay(W.runId,X))}catch(Y){if(Y instanceof QQ)return w(410,{code:Y.code,message:Y.message,oldestSeq:Y.oldest});if(Y instanceof zQ)return w(404,{code:Y.code,message:Y.message});throw Y}}async stop(Q=new UQ){let $=await n9(Q,q3);if($.error)return cQ($);let Z=$.body;await this.authorizeRequest(Q,{route:"stop",threadId:typeof Z.threadId==="string"?Z.threadId:void 0});let J=await this.runOwner(Q),W=typeof Z.runId==="string"?Z.runId:void 0;if(!W&&typeof Z.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId(Z.clientRunId)??void 0,!W){let X=uQ.get(Z.clientRunId);if(X){if(X.owner!==null&&X.owner!==J)return mQ();return X.cancelled=!0,{stopped:!0}}}}if(!W&&typeof Z.threadId==="string")W=(await this.liveRuns.find({threadId:Z.threadId}))?.runId;let G=W?this.liveRuns.get(W):null;if(!G)return{stopped:!1};if(!this.liveRuns.mayAccess(G.runId,J))return mQ();return G.stop({reason:typeof Z.reason==="string"?Z.reason:void 0}),{stopped:!0}}attachmentScope(Q,$,Z){let J=Q.ctx()?.user,W=J?.id??J?.publicId;if(W!==void 0&&W!==null&&String(W)!=="")return{key:`user:${String(W)}`};if($)return{key:`thread:${$}`};return null}attachmentLimits(Q){return null}attachmentDestination(Q,$){return"both"}async attachmentsFor(Q,$,Z={body:{}}){let J=await this.attachmentScope(Q,$,Z);if(!J)return null;return new YQ(this.attachments,this.attachmentStorage,J)}async upload(Q=new UQ){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",W=Z.type||"application/octet-stream",G=A1($.get("body")),X=$.get("threadId");await this.authorizeRequest(Q,{route:"upload",threadId:typeof X==="string"&&X.length>0?X:void 0,body:G});let Y=E1(await this.attachmentLimits(Q),Z,J,W);if(Y)throw new h3(Y.code,Y.message);let H=typeof X==="string"&&X.length>0&&await this.store.loadThread(X)!==null?X:void 0,V=await this.runOwner(Q),K=(O)=>this.fileOwners.record(O,{owner:V,name:J,mimeType:W,size:Z.size,createdAt:new Date().toISOString()}),z=await this.attachmentDestination(Z,Q),B=c1(z,$.get("destination")),U=await this.attachmentScope(Q,H,{body:G}),F=B!=="provider"&&!U;if(F){if(B==="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()`.');m1()}if(B==="provider"||!U){let O=await N3(this.agent.provider,Z);await K(O);let v={fileId:O,name:J,mimeType:W,size:Z.size,destination:"provider"};if(F)v.downgraded="no_scope";return v}let D=Q9(),j=await this.attachmentStorage.put({name:$9(D,J),body:Z,contentType:W}),L=B==="both"?await N3(this.agent.provider,Z):void 0;if(L)await K(L);let S={id:D,scopeKey:U.key,fileId:L,objectName:j,name:J,mimeType:W,size:Z.size,createdAt:new Date().toISOString(),destination:B};return await this.attachments.put(U,S),{fileId:L,attachmentId:D,name:J,mimeType:W,size:Z.size,destination:B}}async foreignFile(Q,$){let Z=new Set(Q.map((J)=>J.fileId).filter((J)=>typeof J==="string"));for(let J of Z){let W=await this.fileOwners.get(J);if(W?W.owner!==null&&W.owner!==$:this.requireKnownFiles)return g1()}return null}onMessage(Q,$){}onToolCall(Q,$){}onAwaitingInput(Q,$){}redactError(Q,$,Z){return r9(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(w3(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:W}=await L3($,(G)=>this.isRunLive(G,Q));if(Z&&W.length>0)try{await this.store.appendMessages(Q,W)}catch(G){this.reportHookFailure(G)}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,W={id:null,notified:Promise.resolve()}){let G=Promise.resolve(),X=(async()=>{let H;try{H=await Q.result()}catch(K){J?.close(),await J?.settled(),G=W.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:K instanceof Error?K.message:String(K),retryable:!1},$)));return}let V=H.messages;if(J?.close(V),await J?.settled(),$.threadId&&V.length>0)try{await this.store.appendMessages($.threadId,V)}catch(K){this.reportHookFailure(K)}G=this.notifyRun(H,V,$,W)})(),Y=X.then(()=>d1(Promise.all([G,Z]).then(()=>{}),this.hookHoldMs));return{stored:X,hooks:Y}}async notifyRun(Q,$,Z,J){await J.notified;for(let W of $){if(W.id===J.id)continue;await this.safely(()=>this.onMessage(W,Z))}await this.safely(()=>this.onStreamComplete(Q,Z))}async safely(Q){try{await Q()}catch($){this.reportHookFailure($)}}}var s9=["turn","clientRunId","threadId","messages","regenerate"],T1=["text","files","toolResults"];function f3(Q,$=g3(Q)?s9:[...s9,...T1]){let Z={};for(let[J,W]of Object.entries(Q)){if($.includes(J))continue;Object.defineProperty(Z,J,{value:W,writable:!0,enumerable:!0,configurable:!0})}return Z}function A1(Q){if(Q===null)return{};let $;if(typeof Q==="string")try{$=JSON.parse(Q)}catch{throw new t9("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new t9("The upload's `body` field must be a JSON object.");return f3($,s9)}class t9 extends pQ{constructor(Q){super(Q);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:Q}}},view:{}}}}async function N3(Q,$){try{return await Q.upload($)}catch(Z){if(Z instanceof y&&k1.has(Z.status))throw new y3(E(Z).message);throw Z}}var k1=new Set([400,413,415,422]);class h3 extends pQ{constructor(Q,$){super($);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:Q,message:$}}},view:{}}}}function E1(Q,$,Z,J){if(!Q)return null;let{maxBytes:W,accept:G}=Q;if(typeof W==="number"&&$.size>W)return{code:"file_too_large",message:`${JSON.stringify(Z)} is ${_3($.size)}; the limit is ${_3(W)}.`};if(G&&G.length>0&&!G.some((X)=>x1(X,Z,J)))return{code:"unsupported_file_type",message:`${JSON.stringify(Z)} is not a type this chat accepts. Accepted: ${G.join(", ")}.`};return null}function x1(Q,$,Z){let J=Q.trim().toLowerCase();if(!J)return!1;if(J.startsWith("."))return $.toLowerCase().endsWith(J);let W=Z.toLowerCase().split(";")[0].trim();if(J.endsWith("/*"))return W.startsWith(J.slice(0,-1));return W===J}function _3(Q){if(Q<1024)return`${Q} B`;let $=["KB","MB","GB"],Z=Q/1024,J=0;while(Z>=1024&&J<$.length-1)Z/=1024,J++;return`${Math.round(Z*10)/10} ${$[J]}`}class y3 extends pQ{constructor(Q){super(Q);this.name="RejectedUploadError";let $=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test(Q)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:$,message:Q}}},view:{}}}}async function n9(Q,$){let Z=Q?.rawRequest;if(!Z||Z.method==="GET"||Z.method==="HEAD"||!Z.body)return{body:{}};if(!b1(Z.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let J=Number(Z.headers.get("Content-Length"));if(Number.isFinite(J)&&J>$)return M3($);let W;try{let X=await w1(Z,$);if(X===null)return M3($);W=X}catch{return{body:{},error:"The request body could not be read."}}if(!W.trim())return{body:{}};let G;try{G=JSON.parse(W)}catch{return{body:{},error:"The request body is not valid JSON."}}if(G===null||typeof G!=="object"||Array.isArray(G))return{body:{},error:"The request body must be a JSON object."};return{body:G}}function b1(Q){return x3(Q)==="application/json"}async function w1(Q,$){if(!Number.isFinite($)||!Q.body)return await Q.text();let Z=Q.body.getReader(),J=[],W=0;for(;;){let{done:Y,value:H}=await Z.read();if(Y)break;if(W+=H.byteLength,W>$)return await Z.cancel().catch(I3),null;J.push(H)}let G=new Uint8Array(W),X=0;for(let Y of J)G.set(Y,X),X+=Y.byteLength;return new TextDecoder().decode(G)}function M3(Q){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${Q} bytes).`}}function a9(Q,$,Z){return w(Q,{...dQ(E3(Q),Z,Q),code:$})}function cQ(Q){if(Q.status===413)return a9(413,Q.code??"body_too_large",Q.error??"");return w(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function g3(Q){return Boolean(Q.turn)&&typeof Q.turn==="object"}function I1(Q){let $=g3(Q)?Q.turn:Q,Z={};if(typeof $.text==="string")Z.text=$.text;if(Array.isArray($.files)){let J=v1($.files);if(typeof J==="string")return{error:J};Z.files=J}if(Array.isArray($.toolResults))Z.toolResults=$.toolResults;if(Object.keys(Z).length===0)return{};if($===Q.turn&&$.localId!==void 0&&$.localId!==null&&$.localId!==""){let{localId:J}=$;if(typeof J!=="string")return{error:"turn.localId must be a string."};if(J.length>S3)return{error:`turn.localId is longer than ${S3} characters.`};Z.localId=J}return{turn:Z}}var S3=200;function v1(Q){let $=[];for(let[Z,J]of Q.entries()){let W=`turn.files[${Z}]`;if(!J||typeof J!=="object"||Array.isArray(J))return`${W} must be an object.`;let G={};for(let K of["fileId","attachmentId","name","mimeType"]){let z=J[K];if(z===void 0||z===null||z==="")continue;if(typeof z!=="string")return`${W}.${K} must be a string.`;G[K]=z}let{fileId:X,attachmentId:Y,name:H,mimeType:V}=G;if(X?.startsWith(f))return`${W}.fileId holds a gemi attachment id (${X}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(Y!==void 0&&!Y.startsWith(f))return`${W}.attachmentId is not a gemi attachment id: it must start with "${f}".`;if(!X&&!Y)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...X?{fileId:X}:{},...Y?{attachmentId:Y}:{},...H!==void 0?{name:H}:{},...V!==void 0?{mimeType:V}:{}})}return $}function f1(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 h1(Q,$){let Z=Q?.search?.get($);return typeof Z==="string"?Z:void 0}function y1(Q){let $=c(Q);for(let Z=Q.length-1;Z>=0;Z--){let J=Q[Z];if(J.role!=="user"||$.has(J.id))continue;let W="",G=[];for(let X of J.content){if(X.type==="text")W+=X.text;if(X.type==="file")G.push({...X.fileId?{fileId:X.fileId}:{},...X.attachmentId?{attachmentId:X.attachmentId}:{},...X.name?{name:X.name}:{},...X.mimeType?{mimeType:X.mimeType}:{}})}if(!W&&G.length===0)continue;return{index:Z,turn:{...W?{text:W}:{},...G.length>0?{files:G}:{}}}}return null}function R3(){return w(409,{code:"stopped",message:"The turn was stopped before it started."})}function mQ(){return w(403,dQ("permission","This run belongs to someone else.",403))}function g1(){return w(403,dQ("permission","A file in this turn was uploaded by someone else.",403))}function u1(Q){if(!Array.isArray(Q))return[];let $=[];for(let Z of Q){let J=Z?.content;if(!Array.isArray(J))continue;for(let W of J)if(W&&typeof W==="object"&&typeof W.fileId==="string")$.push({fileId:W.fileId})}return $}function w(Q,$){return new Response(JSON.stringify({error:$}),{status:Q,headers:{"Content-Type":"application/json"}})}function c1(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 T3=!1;function m1(){if(T3)return;T3=!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 p1=2147483647;function d1(Q,$){let Z=Q.then(()=>{},()=>{});if(!($<=p1))return Z;let J,W=new Promise((G)=>{J=setTimeout(G,$)});return Promise.race([Z,W]).finally(()=>clearTimeout(J))}var A3=!1;function l1(Q){if(A3||Bun.env.NODE_ENV!=="production")return;if(!(Q instanceof GQ))return;A3=!0,console.warn("[gemi/ai] A stateless agent chat is spending approval nonces in process memory. With more than one instance a replayed approval is accepted once per instance. Set `nonces = new RedisNonceStore()` (or your own NonceStore) on the AgentController.")}export{X9 as windowMessages,G9 as turnStarts,RZ as toAgentTools,$Q as supportsStrict,KZ as splitTurns,o1 as s,r9 as redactError,_$ as messageSize,u9 as liveRuns,c as injectedMessageIds,i3 as generate,B1 as evalChain,o as defaultNonceStore,c9 as defaultFileOwners,RQ as defaultAttachmentStore,l9 as defaultAgentStore,s as ToolNamespace,A as ToolError,U9 as Skill,YQ as ScopedAttachments,HQ as SKILLS_NAMESPACE,d9 as RedisReceiptStore,iQ as RedisNonceStore,m as PendingEscalation,v9 as OpenAIProvider,N9 as OpenAIImageProvider,p9 as MemoryReceiptStore,GQ as MemoryNonceStore,fQ as MemoryLiveRuns,hQ as MemoryFileOwners,vQ as MemoryCircuitStore,SQ as MemoryAttachmentStore,yQ as MemoryAgentStore,zQ as LiveRunNotFoundError,i1 as JSONSchemaError,n as InvalidAttachmentScopeError,bQ as ImageRequestError,wQ as ImageProvider,P9 as ImageModel,QQ as FrameCursorEvictedError,BQ as FallbackProvider,j9 as DEFAULT_MAX_RUN_DURATION_MS,M$ as DEFAULT_CONTEXT_WINDOW_STEP,S$ as DEFAULT_CONTEXT_WINDOW_NOTE,f9 as AzureOpenAIProvider,_9 as AzureOpenAIImageProvider,VQ as AttachmentNotFoundError,p as AgentTool,WQ as AgentRunError,e as AgentProvider,e9 as AgentController,L9 as Agent};
|
|
25
25
|
|
|
26
|
-
//# debugId=
|
|
26
|
+
//# debugId=CEEF45C2A5FAF7FE64756E2164756E21
|