gemi 0.111.0 → 0.112.1
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 +54 -1
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/AgentController.d.ts +41 -0
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/client/index.d.ts +1 -1
- package/dist/ai/client/index.d.ts.map +1 -1
- package/dist/ai/contextCompaction.d.ts +247 -0
- package/dist/ai/contextCompaction.d.ts.map +1 -0
- package/dist/ai/contextWindow.d.ts +18 -0
- package/dist/ai/contextWindow.d.ts.map +1 -1
- package/dist/ai/index.d.ts +5 -1
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +93 -14
- package/dist/ai/index.js.map +16 -10
- package/dist/ai/jobs/AgentJob.d.ts +259 -0
- package/dist/ai/jobs/AgentJob.d.ts.map +1 -0
- package/dist/ai/jobs/AgentJobDeadlineSweep.d.ts +18 -0
- package/dist/ai/jobs/AgentJobDeadlineSweep.d.ts.map +1 -0
- package/dist/ai/jobs/AgentJobStore.d.ts +141 -0
- package/dist/ai/jobs/AgentJobStore.d.ts.map +1 -0
- package/dist/ai/jobs/DatabaseAgentJobStore.d.ts +82 -0
- package/dist/ai/jobs/DatabaseAgentJobStore.d.ts.map +1 -0
- package/dist/ai/jobs/contextBlock.d.ts +31 -0
- package/dist/ai/jobs/contextBlock.d.ts.map +1 -0
- package/dist/ai/jobs/index.d.ts +6 -0
- package/dist/ai/jobs/index.d.ts.map +1 -0
- package/dist/ai/jobs/overlay.d.ts +49 -0
- package/dist/ai/jobs/overlay.d.ts.map +1 -0
- package/dist/ai/providers/request.d.ts.map +1 -1
- package/dist/ai/store/Attachments.d.ts +6 -0
- package/dist/ai/store/Attachments.d.ts.map +1 -1
- package/dist/ai/store/MemoryAgentStore.d.ts +3 -0
- package/dist/ai/store/MemoryAgentStore.d.ts.map +1 -1
- package/dist/ai/types.d.ts +28 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/bin/gemi.js +13 -2
- package/dist/bin/gemi.js.map +4 -4
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-30xjcyzh.js → chunk-0z2h35d7.js} +2 -2
- package/dist/{chunk-30xjcyzh.js.map → chunk-0z2h35d7.js.map} +1 -1
- package/dist/{chunk-358sdcx9.js → chunk-15a1mrdv.js} +2 -2
- package/dist/{chunk-358sdcx9.js.map → chunk-15a1mrdv.js.map} +1 -1
- package/dist/{chunk-hf7a51s3.js → chunk-18c3y8m3.js} +2 -2
- package/dist/{chunk-hf7a51s3.js.map → chunk-18c3y8m3.js.map} +1 -1
- package/dist/{chunk-tq85n8zh.js → chunk-1pvkw2pq.js} +2 -2
- package/dist/{chunk-tq85n8zh.js.map → chunk-1pvkw2pq.js.map} +1 -1
- package/dist/{chunk-8afxrmdc.js → chunk-2taa0brj.js} +2 -2
- package/dist/{chunk-8afxrmdc.js.map → chunk-2taa0brj.js.map} +1 -1
- package/dist/{chunk-5cygrbxv.js → chunk-30yg31sz.js} +2 -2
- package/dist/{chunk-5cygrbxv.js.map → chunk-30yg31sz.js.map} +1 -1
- package/dist/{chunk-3y8q8x11.js → chunk-3z9vhjd7.js} +2 -2
- package/dist/{chunk-3y8q8x11.js.map → chunk-3z9vhjd7.js.map} +1 -1
- package/dist/chunk-4sb1484x.js +46 -0
- package/dist/{chunk-h3864a8z.js.map → chunk-4sb1484x.js.map} +13 -4
- package/dist/{chunk-0sjh5v1n.js → chunk-53bek7sp.js} +1 -1
- package/dist/{chunk-xkc7ftnq.js → chunk-57edag57.js} +3 -3
- package/dist/{chunk-xkc7ftnq.js.map → chunk-57edag57.js.map} +1 -1
- package/dist/{chunk-ddr4qvvt.js → chunk-5az0mq4p.js} +3 -3
- package/dist/{chunk-ddr4qvvt.js.map → chunk-5az0mq4p.js.map} +1 -1
- package/dist/{chunk-nsvktvp4.js → chunk-5waxjsvv.js} +2 -2
- package/dist/{chunk-nsvktvp4.js.map → chunk-5waxjsvv.js.map} +1 -1
- package/dist/{chunk-rfcygmf5.js → chunk-6w79zajj.js} +3 -3
- package/dist/{chunk-rfcygmf5.js.map → chunk-6w79zajj.js.map} +1 -1
- package/dist/{chunk-gb37722w.js → chunk-75ptmewf.js} +3 -3
- package/dist/{chunk-gb37722w.js.map → chunk-75ptmewf.js.map} +1 -1
- package/dist/{chunk-pyj7cd9t.js → chunk-851k0b26.js} +2 -2
- package/dist/{chunk-pyj7cd9t.js.map → chunk-851k0b26.js.map} +1 -1
- package/dist/{chunk-m6ystvtk.js → chunk-8reepafh.js} +2 -2
- package/dist/{chunk-m6ystvtk.js.map → chunk-8reepafh.js.map} +1 -1
- package/dist/{chunk-nvv9wej6.js → chunk-9hr0bcfy.js} +3 -3
- package/dist/{chunk-nvv9wej6.js.map → chunk-9hr0bcfy.js.map} +1 -1
- package/dist/{chunk-yqavgpwd.js → chunk-a9q2cr4w.js} +2 -2
- package/dist/{chunk-yqavgpwd.js.map → chunk-a9q2cr4w.js.map} +1 -1
- package/dist/{chunk-cy5qp6mz.js → chunk-amvy4r59.js} +2 -2
- package/dist/{chunk-cy5qp6mz.js.map → chunk-amvy4r59.js.map} +1 -1
- package/dist/{chunk-twnn7r66.js → chunk-b1mk12xg.js} +2 -2
- package/dist/{chunk-twnn7r66.js.map → chunk-b1mk12xg.js.map} +1 -1
- package/dist/{chunk-a6453d9s.js → chunk-b7cqwcbm.js} +2 -2
- package/dist/{chunk-a6453d9s.js.map → chunk-b7cqwcbm.js.map} +1 -1
- package/dist/{chunk-nncz308h.js → chunk-b7qjp7r1.js} +2 -2
- package/dist/{chunk-nncz308h.js.map → chunk-b7qjp7r1.js.map} +1 -1
- package/dist/chunk-beks65me.js +19 -0
- package/dist/{chunk-mb7q7s0a.js.map → chunk-beks65me.js.map} +3 -4
- package/dist/chunk-bf1ets45.js +5 -0
- package/dist/{chunk-11fsn5mr.js.map → chunk-bf1ets45.js.map} +4 -3
- package/dist/{chunk-9rchedr4.js → chunk-bhw7k8vp.js} +2 -2
- package/dist/{chunk-9rchedr4.js.map → chunk-bhw7k8vp.js.map} +1 -1
- package/dist/{chunk-k1vw22t2.js → chunk-ck0v2kzw.js} +2 -2
- package/dist/{chunk-k1vw22t2.js.map → chunk-ck0v2kzw.js.map} +1 -1
- package/dist/{chunk-6vr7f5fq.js → chunk-csbc1fxa.js} +3 -3
- package/dist/{chunk-6vr7f5fq.js.map → chunk-csbc1fxa.js.map} +1 -1
- package/dist/{chunk-kf71mjxa.js → chunk-d0trs736.js} +3 -3
- package/dist/{chunk-kf71mjxa.js.map → chunk-d0trs736.js.map} +1 -1
- package/dist/{chunk-zhs1r1z0.js → chunk-d8ekyng4.js} +3 -3
- package/dist/{chunk-zhs1r1z0.js.map → chunk-d8ekyng4.js.map} +1 -1
- package/dist/chunk-d9an2nra.js +5 -0
- package/dist/{chunk-hn67spz6.js.map → chunk-d9an2nra.js.map} +1 -1
- package/dist/{chunk-0d9qsmx2.js → chunk-dan79jab.js} +2 -2
- package/dist/{chunk-0d9qsmx2.js.map → chunk-dan79jab.js.map} +1 -1
- package/dist/{chunk-1yx2e0bh.js → chunk-ddad3902.js} +2 -2
- package/dist/{chunk-1yx2e0bh.js.map → chunk-ddad3902.js.map} +1 -1
- package/dist/{chunk-3cg7y62b.js → chunk-dm59ze55.js} +2 -2
- package/dist/{chunk-3cg7y62b.js.map → chunk-dm59ze55.js.map} +1 -1
- package/dist/{chunk-wvsv1jgg.js → chunk-dx7wpz5b.js} +2 -2
- package/dist/{chunk-wvsv1jgg.js.map → chunk-dx7wpz5b.js.map} +1 -1
- package/dist/{chunk-q9s7kwgt.js → chunk-eazqda9z.js} +3 -3
- package/dist/{chunk-q9s7kwgt.js.map → chunk-eazqda9z.js.map} +1 -1
- package/dist/{chunk-td8tha3j.js → chunk-es487acc.js} +1 -1
- package/dist/{chunk-9s851qz8.js → chunk-et3vhkbf.js} +2 -2
- package/dist/{chunk-9s851qz8.js.map → chunk-et3vhkbf.js.map} +1 -1
- package/dist/{chunk-qd2v93y4.js → chunk-f1y8eggf.js} +2 -2
- package/dist/{chunk-qd2v93y4.js.map → chunk-f1y8eggf.js.map} +1 -1
- package/dist/{chunk-1pem26zc.js → chunk-ga7c7tq0.js} +3 -3
- package/dist/{chunk-1pem26zc.js.map → chunk-ga7c7tq0.js.map} +1 -1
- package/dist/{chunk-c098fzvk.js → chunk-gcs9ydjv.js} +2 -2
- package/dist/{chunk-c098fzvk.js.map → chunk-gcs9ydjv.js.map} +1 -1
- package/dist/{chunk-bn5yn731.js → chunk-hfyxvdjj.js} +2 -2
- package/dist/{chunk-bn5yn731.js.map → chunk-hfyxvdjj.js.map} +1 -1
- package/dist/chunk-j0sncgxc.js +14 -0
- package/dist/{chunk-mn5xw79b.js.map → chunk-j0sncgxc.js.map} +6 -5
- package/dist/{chunk-p7r2w4qw.js → chunk-j9jqxv1d.js} +3 -3
- package/dist/{chunk-p7r2w4qw.js.map → chunk-j9jqxv1d.js.map} +1 -1
- package/dist/{chunk-jbrwt3cs.js → chunk-jdtn0zk2.js} +4 -4
- package/dist/{chunk-jbrwt3cs.js.map → chunk-jdtn0zk2.js.map} +1 -1
- package/dist/{chunk-s6jjy4y9.js → chunk-jn59bsww.js} +2 -2
- package/dist/{chunk-s6jjy4y9.js.map → chunk-jn59bsww.js.map} +1 -1
- package/dist/chunk-jn8hh25v.js +24 -0
- package/dist/{chunk-wqvvjd5r.js.map → chunk-jn8hh25v.js.map} +2 -2
- package/dist/chunk-k7rbkhhw.js +6 -0
- package/dist/{chunk-tdsfke9q.js.map → chunk-k7rbkhhw.js.map} +2 -2
- package/dist/{chunk-he7z7y9j.js → chunk-kk502yk2.js} +2 -2
- package/dist/{chunk-he7z7y9j.js.map → chunk-kk502yk2.js.map} +1 -1
- package/dist/{chunk-wsttx9rg.js → chunk-mrdarm2q.js} +2 -2
- package/dist/{chunk-wsttx9rg.js.map → chunk-mrdarm2q.js.map} +1 -1
- package/dist/chunk-mvtgx1mr.js +4 -0
- package/dist/{chunk-x78jrs4y.js.map → chunk-mvtgx1mr.js.map} +2 -2
- package/dist/{chunk-et4pv1b1.js → chunk-mx9y9mtx.js} +1 -1
- package/dist/{chunk-cttmy1jp.js → chunk-p2fhtf5r.js} +3 -3
- package/dist/{chunk-cttmy1jp.js.map → chunk-p2fhtf5r.js.map} +1 -1
- package/dist/{chunk-w7jsh3xd.js → chunk-qtbf3w6w.js} +2 -2
- package/dist/{chunk-w7jsh3xd.js.map → chunk-qtbf3w6w.js.map} +1 -1
- package/dist/chunk-qx87cdfg.js +5 -0
- package/dist/chunk-qx87cdfg.js.map +10 -0
- package/dist/{chunk-1kr25rcg.js → chunk-qyp652jz.js} +3 -3
- package/dist/{chunk-1kr25rcg.js.map → chunk-qyp652jz.js.map} +1 -1
- package/dist/{chunk-8b2tw2yp.js → chunk-rend2sbk.js} +1 -1
- package/dist/chunk-rx2shb3t.js +25 -0
- package/dist/chunk-rx2shb3t.js.map +19 -0
- package/dist/{chunk-mwqg079k.js → chunk-ryzcfxq7.js} +2 -2
- package/dist/{chunk-mwqg079k.js.map → chunk-ryzcfxq7.js.map} +1 -1
- package/dist/{chunk-7tx5y712.js → chunk-s9rfgxj5.js} +2 -2
- package/dist/{chunk-7tx5y712.js.map → chunk-s9rfgxj5.js.map} +1 -1
- package/dist/{chunk-1c1d0e60.js → chunk-scbvv2e4.js} +3 -3
- package/dist/{chunk-1c1d0e60.js.map → chunk-scbvv2e4.js.map} +1 -1
- package/dist/{chunk-1bkr5wnt.js → chunk-tb126j80.js} +2 -2
- package/dist/{chunk-1bkr5wnt.js.map → chunk-tb126j80.js.map} +1 -1
- package/dist/{chunk-pwmgqq7z.js → chunk-teny6xkw.js} +2 -2
- package/dist/{chunk-pwmgqq7z.js.map → chunk-teny6xkw.js.map} +1 -1
- package/dist/{chunk-09ypnhjv.js → chunk-tmrmwthr.js} +2 -2
- package/dist/{chunk-09ypnhjv.js.map → chunk-tmrmwthr.js.map} +1 -1
- package/dist/{chunk-h4sw6nt3.js → chunk-vgdcz7tk.js} +3 -3
- package/dist/{chunk-h4sw6nt3.js.map → chunk-vgdcz7tk.js.map} +1 -1
- package/dist/{chunk-xk930yaw.js → chunk-wexs11yy.js} +2 -2
- package/dist/{chunk-xk930yaw.js.map → chunk-wexs11yy.js.map} +1 -1
- package/dist/{chunk-k1xt2tw7.js → chunk-xs4c2nvz.js} +2 -2
- package/dist/{chunk-k1xt2tw7.js.map → chunk-xs4c2nvz.js.map} +1 -1
- package/dist/{chunk-1va15sfq.js → chunk-xv74rhay.js} +2 -2
- package/dist/{chunk-1va15sfq.js.map → chunk-xv74rhay.js.map} +1 -1
- package/dist/{chunk-sq2wkynk.js → chunk-yv1psptb.js} +2 -2
- package/dist/{chunk-sq2wkynk.js.map → chunk-yv1psptb.js.map} +1 -1
- package/dist/{chunk-tk5q8hkv.js → chunk-zfter1x0.js} +4 -4
- package/dist/{chunk-tk5q8hkv.js.map → chunk-zfter1x0.js.map} +1 -1
- package/dist/client/ClientRouter.d.ts.map +1 -1
- package/dist/client/index.d.ts +2 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +215 -2
- package/dist/client/index.js.map +1 -1
- package/dist/client/useSubscription.d.ts +70 -0
- package/dist/client/useSubscription.d.ts.map +1 -0
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +2 -2
- 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/ChangeFeed.d.ts +42 -0
- package/dist/facades/ChangeFeed.d.ts.map +1 -0
- package/dist/facades/index.d.ts +1 -0
- package/dist/facades/index.d.ts.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/ResourcePolicy.d.ts +141 -0
- package/dist/http/ResourcePolicy.d.ts.map +1 -0
- package/dist/http/errors.d.ts +13 -0
- package/dist/http/errors.d.ts.map +1 -1
- package/dist/http/index.d.ts +2 -1
- package/dist/http/index.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 +2 -2
- package/dist/kernel/index.js +3 -3
- package/dist/kernel/index.js.map +3 -3
- package/dist/kernel/providers.d.ts.map +1 -1
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/change-feed/ChangeFeedDriver.d.ts +94 -0
- package/dist/services/change-feed/ChangeFeedDriver.d.ts.map +1 -0
- package/dist/services/change-feed/ChangeFeedManager.d.ts +166 -0
- package/dist/services/change-feed/ChangeFeedManager.d.ts.map +1 -0
- package/dist/services/change-feed/ChangeFeedServiceProvider.d.ts +11 -0
- package/dist/services/change-feed/ChangeFeedServiceProvider.d.ts.map +1 -0
- package/dist/services/change-feed/DatabaseChangeFeedDriver.d.ts +84 -0
- package/dist/services/change-feed/DatabaseChangeFeedDriver.d.ts.map +1 -0
- package/dist/services/change-feed/MemoryChangeFeedDriver.d.ts +26 -0
- package/dist/services/change-feed/MemoryChangeFeedDriver.d.ts.map +1 -0
- package/dist/services/change-feed/changeFeedDriverContract.d.ts +8 -0
- package/dist/services/change-feed/changeFeedDriverContract.d.ts.map +1 -0
- package/dist/services/change-feed/config.d.ts +42 -0
- package/dist/services/change-feed/config.d.ts.map +1 -0
- package/dist/services/change-feed/cursor.d.ts +17 -0
- package/dist/services/change-feed/cursor.d.ts.map +1 -0
- package/dist/services/change-feed/postgresListen.d.ts +30 -0
- package/dist/services/change-feed/postgresListen.d.ts.map +1 -0
- package/dist/services/change-feed/stream.d.ts +16 -0
- package/dist/services/change-feed/stream.d.ts.map +1 -0
- package/dist/services/change-feed/wire.d.ts +20 -0
- package/dist/services/change-feed/wire.d.ts.map +1 -0
- package/dist/services/index.d.ts +9 -0
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +3 -3
- package/dist/services/index.js.map +2 -2
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts +16 -0
- package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vitest/index.js +1 -1
- package/package.json +6 -2
- package/skills/gemi-react-best-practices/rules/controller-authorize-every-tenant-read.md +16 -1
- package/dist/chunk-11fsn5mr.js +0 -5
- package/dist/chunk-h3864a8z.js +0 -17
- package/dist/chunk-hn67spz6.js +0 -5
- package/dist/chunk-mb7q7s0a.js +0 -19
- package/dist/chunk-mn5xw79b.js +0 -9
- package/dist/chunk-tdsfke9q.js +0 -6
- package/dist/chunk-wqvvjd5r.js +0 -24
- package/dist/chunk-x78jrs4y.js +0 -4
- /package/dist/{chunk-0sjh5v1n.js.map → chunk-53bek7sp.js.map} +0 -0
- /package/dist/{chunk-td8tha3j.js.map → chunk-es487acc.js.map} +0 -0
- /package/dist/{chunk-et4pv1b1.js.map → chunk-mx9y9mtx.js.map} +0 -0
- /package/dist/{chunk-8b2tw2yp.js.map → chunk-rend2sbk.js.map} +0 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,26 +1,105 @@
|
|
|
1
1
|
// @bun
|
|
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
|
-
|
|
2
|
+
import{Kb as S,Lb as O9,Mb as bZ,Nb as fZ,Ob as m6}from"../chunk-3z9vhjd7.js";import{bc as yZ}from"../chunk-qx87cdfg.js";import{fc as fQ,jc as vQ}from"../chunk-ga7c7tq0.js";import{Cf as u6,Rf as M1,Sf as d9,Tf as z9,Uf as k9,hg as y9,jg as D9,kg as Q9,mg as wZ,og as c6,zf as y6}from"../chunk-j0sncgxc.js";import{pg as g6,rg as F$,sg as L$}from"../chunk-teny6xkw.js";import{wg as a9}from"../chunk-yv1psptb.js";import"../chunk-b1mk12xg.js";import"../chunk-hfyxvdjj.js";import{Cg as pZ,Dg as lZ,Rg as dZ}from"../chunk-57edag57.js";import"../chunk-jn59bsww.js";import{Dh as $9}from"../chunk-eazqda9z.js";import"../chunk-dm59ze55.js";import"../chunk-et3vhkbf.js";import"../chunk-8reepafh.js";import"../chunk-ddad3902.js";class g extends Error{status;body;requestId;constructor($,Q,Z){super(`Provider request failed with status ${$}: ${t6(Q)}`);this.name="ProviderHttpError",this.status=$,this.body=Q,this.requestId=Z}}class E9 extends Error{timeoutMs;constructor($){super(`Provider request timed out after ${$}ms`);this.name="ProviderTimeoutError",this.timeoutMs=$}}function t6($){let Q=xQ($);if(Q?.message)return Q.message;if(typeof $==="string")return $.slice(0,500);return"no error body"}function xQ($){if(!$||typeof $!=="object")return null;let Q=$,J=Q.error&&typeof Q.error==="object"?Q.error:$;if(typeof J.message!=="string"&&typeof J.code!=="string"&&typeof J.type!=="string")return null;let G=J.innererror?.code??J.code;return{message:J.message,type:J.type,code:G,param:J.param}}function b($){if(!$||typeof $!=="object")return{};let{status:Q,requestId:Z}=$;return{...typeof Q==="number"&&Q>=100&&Q<=599?{status:Q}:{},...typeof Z==="string"&&Z?{requestId:Z}:{}}}function I($){if($ instanceof E9)return{code:"provider_error",message:$.message,retryable:!0};if($8($))return{code:"aborted",message:"The request was aborted.",retryable:!1};if($ instanceof g)return a6($.status,xQ($.body),$.message);if($ instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${$.message}`,retryable:!0};if($ instanceof Error)return{code:"provider_error",message:$.message,retryable:!1};return{code:"unknown",message:String($),retryable:!1}}function a6($,Q,Z){let J=Q?.message??Z,G=(Q?.code??"").toLowerCase(),W=(Q?.type??"").toLowerCase(),V=`${G} ${W} ${J}`.toLowerCase();if($===429){let Y=G==="insufficient_quota"||V.includes("quota");return{code:"rate_limited",message:J,retryable:!Y}}if($>=500||$===408||$===409)return{code:"provider_error",message:J,retryable:!0};if(r6(V))return{code:"context_length_exceeded",message:J,retryable:!1};if(e6(V))return{code:"content_filtered",message:J,retryable:!1};if(Q?.param?.startsWith("tools")||V.includes("invalid schema for function"))return{code:"invalid_tool_input",message:J,retryable:!1};return{code:"provider_error",message:J,retryable:!1}}function r6($){return $.includes("context_length_exceeded")||$.includes("maximum context length")||$.includes("context window")||$.includes("reduce the length")}function e6($){return $.includes("content_filter")||$.includes("content_policy_violation")||$.includes("responsibleaipolicyviolation")||$.includes("content management policy")}function $8($){if(!$||typeof $!=="object")return!1;let Q=$;return Q.name==="AbortError"||Q.code==="ABORT_ERR"}class w extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function m($,Q){if(Q.aborted)return Promise.reject(new w);return new Promise((Z,J)=>{let G=()=>J(new w);Q.addEventListener("abort",G,{once:!0}),$.then(Z,J).finally(()=>Q.removeEventListener("abort",G))})}function R(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function M($,Q){if(!Q)return $;let Z={inputTokens:$.inputTokens+(Q.inputTokens??0),outputTokens:$.outputTokens+(Q.outputTokens??0),totalTokens:$.totalTokens+(Q.totalTokens??0)};if(Q.reasoningTokens!==void 0||$.reasoningTokens!==void 0)Z.reasoningTokens=($.reasoningTokens??0)+(Q.reasoningTokens??0);if(Q.cachedInputTokens!==void 0||$.cachedInputTokens!==void 0)Z.cachedInputTokens=($.cachedInputTokens??0)+(Q.cachedInputTokens??0);if(Q.imageInputTokens!==void 0||$.imageInputTokens!==void 0)Z.imageInputTokens=($.imageInputTokens??0)+(Q.imageInputTokens??0);if(Q.imageOutputTokens!==void 0||$.imageOutputTokens!==void 0)Z.imageOutputTokens=($.imageOutputTokens??0)+(Q.imageOutputTokens??0);return Z}function x9($){if(!$.trim())return{};try{return JSON.parse($)}catch{}let Q=[],Z=!1,J=!1;for(let V of $){if(Z){if(J)J=!1;else if(V==="\\")J=!0;else if(V==='"')Z=!1;continue}if(V==='"')Z=!0;else if(V==="{")Q.push("}");else if(V==="[")Q.push("]");else if(V==="}"||V==="]")Q.pop()}let G=$;if(Z)G+='"';G=G.replace(/[,:]\s*$/,"");let W=Q.reverse().join("");try{return JSON.parse(G+W)}catch{try{return JSON.parse(G.replace(/,?\s*"[^"]*"\s*$/,"")+W)}catch{return{}}}}function I9($){return{name:"output",schema:$.toJSONSchema(),strict:z9($)}}function w9($,Q){let Z=$.safeParse(x9(Q));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 b9($){if($.length>0)$[0];return $}function B9($,Q,Z){let J=$.content[$.content.length-1];if(J&&J.type===Q){J.text=(J.text??"")+Z;return}$.content.push(Q==="text"?{type:"text",text:Z}:{type:"reasoning",text:Z})}function f9($,Q,Z){let J=$.content[$.content.length-1];if(J&&J.type==="reasoning"&&J.id===Q){J.text=(J.text??"")+Z;return}$.content.push(Q?{type:"reasoning",id:Q,text:Z}:{type:"reasoning",text:Z})}function U$($){return F9($)}async function F9($,Q={}){let Z=`gen_${crypto.randomUUID()}`,J=await Z8($);if(Q.settled?.(J),!J.ok){if($.logErrors!==!1&&J.error.code!=="aborted")Q8(Z,J.error,Q.origin);if($.throwOnError)throw new L9({runId:Z,messages:J.messages,finishReason:J.finishReason,usage:J.usage,error:J.error})}return J}function Q8($,Q,Z){let J=`[gemi/ai] generate() failed (${Q.code}${Q.status!==void 0?` ${Q.status}`:""}): ${Q.message}`,G={...Z,generateId:$,error:Q},W=!1;try{D9.error(J,G),W=!0}catch{}if(!W||Bun.env.NODE_ENV==="development")console.error(J,G)}async function Z8($){let Q=$.messages??[];if(Q.length===0&&!$.prompt)throw Error("generate() was given neither a `prompt` nor `messages`, so there is nothing to send the model.");let Z=[...Q];if($.prompt)Z.push({id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:$.prompt}],createdAt:new Date().toISOString()});let J={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()},G=$.signal??new AbortController().signal,W=R(),V="stop",Y,H={},X="";try{let D=$.provider.stream({messages:[...Z],systemPrompt:$.instructions?.trim()?$.instructions:void 0,output:I9($.output),reasoning:$.reasoning,maxOutputTokens:$.maxOutputTokens,temperature:$.temperature,signal:$.signal})[Symbol.asyncIterator]();try{for(;;){let L=await m(Promise.resolve(D.next()),G);if(L.done)break;let F=L.value;switch(F.type){case"output-delta":X+=F.delta;break;case"text-delta":B9(J,"text",F.delta);break;case"reasoning-delta":f9(J,F.id,F.delta);break;case"finish":if(W=M(W,F.usage),!Y)V=F.reason;break;case"error":V="error",Y=F.error,H=b(F);break}}}finally{if(G.aborted)Promise.resolve(D.return?.()).catch(()=>{})}}catch(z){if(z instanceof w||G.aborted)V="aborted",Y=J8(G);else V="error",Y=$.provider.normalizeError(z),H=b(z)}let K=!1,B;if(!Y)if(V==="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(!X.trim())Y={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let z=w9($.output,X);if(z.ok===!0)K=!0,B=z.value;else Y=z.error}if(K)J.content.push({type:"output",value:B});else if(X)B9(J,"text",X);for(let z of J.content)if((z.type==="text"||z.type==="reasoning")&&typeof z.text==="string")z.text=b9(z.text);if(J.finishReason=V,J.usage=W,Z.push(J),K)return{ok:!0,output:B,messages:Z,usage:W,finishReason:V};return{ok:!1,error:{...Y,...H},messages:Z,usage:W,finishReason:V}}function J8($){return $.reason?.name==="TimeoutError"?{code:"timeout",message:"The generation timed out.",retryable:!0}:{code:"aborted",message:"The generation was stopped.",retryable:!1}}class U9 extends S{id;code="attachment_not_found";constructor($){super(`No attachment ${$}.`);this.id=$;this.name="AttachmentNotFoundError"}}class u extends S{code="invalid_attachment_scope";constructor($){super($);this.name="InvalidAttachmentScopeError"}}function P$($){if(!$||typeof $.key!=="string"||$.key.length===0)throw new u("An attachment scope needs a non-empty key. Return `null` from `attachmentScope()` for a request that has no subject \u2014 an empty key is a bucket every caller shares.");return $}var h="gemi_att_";function C$(){return`${h}${crypto.randomUUID()}`}class p{store;storage;scope;constructor($,Q,Z){this.store=$;this.storage=Q;this.scope=Z;P$(Z)}get scopeKey(){return this.scope.key}async get($){let Q=await this.store.find(this.scope,$);if(!Q||Q.scopeKey!==this.scope.key)throw new U9($);return Q}async read($){return await this.readRecord($,await this.get($))}async readRecord($,Q){if(!Q.objectName)throw new U9($);return await this.storage.read({name:Q.objectName})}async file($){let Q=await this.get($),J=(await this.readRecord($,Q)).body,G=J instanceof Blob?J:J?await new Response(J).blob():new Blob([]);return new File([G],Q.name,{type:Q.mimeType})}async put($,Q={}){let Z=C$(),J=Q.mimeType??$.type??"",G=Q.name??($ instanceof File?$.name:Z),W=await this.storage.put({name:O$(Z,G),body:$,contentType:J||void 0}),V={id:Z,scopeKey:this.scope.key,objectName:W,name:G,mimeType:J||"application/octet-stream",size:$.size,createdAt:new Date().toISOString(),destination:Q.fileId?"both":"storage",...Q.fileId?{fileId:Q.fileId}:{}};return await this.store.put(this.scope,V),V}}function O$($,Q){let Z=/\.([A-Za-z0-9]{1,8})$/.exec(Q);return`attachments/${$}${Z?`.${Z[1].toLowerCase()}`:""}`}class v9{rows=new Map;async put($,Q){P$($),this.rows.set(Q.id,{...Q,scopeKey:$.key})}async find($,Q){P$($);let Z=this.rows.get(Q);if(!Z||Z.scopeKey!==$.key)return null;return Z}get size(){return this.rows.size}}var r=new v9;class P9{jobs=new Map;async create($){if(this.jobs.has($.id))throw Error(`A background job with the id ${$.id} already exists.`);let Q=Date.now(),{deadlineMs:Z,...J}=$,G={...structuredClone(J),state:"running",createdAt:Q,updatedAt:Q,deadlineAt:Q+Z};return this.jobs.set(G.id,G),this.trim(G.threadId),structuredClone(G)}async get($){let Q=this.jobs.get($);return Q?structuredClone(Q):null}async listForThread($,Q={}){let Z=[];for(let J of this.jobs.values()){if(J.threadId!==$)continue;if(Q.states&&!Q.states.includes(J.state))continue;Z.push(J)}return Z.sort(IQ),(Q.limit===void 0?Z:Z.slice(0,Q.limit)).map((J)=>structuredClone(J))}async transition($,Q,Z){let J=this.jobs.get($);if(!J||!Q.includes(J.state))return!1;let G=structuredClone(Z),W=Date.now();if(Object.assign(J,G,{updatedAt:W}),G.state&&G.state!=="running"&&J.settledAt===void 0)J.settledAt=G.settledAt??W;return!0}async overdue($,Q){let Z=[];for(let J of this.jobs.values())if(J.state==="running"&&J.deadlineAt<=$)Z.push(J);return Z.sort((J,G)=>J.deadlineAt-G.deadlineAt),Z.slice(0,Math.max(0,Q)).map((J)=>structuredClone(J))}async now(){return Date.now()}trim($){let Q=[...this.jobs.values()].filter((Z)=>Z.threadId===$&&Z.state!=="running").sort(IQ);for(let Z of Q.slice(200))this.jobs.delete(Z.id)}}function IQ($,Q){return Q.createdAt-$.createdAt||($.id<Q.id?1:$.id>Q.id?-1:0)}var hQ=Symbol.for("gemi.ai.JobHandle");class g9{id;toolCallId;summary;deadlineAt;[hQ]=!0;constructor($,Q,Z,J){this.id=$;this.toolCallId=Q;this.summary=Z;this.deadlineAt=J}}function yQ($){return typeof $==="object"&&$!==null&&$[hQ]===!0}class C9 extends S{code="jobs_require_thread";constructor($){super($,{retryable:!1});this.name="JobsRequireThreadError"}}var e=new P9,G8=["running","ok","error"],y={get store(){return e},use($){e=$},get($){return e.get($)},async settle($,Q){return h9(e,$,Q)},async fail($,Q){return h9(e,$,{error:Q})},async sweep($={}){let Q=e,Z=$.limit??100,J=await N$(Q),G=0;for(let W of await Q.overdue(J,Z))if(await _$(Q,W))G++;return G}};async function N$($){return $.now?await $.now():Date.now()}function _$($,Q){return $.transition(Q.id,["running"],{state:"error",error:{code:"timeout",message:`The background job for "${Q.toolName}" did not finish before its deadline, so it was given up on. Its result, if it ever arrives, is ignored.`,toolCallId:Q.toolCallId,retryable:!0}})}async function h9($,Q,Z){let J=await $.get(Q);if(!J||J.state!=="running")return!1;let G=Z.usage?M(J.usage??R(),Z.usage):void 0;if("error"in Z)return $.transition(Q,["running"],{state:"error",error:W8(J,Z.error),...G?{usage:G}:{}});return $.transition(Q,["running"],{state:"ok",output:gQ(Z.output,J),...G?{usage:G}:{}})}function W8($,Q){if(typeof Q==="string")return{code:"tool_error",message:Q,toolCallId:$.toolCallId,retryable:!0};if(Q instanceof Error){let Z={code:"tool_error",message:Q.message,toolCallId:$.toolCallId,retryable:Q instanceof S?Q.retryable:!0};if(!(Q instanceof S))console.error(`The background job ${$.job??"(tracked)"} for "${$.toolName}" failed.`,Q);return O9(Z,{source:"tool",toolName:$.toolName,cause:Q})}return{code:Q.code??"tool_error",message:String(Q.message),toolCallId:$.toolCallId,retryable:Q.retryable??!0}}function gQ($,Q){if($===void 0)return null;try{return JSON.parse(JSON.stringify($))}catch(Z){throw Error(`The output of the background job for "${Q.toolName}" is not JSON: ${String(Z)}`)}}var q$=3600000;function uQ($){let Q=null,Z=(J,G,W={})=>{if($.async===void 0)throw new S(`"${$.toolName}" called ctx.jobs, but the tool does not declare \`async\`. Add \`async: { deadlineMs }\` to its definition.`,{retryable:!1});if(!$.jobs||!$.threadId)throw new C9(`"${$.toolName}" can only run in the background on a conversation the server keeps (a turn with a threadId), and this one has none.`);if($.depth>0)throw new C9(`"${$.toolName}" can only run in the background from the top-level agent, not from a sub-agent.`);if(Q)throw new S(`"${$.toolName}" started a background job already: a tool call has at most one.`,{retryable:!1});let V=W.deadlineMs??$.async.deadlineMs??q$;if(!Number.isFinite(V)||V<=0)throw new S(`A job's deadlineMs must be a positive number; got ${V}.`);let{jobs:Y,threadId:H}=$;return Q=(async()=>{let X=y.store,K=(await X.listForThread(H,{limit:50})).find((D)=>D.toolCallId===$.toolCallId);if(K)return wQ(K);let B=async()=>{let D=await X.create({id:`ajob_${crypto.randomUUID()}`,threadId:H,runId:$.runId,toolCallId:$.toolCallId,toolName:$.toolName,owner:Y.owner,job:J?J.name:null,...W.summary!==void 0?{summary:gQ(W.summary,$)}:{},attachmentScope:$.attachments?.scopeKey??null,deadlineMs:V});if(J)try{await V8(J,{jobId:D.id,args:G})}catch(L){if(X.transaction)throw L;throw await X.transition(D.id,["running"],{state:"error",error:{code:"tool_error",message:`The background job for "${$.toolName}" could not be queued.`,toolCallId:$.toolCallId,retryable:!0}}).catch(()=>{}),L}return D},z=X.transaction?await X.transaction(B):await B();return wQ(z)})(),Q};return{start:(J,G,W)=>Z(J,G,W),track:(J)=>Z(null,void 0,J)}}function wQ($){return new g9($.id,$.toolCallId,$.summary,$.deadlineAt)}function V8($,Q){if($.name==="unset"||!$.name)throw Error("Cannot start an AgentJob with no `static name`.");return $9(vQ).push($,JSON.stringify([Q]))}class M$ extends fQ{attachments=r;attachmentStorage=y9;constructor(){super();let $=this.run;this.run=(Q)=>this.$runEnvelope(Q,$)}onDeadletter($,...Q){let Z=Q[0];if(!Z?.jobId)return;h9(y.store,Z.jobId,{error:$}).catch((J)=>{console.error(`Could not record the failure of background job ${Z.jobId}.`,J)})}async $runEnvelope($,Q){let Z=y.store,J=await Z.get($.jobId);if(!J||J.state!=="running")return;let G=new cQ(J,this),W;try{W=await Q.call(this,$.args,G)}catch(V){throw await bQ(Z,J.id,G.usage),V}if(this.$outcome)return await bQ(Z,J.id,G.usage),W;return await h9(Z,J.id,{output:W,usage:G.usage}),W}}async function bQ($,Q,Z){if(Z.totalTokens===0&&Z.inputTokens===0&&Z.outputTokens===0)return;let J=await $.get(Q);if(!J)return;await $.transition(Q,G8,{usage:M(J.usage??R(),Z)}).catch(()=>{})}class cQ{id;threadId;toolCallId;toolName;owner;summary;signal=new AbortController().signal;usage=R();attachments;constructor($,Q){this.id=$.id,this.threadId=$.threadId,this.toolCallId=$.toolCallId,this.toolName=$.toolName,this.owner=$.owner,this.summary=$.summary;let Z=$.attachmentScope?new p(Q.attachments,Q.attachmentStorage,{key:$.attachmentScope}):null,J=()=>{if(!Z)throw new u("The run that started this job had no attachment scope, so the job cannot store or read files. See `attachmentScope()` on the controller.");return Z};this.attachments={put:(G,W={})=>J().put(G,W),get:(G)=>J().get(G),read:(G)=>J().read(G),file:(G)=>J().file(G)}}generate($){return F9($,{origin:{threadId:this.threadId,toolCallId:this.toolCallId,jobId:this.id},settled:(Q)=>{this.usage=M(this.usage,Q.usage)}})}async generateImage($,Q){let{name:Z,...J}=Q,G=await $.generate({...J,signal:this.signal});return this.park($,G,Z)}async editImage($,Q){let{name:Z,images:J,mask:G,...W}=Q,V=async(H)=>typeof H==="string"?await this.attachments.file(H):H,Y=await $.edit({...W,images:await Promise.all(J.map(V)),...G?{mask:await V(G)}:{},signal:this.signal});return this.park($,Y,Z)}async park($,Q,Z){this.usage=M(this.usage,Q.usage);let J=Q.mimeType==="image/jpeg"?"jpg":"png";return{attachment:await this.attachments.put(Q.image,{name:Z??`${$.name}.${J}`,mimeType:Q.mimeType}),size:Q.size,mimeType:Q.mimeType,usage:Q.usage}}}import{createHmac as X8,hkdfSync as Y8,randomBytes as mQ,timingSafeEqual as H8}from"crypto";class N9{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($);if(J!==void 0&&J>Z)return!1;return this.spent.set($,Q),!0}get size(){return this.spent.size}sweep($){for(let[Q,Z]of this.spent)if(Z<=$)this.spent.delete(Q);this.sweepAt=Math.max(1024,this.spent.size*2)}}class R${injectedClient;prefix;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:ai:nonce"}async consume($,Q){let Z=Math.max(1,Math.ceil(Q-Date.now()));return await this.client.send("SET",[`${this.prefix}:${$}`,"1","PX",String(Z),"NX"])==="OK"}get client(){if(this.injectedClient)return this.injectedClient;let $=$9(),Q=$.bound(Q9)?$.make(Q9).client:void 0;if(!Q)throw Error("RedisNonceStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisNonceStore({ client }).");return Q}}var Z9=new N9;var j$="agt2",c9="agt1",pQ=[j$,c9],S$=86400000,K8=Date.now()+S$;function lQ($){return $<=K8}var dQ="gemi.ai.pending-call.v1",iQ="gemi.ai.nested-run.v1",z8="gemi.ai.execution-receipt.v1",B8="gemi.ai.signing",u9=new Map;function _9($,Q){let Z=A$(Q),J=`${$}\x00${Z}`,G=u9.get(J);if(!G){if(G=Buffer.from(Y8("sha256",Z,B8,$,32)),u9.size>64)u9.clear();u9.set(J,G)}return G}function A$($){let Q=$??process.env.SECRET;if(!Q)throw Error("Signing a pending tool call needs an app secret. Set SECRET in the environment.");return Q}function v($){if($===null||typeof $!=="object")return JSON.stringify($)??"null";if(Array.isArray($))return`[${$.map(v).join(",")}]`;let Q=$;return`{${Object.keys(Q).filter((J)=>Q[J]!==void 0).sort().map((J)=>`${JSON.stringify(J)}:${v(Q[J])}`).join(",")}}`}function D8($){return $.map((Q)=>`${Q.length}:${Q}`).join("")}function l($,Q){return X8("sha256",$).update(D8(Q)).digest()}function nQ($,Q){let Z=Buffer.from($.split(".")[4],"base64url");return Z.length===Q.length&&H8(Z,Q)}function T$($){return v($??null)}function oQ($,Q,Z){return[j$,$.runId,$.toolCallId,$.name,$.kind,Q,String(Z),v($.input),v($.path??[]),T$($.subject)]}function F8($,Q,Z){let J=[c9,$.runId,$.toolCallId,$.name,$.kind,Q,String(Z),v($.input)];if($.path&&$.path.length>0)J.push(v($.path));return J}var sQ=($)=>Buffer.from($,"utf8").toString("base64url"),L8=($)=>Buffer.from($,"base64url").toString("utf8");function tQ($,Q={}){let Z=_9(dQ,Q.secret),G=(Q.now??Date.now())+(Q.ttlMs??S$),W=mQ(12).toString("base64url"),V=l(Z,oQ($,W,G)).toString("base64url");return[j$,sQ($.runId),W,G.toString(36),V].join(".")}function k$($){return p9($,pQ)}function p9($,Q){let Z=$.split(".");if(Z.length!==5||!Q.includes(Z[0]))return null;let J=Number.parseInt(Z[3],36);if(!Number.isFinite(J))return null;try{return{runId:L8(Z[1]),nonce:Z[2],expiresAt:J,version:Z[0]}}catch{return null}}function aQ($,Q,Z={}){let J=p9($,pQ);if(!J)return{ok:!1,reason:"malformed"};if(J.version===c9&&!lQ(J.expiresAt))return{ok:!1,reason:"forged"};let G=J.version===c9?l(A$(Z.secret),F8(Q,J.nonce,J.expiresAt)):l(_9(dQ,Z.secret),oQ(Q,J.nonce,J.expiresAt));if(!nQ($,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}}var E$="agn2",m9="agn1",rQ=[E$,m9];function eQ($,Q,Z){return[...$Z($,Q,Z,E$),T$($.subject)]}function $Z($,Q,Z,J=m9){return[J,$.runId,v($.path),$.nestedRunId,Q,String(Z),v([...$.open].sort()),v($.input)]}function QZ($,Q={}){let Z=_9(iQ,Q.secret),G=(Q.now??Date.now())+(Q.ttlMs??S$),W=mQ(12).toString("base64url"),V=l(Z,eQ($,W,G)).toString("base64url");return[E$,sQ($.runId),W,G.toString(36),V].join(".")}function ZZ($,Q,Z={}){let J=p9($,rQ);if(!J)return{ok:!1,reason:"malformed"};if(J.version===m9&&!lQ(J.expiresAt))return{ok:!1,reason:"forged"};let G={...Q,runId:J.runId},W=J.version===m9?l(A$(Z.secret),$Z(G,J.nonce,J.expiresAt)):l(_9(iQ,Z.secret),eQ(G,J.nonce,J.expiresAt));if(!nQ($,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}}function JZ($,Q,Z={}){let J=_9(z8,Z.secret);return l(J,[$,Q.runId,Q.toolCallId,Q.name,Q.kind,v(Q.input),v(Q.path??[]),T$(Q.subject)]).toString("base64url")}function GZ($,Q){return VZ(Q,k$($))}function WZ($,Q){return VZ(Q,p9($,rQ))}async function VZ($,Q){if(!Q)return!1;return $.consume(Q.nonce,Q.expiresAt)}function d($){let Q=new Set;for(let Z of $)for(let J of Z.content??[]){if(J.type!=="tool-call")continue;for(let G of J.attachments??[])if(G&&"shown"in G&&G.shown)Q.add(G.shown.messageId)}return Q}function q9($){if($.length===0)return[];let Q=d($),Z=[0];for(let J=1;J<$.length;J++){let G=$[J];if(G.role==="user"&&!Q.has(G.id))Z.push(J)}return Z}function U8($){let Q=q9($);return Q.map((Z,J)=>$.slice(Z,Q[J+1]??$.length))}function YZ($){try{return JSON.stringify($).length}catch{return 0}}var P8=4,HZ=10,KZ="[Earlier turns of this conversation are not shown.]";function J9($,Q={}){let Z=[...$],J=q9(Z),G=C8(Q),W=l9(Q.maxTurns)??1/0,V=Math.max(1,Math.floor(l9(Q.step)??HZ));if(J.length<=1||W>=J.length&&G===1/0)return{messages:Z,start:0,omittedTurns:0,omittedMessages:0};let Y=Array.from({length:Z.length+1},()=>0);if(G!==1/0)for(let U=Z.length-1;U>=0;U--)Y[U]=Y[U+1]+YZ(Z[U]);let H=(U)=>J.length-U<=W&&Y[J[U]]<=G,X=-1;for(let U=0;U<J.length;U+=V)if(H(U)){X=U;break}if(X<0){for(let U=0;U<J.length;U++)if(H(U)){X=U;break}}if(X<0)X=J.length-1;if(X===0)return{messages:Z,start:0,omittedTurns:0,omittedMessages:0};let K=J[X],B=Z.slice(0,K),z=B.filter((U)=>U.role==="system"),D=O8(B,Z.slice(K)),L={turns:X,messages:B.length-z.length},F=typeof Q.note==="function"?Q.note(L):Q.note===void 0?KZ:Q.note;if(F){let U=D[0];D[0]={...U,content:[{type:"text",text:F},...U.content]}}return{messages:[...z,...D],start:K,omittedTurns:L.turns,omittedMessages:L.messages}}function l9($){return typeof $==="number"&&$>0?$:void 0}function C8($){let Q=l9($.maxBytes)??1/0,Z=l9($.maxTokens);return Math.min(Q,Z===void 0?1/0:Z*P8)}function XZ($,Q){let Z=Array.isArray($?.namespaces)?$.namespaces:[],J=Array.isArray($?.loaded)?$.loaded:[];return Q.namespace?Z.includes(Q.namespace):J.includes(String(Q.name))}function x$($){return Array.isArray($.toolSearches)?$.toolSearches:[]}function O8($,Q){let Z=[];for(let X of $)for(let K of X.content??[])if(K.type==="tool-call")Z.push(...x$(K));if(Z.length===0)return Q;let J=[],G=new Set,W;if(Q.forEach((X,K)=>{(X.content??[]).forEach((B,z)=>{if(B.type!=="tool-call"||B.partial)return;if(J.push(...x$(B)),J.some((L)=>XZ(L,B)))return;let D=Z.filter((L)=>XZ(L,B));if(D.length===0)return;for(let L of D)G.add(L);W??={message:K,part:z}})}),!W)return Q;let V=Z.filter((X)=>G.has(X)),Y=[...Q],H=Y[W.message];return Y[W.message]={...H,content:H.content.map((X,K)=>K===W.part&&X.type==="tool-call"?{...X,toolSearches:[...V,...x$(X)]}:X)},Y}var FZ=1000,N8=24000,_8=20000,LZ=1e5,q8=120000,UZ=["You keep a running summary of a conversation between a user and an AI assistant.","The assistant will continue the conversation with only your summary and the latest turns, so the summary has to carry everything from the earlier turns it may still need.","You are given the summary so far (possibly empty) and the turns that came after it. Answer the updated summary, which replaces the old one.","Keep: the user's goals, preferences and constraints; decisions made and why; facts, names, ids, numbers, dates, file names and URLs that may matter later; what tools were used and their important results; open questions and unfinished work.","Drop greetings, repetition and anything later turns superseded. Do not invent anything, and do not answer the user.","Write terse prose or bullet points, in the language of the conversation."].join(" "),PZ="[Summary of the earlier turns of this conversation, which are not shown:]",M8=8;class b${ttlMs;threads=new Map;lastSweep=0;constructor($=86400000){this.ttlMs=$}async loadSummaries($){this.sweep();let Q=this.threads.get($);if(!Q)return[];return Q.touchedAt=Date.now(),Q.summaries.slice()}async saveSummary($,Q){this.sweep();let Z=this.threads.get($)??{summaries:[],touchedAt:Date.now()};Z.summaries=n9(Z.summaries,Q),Z.touchedAt=Date.now(),this.threads.set($,Z)}delete($){this.threads.delete($)}sweep($=Date.now()){if($-this.lastSweep<60000)return;this.lastSweep=$;for(let[Q,Z]of this.threads)if($-Z.touchedAt>this.ttlMs)this.threads.delete(Q)}}function n9($,Q){return[Q,...$.filter((Z)=>Z.cutMessageId!==Q.cutMessageId)].slice(0,M8)}var f$=new b$;function CZ($){let Q=$;return typeof Q?.loadSummaries==="function"&&typeof Q?.saveSummary==="function"}function OZ($,Q,Z){let J=c(Z.maxSummaryTokens)??FZ,G=(H)=>Math.max(1,H-J),W={...Q,...c(Q.maxTokens)?{maxTokens:G(Q.maxTokens)}:{},...c(Q.maxBytes)?{maxBytes:Math.max(1,Q.maxBytes-J*w$)}:{}},V=R8(Q,Z),Y={...W,note:!1,...V?{maxTokens:Math.min(W.maxTokens??1/0,G(V))}:{}};return{plain:W,cut:J9($,Y),maxSummaryTokens:J}}function R8($,Q){if(Q.triggerTokens===!1)return;let Z=c(Q.triggerTokens||void 0);if(Z)return Z;if(c($.maxTokens)||c($.maxBytes))return;return LZ}async function NZ($){let{history:Q,window:Z,compact:J}=$,{plain:G,cut:W,maxSummaryTokens:V}=OZ(Q,Z,J);if(W.omittedTurns===0)return W.messages;let Y=`${Q[W.start].id}:${W.start}`,H=$.memo?.get(Y);if(H===void 0){try{H=await k8($,W.start,V)}catch(D){if($.signal.aborted)throw D;H=null}if(!$.signal.aborted)$.memo?.set(Y,H)}if(!H)return J9(Q,G).messages;let X=Q.length-W.start,K=W.messages.slice(0,W.messages.length-X),B=W.messages.slice(W.messages.length-X),z=Q[W.start];return[...K,{id:`summary_${z.id}`,role:"user",content:[{type:"text",text:`${PZ}
|
|
3
|
+
${H.text}`}],createdAt:z.createdAt},...B]}var zZ="\x00next-turn";function _Z($){let Q=j8($).finally(()=>i9.delete(Q));return i9.add(Q),Q}var i9=new Set;async function j8($){try{let Q={id:zZ,role:"user",content:[{type:"text",text:""}],createdAt:new Date().toISOString()},Z=[...$.history,Q],J=[...$.stored,Q],{cut:G,maxSummaryTokens:W}=OZ(Z,$.window,$.compact);if(G.omittedTurns===0||Z[G.start].id===zZ)return;let V=qZ({...$,history:Z,stored:J},G.start);if((await o9($.store,$.threadId)).some(V.matches))return;await MZ(V,{...$,history:Z,stored:J},G.start,W).promise}catch{}}async function S8(){while(R9.size>0||i9.size>0)await Promise.allSettled([...i9,...[...R9.values()].map(($)=>$.promise)])}var R9=new Map,i=new Map,A8=1000;function T8($,Q){i.set($,M(i.get($)??R(),Q));while(i.size>A8)i.delete(i.keys().next().value)}function BZ($,Q){let Z=i.get($);if(!Z)return;i.delete($),Q(Z)}function qZ($,Q){let Z=$.history[Q].id,J=h8($.stored,Q),G=J[Q];return{key:`${$.threadId}\x00${Z}\x00${G}`,fingerprints:J,matches:(W)=>W?.cutMessageId===Z&&W.fingerprint===G}}async function k8($,Q,Z){let J=qZ($,Q),G=(await o9($.store,$.threadId)).find(J.matches);if(G)return BZ(J.key,$.onUsage),G;let W=MZ(J,$,Q,Z);if(W.owed)$.onUsage(W.owed),W.owed=void 0;W.payers.push($.onUsage);try{return await E8(W.promise,$.signal)}finally{W.payers.splice(W.payers.indexOf($.onUsage),1),BZ(J.key,$.onUsage)}}function MZ($,Q,Z,J){let G=R9.get($.key);if(G)return G;let W={promise:void 0,payers:[],owed:void 0},V=(Y)=>{let H=W.payers[0];if(H)H(Y);else W.owed=M(W.owed??R(),Y)};return W.promise=(async()=>{let{store:Y,threadId:H}=Q,X=c(Q.compact.lockWaitMs)??_8,K=null;if(Y.lockSummary){try{K=await Y.lockSummary(H,Q.history[Z].id,X+60000)}catch{K=null}if(!K)return I8(Q,$.matches,X)}try{let B=await o9(Y,H),z=B.find($.matches);if(z)return z;return await w8(Q,B,$.fingerprints,Z,J,V)}finally{if(K)await K().catch(()=>{})}})().catch(()=>null).finally(()=>{if(R9.delete($.key),W.owed)T8($.key,W.owed);W.owed=void 0}),R9.set($.key,W),W}function E8($,Q){if(Q.aborted)return Promise.reject(Q.reason);return new Promise((Z,J)=>{let G=()=>J(Q.reason);Q.addEventListener("abort",G,{once:!0}),$.then((W)=>{Q.removeEventListener("abort",G),Z(W)},(W)=>{Q.removeEventListener("abort",G),J(W)})})}async function o9($,Q){try{let Z=await $.loadSummaries(Q);return Array.isArray(Z)?Z.filter(x8):[]}catch{return[]}}function x8($){let Q=$;return!!Q&&typeof Q.cutMessageId==="string"&&typeof Q.text==="string"&&typeof Q.fingerprint==="string"}async function I8($,Q,Z){let J=Date.now()+Z;while(Date.now()<J){await new Promise((W)=>setTimeout(W,250));let G=(await o9($.store,$.threadId)).find(Q);if(G)return G}return null}async function w8($,Q,Z,J,G,W){let{history:V,compact:Y}=$,H=q9(V),X=H.indexOf(J),K=new Map(H.map((N)=>[V[N].id,N])),B,z=0;for(let N of Q){let A=K.get(N.cutMessageId);if(A===void 0||A>=J||A<=z)continue;if(N.fingerprint!==Z[A])continue;B=N,z=A}let D=(c(Y.chunkTokens)??N8)*w$,L=b8(V,H,z,J,D),F=G*w$,U=`${Y.instructions??UZ} Keep the summary under about ${Math.round(G*0.75)} words.`,P=B?.text??"",q=R();for(let N of L){let A=await U$({provider:Y.provider??$.provider,instructions:U,prompt:`Summary so far:
|
|
4
|
+
${P||"(none yet: these are the first turns of the conversation)"}
|
|
4
5
|
|
|
5
|
-
|
|
6
|
+
The turns that came after it:
|
|
7
|
+
${N}`,output:d9.object({summary:d9.string()}),reasoning:Y.reasoning??"low",signal:AbortSignal.timeout(q8)});if(q=M(q,A.usage),W(A.usage),!A.ok)return null;P=M9(A.output.summary.trim(),F)}if(!P)return null;let _={cutMessageId:V[J].id,text:P,turns:X<0?0:X,messages:J,fingerprint:Z[J],createdAt:new Date().toISOString(),usage:q};try{await $.store.saveSummary($.threadId,_)}catch{}return _}var w$=4;function b8($,Q,Z,J,G){let W=new Set,V=new Set(Q);for(let B=0;B<$.length;B++)if($[B].role==="user"&&!V.has(B)&&B!==0)W.add($[B].id);let Y=Math.max(500,Math.min(20000,Math.floor(G/2))),H=[],X="",K=Q.filter((B)=>B>=Z&&B<J);if(K.forEach((B,z)=>{let D=K[z+1]??J,L=[];for(let U=B;U<D;U++){let P=f8($[U],W.has($[U].id),Y);if(P)L.push(P)}let F=L.join(`
|
|
8
|
+
`);if(!F)return;if(X&&X.length+F.length+2>G)H.push(X),X="";X=X?`${X}
|
|
6
9
|
|
|
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
|
-
${
|
|
10
|
+
${F}`:F}),X)H.push(X);return H}function f8($,Q,Z){if($.role==="system")return"";let J=Q?"Tool (file shown)":$.role==="user"?"User":"Assistant",G=($.content??[]).map((W)=>v8(W,Z)).filter(Boolean);return G.length>0?`${J}: ${G.join(`
|
|
11
|
+
`)}`:""}function v8($,Q){switch($.type){case"text":return M9($.text??"",Q);case"file":return`[file: ${$.name??$.mimeType??$.fileId??"attachment"}]`;case"tool-call":return`[called ${$.namespace?`${$.namespace}.${String($.name)}`:String($.name)}(${M9(I$($.input),Math.min(Q,1000))})]`;case"tool-result":{let Z=$.status==="ok"?I$($.output):$.status==="error"?`error: ${$.error?.message??""}`:$.status==="running"?`a background job (${$.job?.id??"unknown"}) that was still running`:`${$.status}${$.reason?`: ${$.reason}`:""}`;return`[${String($.name)} returned: ${M9(Z,Math.min(Q,2000))}]`}case"output":return`[structured answer: ${M9(I$($.value),Math.min(Q,2000))}]`;default:return""}}function I$($){if(typeof $==="string")return $;try{return JSON.stringify($)??""}catch{return String($)}}function M9($,Q){return $.length<=Q?$:`${$.slice(0,Q)}\u2026[cut]`}function c($){return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):void 0}function h8($,Q){let Z=["0"],J="";for(let G=0;G<Q;G++){let W;try{W=JSON.stringify($[G])??""}catch{W=String($[G]?.id)}J=DZ(`${J}|${DZ(W)}`),Z.push(J)}return Z}function DZ($){let Q=3735928559,Z=1103547991;for(let J=0;J<$.length;J++){let G=$.charCodeAt(J);Q=Math.imul(Q^G,2654435761),Z=Math.imul(Z^G,1597334677)}return Q=Math.imul(Q^Q>>>16,2246822507)^Math.imul(Z^Z>>>13,3266489909),Z=Math.imul(Z^Z>>>16,2246822507)^Math.imul(Q^Q>>>13,3266489909),(4294967296*(2097151&Z)+(Q>>>0)).toString(36)}class n extends Error{pending;path;nested;constructor($){super(`A nested agent run is waiting on the user for ${$.pending.length} tool call(s).`);this.name="PendingEscalation",this.pending=$.pending,this.path=$.path,this.nested=$.nested}}class o{name;description;inputSchema;outputSchema;requiresApproval;deferred;answeredBy;timeoutMs;async;execute;constructor($){this.name=$.name,this.description=$.description,this.inputSchema=$.inputSchema,this.outputSchema=$.outputSchema,this.requiresApproval=$.requiresApproval===!0,this.deferred=$.deferred===!0,this.answeredBy=$.answeredBy==="client"?"client":"server",this.execute=$.execute??void 0,this.timeoutMs=$.timeoutMs,this.async=$.async}static create($){if(typeof $.inputSchema!=="function")m$($.inputSchema,`The tool "${$.name}"`,"inputSchema");if($.timeoutMs!==void 0)t9($.timeoutMs,`The tool "${$.name}"`,"timeoutMs");if($.async?.deadlineMs!==void 0)t9($.async.deadlineMs,`The tool "${$.name}"`,"async.deadlineMs");if($.async&&$.answeredBy==="client")throw Error(`The tool "${$.name}" is answered by the client and cannot be \`async\`: background jobs are for tools the server runs.`);return new o($)}static ask($){return o.create({name:$.name,description:$.description,inputSchema:u$,outputSchema:$.outputSchema,answeredBy:"client"})}}var u$={toJSONSchema:()=>({type:"object",properties:{question:{type:"string",description:"What to ask the user"}},required:["question"],additionalProperties:!1}),parse($){let Q=u$.safeParse($);if(Q.ok===!1)throw Error(Q.errors.join(", "));return Q.value},safeParse($){if(typeof $!=="object"||$===null||typeof $.question!=="string")return{ok:!1,errors:["question: expected a string"]};return{ok:!0,value:{question:$.question}}}};class G9{name;description;tools;deferred;constructor($){this.name=$.name,this.description=$.description,this.tools=$.tools,this.deferred=$.deferred===!0}static create($){return new G9($)}}class c${name;description;instructions;files;constructor($){this.name=$.name,this.description=$.description,this.instructions=$.instructions,this.files=$.files}static create($){return new c$($)}}var j9="skills",y8="Instructions this agent can load on demand. Load the relevant one before acting in the area it covers.";function m$($,Q,Z){let J=$?.toJSONSchema?.();if(J?.type==="object")return;let G=!J?"no JSON Schema":J.anyOf?"a union (`anyOf`) \u2014 `s.union(...)`":J.type!==void 0?`a schema of type ${JSON.stringify(J.type)}`:"an unconstrained schema (`s.json()`)";throw Error(`${Q} declares an \`${Z}\` whose root is ${G}, but the provider only accepts an object there (OpenAI rejects \`anyOf\` or a non-object at the root of tool parameters and structured output). Wrap it in an object, e.g. \`s.object({ value: s.union([...]) })\`, and read \`.value\` off the result.`)}function t9($,Q,Z){if(typeof $==="number"&&$>0)return;throw Error(`${Q} sets \`${Z}\` to ${String($)}, but it has to be a positive number of milliseconds. Use \`null\` for no limit.`)}function RZ($){if($===void 0)return;if($===null||!Number.isFinite($))return null;return $}var g8=2147483647;function jZ($,Q){if($===null||$>g8)return()=>{};let Z=setTimeout(Q,$);return()=>clearTimeout(Z)}function v$($){if($<1000)return`${$}ms`;if($<60000)return`${+($/1000).toFixed(1)}s`;return`${+($/60000).toFixed(1)}m`}var p$={type:"object",properties:{},required:[],additionalProperties:!1},l$=600000;class L9 extends Error{code;retryable;status;requestId;toolCallId;runId;result;constructor($){super($.error.message);this.name="AgentRunError",this.code=$.error.code,this.retryable=$.error.retryable,this.status=$.error.status,this.requestId=$.error.requestId,this.toolCallId=$.error.toolCallId,this.runId=$.runId,this.result=$}}var u8=8,c8=3;class d${name;tools;skills;provider;output;instructions;maxSteps;maxDepth;reasoning;maxRunDurationMs;jobs;config;constructor($){this.name=$.name,this.instructions=$.instructions,this.provider=$.provider,this.tools=$.tools??[],this.skills=$.skills??[],this.output=$.output,this.maxSteps=$.maxSteps??u8,this.maxDepth=$.maxDepth??c8,this.reasoning=$.reasoning,this.jobs=$.jobs??{};let Q=RZ($.maxRunDurationMs);this.maxRunDurationMs=Q===void 0?l$:Q;let{registry:Z,providerTools:J}=m8(this.tools,this.skills);this.config={name:this.name,instructions:this.instructions,provider:this.provider,registry:Z,providerTools:J,output:$.output,maxSteps:this.maxSteps,maxDepth:this.maxDepth,reasoning:this.reasoning,maxOutputTokens:$.maxOutputTokens,temperature:$.temperature,logErrors:$.logErrors??!0,maxRunDurationMs:Q,contextWindow:$.contextWindow,prepareStep:$.prepareStep?[$.prepareStep]:[]}}static create($){if($.output)m$($.output,`The agent "${$.name}"`,"output");if($.maxRunDurationMs!=null)t9($.maxRunDurationMs,`The agent "${$.name}"`,"maxRunDurationMs");let Q=$.jobs?.contextBlock;if(Q&&Q.max!==void 0&&!(Number.isInteger(Q.max)&&Q.max>0))throw Error(`The agent "${$.name}" sets \`jobs.contextBlock.max\` to ${String(Q.max)}, but it has to be a whole number above 0. Use \`contextBlock: false\` for no block.`);return new d$($)}stream($){let Q={...this.config,provider:$.provider??this.config.provider,maxSteps:$.maxSteps??this.config.maxSteps,reasoning:$.reasoning??this.config.reasoning,maxOutputTokens:$.maxOutputTokens??this.config.maxOutputTokens,temperature:$.temperature??this.config.temperature,maxRunDurationMs:$.maxRunDurationMs!==void 0?RZ($.maxRunDurationMs):this.config.maxRunDurationMs,contextWindow:$.contextWindow===!1?void 0:$.contextWindow??this.config.contextWindow,prepareStep:$.prepareStep?[...this.config.prepareStep,$.prepareStep]:this.config.prepareStep};if($.maxRunDurationMs!=null)t9($.maxRunDurationMs,`Agent.stream for "${this.name}"`,"maxRunDurationMs");return new hZ(Q,$)}}function y$($){let Q=$.inputSchema;return{name:$.tool.name,description:$.tool.description,parameters:Q?Q.toJSONSchema():p$,strict:Q?z9(Q):!0,deferred:$.deferred}}function h$($){return typeof $.inputSchema==="function"?void 0:$.inputSchema}function m8($,Q){let Z=new Map,J=[],G=(W)=>{if(Z.has(W.tool.name))throw Error(`Two tools are named "${W.tool.name}". Tool names are global within an agent \u2014 the client discriminates a tool part by name alone.`);Z.set(W.tool.name,W)};for(let W of $){if(W instanceof G9){if(W.name===j9)throw Error(`"${j9}" 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 W.tools){let X={tool:H,namespace:W.name,deferred:W.deferred||H.deferred,inputSchema:h$(H)};G(X),Y.push(y$(X))}J.push({name:W.name,description:W.description,tools:Y});continue}let V={tool:W,deferred:W.deferred,inputSchema:h$(W)};G(V),J.push(y$(V))}if(Q.length>0){let W=[];for(let V of Q){let Y=p8(V);G({tool:Y,namespace:j9,deferred:!1,inputSchema:h$(Y)}),W.push({name:V.name,description:V.description,parameters:p$,strict:!0,deferred:!1})}J.push({name:j9,description:y8,tools:W})}return{registry:Z,providerTools:J}}function p8($){return o.create({name:$.name,description:$.description,inputSchema:{toJSONSchema:()=>p$,parse:()=>({}),safeParse:()=>({ok:!0,value:{}})},execute:async()=>{let Z=[typeof $.instructions==="function"?await $.instructions():$.instructions];for(let J of $.files??[])Z.push(`--- ${J} ---
|
|
12
|
+
${await l8(J)}`);return Z.join(`
|
|
9
13
|
|
|
10
|
-
`)}})}async function
|
|
14
|
+
`)}})}async function l8($){try{return await Bun.file($).text()}catch(Q){return`(could not be read: ${Q.message})`}}function d8($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}function SZ($,Q){let Z=[...$],J=new Map(Z.map((G,W)=>[G.id,W]));for(let G of Q){let W=J.get(G.id);if(W===void 0)J.set(G.id,Z.length),Z.push(G);else Z[W]=G}return Z}function s9($){let Q=new Set;for(let J of $)for(let G of J.content)if(G.type==="tool-result")Q.add(G.toolCallId);let Z=new Set;for(let J of $)for(let G of J.content)if(G.type==="tool-call"&&!Q.has(G.toolCallId))Z.add(G.toolCallId);return Z}function AZ($){for(let Q=$.length-1;Q>=0;Q--){let Z=$[Q].content;for(let J=Z.length-1;J>=0;J--){let G=Z[J];if(G.type==="output"&&G.partial!==!0)return G.value}}return}function TZ($,Q){return Q===void 0?`"${$}"`:`"${$}" labelled "${Q}"`}function vZ($){return $.content.map((Q)=>Q.type==="text"?Q.text:`<${Q.type}>`).join("")}function i8($){if($.prompt!==void 0)return`user:${$.prompt}`;let Q=$.messages?.[0];return Q?`${Q.role}:${vZ(Q)}`:null}var kZ=1;function n8($,Q,Z){let J=Z.mimeType||Q.type||"";if(J&&$.attachment.mimeType!==J)return`was ${JSON.stringify($.attachment.mimeType)} on the turn that escalated and is ${JSON.stringify(J)} on the replay`;let G=Boolean(Z.showModel);if(G!==Boolean($.shown))return G?"was stored without showModel on the turn that escalated and asks for showModel on the replay":"was stored with showModel on the turn that escalated and asks for a plain put on the replay";return null}function o8($,Q,Z){if($.agent!==Q.name||$.label!==Z.label)return`was ${TZ($.agent,$.label)} on the turn that escalated and is ${TZ(Q.name,Z.label)} on the replay`;let J=i8(Z),G=$.messages[0],W=G?`${G.role}:${vZ(G)}`:null;if(J!==null&&W!==null&&J!==W)return`was started with ${JSON.stringify(W)} on the turn that escalated and with ${JSON.stringify(J)} on the replay`;return null}function EZ($,Q){let Z=$??[];if(Z.length<Q.length)return null;for(let J=0;J<Q.length;J++)if(Z[J]!==Q[J])return null;return Z.slice(Q.length)}class g${read;create;fill;index=0;replayable;constructor($,Q,Z){this.read=$;this.create=Q;this.fill=Z;this.replayable=$()?.length??0}next(){let $=this.index++;return{at:$,recorded:$<this.replayable?this.read()?.[$]:void 0,write:(Q)=>{let Z=this.read()??this.create();if(this.fill)for(let J=Z.length;J<$;J++)Z[J]=this.fill();Z[$]=Q}}}}class hZ{runId;config;params;context;controller=new AbortController;buffer=[];waiters=new Set;seq=0;ended=!1;history=[];compactMemo=new Map;lastStep;produced=[];current=null;outputTruncated=!1;amended=new Map;unreported=new Set;usage=R();finishReason="stop";failure;output;stopReason;timedOutAfter;cancelDeadline=()=>{};settled;depth;maxDepth;chain;signingRunId;pathPrefix;onPending;nestedSettling=new Set;shownQueue=new Map;constructor($,Q){this.config=$,this.params=Q,this.context=Q.context??{},this.runId=Q.runId??`run_${crypto.randomUUID()}`,this.history=[...Q.messages];let Z=Q.nesting;if(this.depth=Z?.depth??0,this.maxDepth=Z?.maxDepth??$.maxDepth,this.chain=Z?.chain??[$.name],this.signingRunId=Z?.signingRunId??this.runId,this.pathPrefix=Z?.signingPath??[],this.onPending=Z?.onPending??"escalate",Q.signal)if(Q.signal.aborted)this.controller.abort();else Q.signal.addEventListener("abort",()=>this.stop(),{once:!0});let J=$.maxRunDurationMs!==void 0?$.maxRunDurationMs:Z?null:l$;this.cancelDeadline=jZ(J,()=>this.expire(J)),this.settled=this.execute(),a9.getStore()?.waitUntil(this.settled)}emit($){if(this.ended)return;this.buffer.push({seq:++this.seq,event:$}),this.wake()}wake(){let $=[...this.waiters];this.waiters.clear();for(let Q of $)Q()}nextFrame(){return new Promise(($)=>this.waiters.add($))}async*frames($=0){let Q=$>0?$-1:0;for(;;){while(Q<this.buffer.length)yield this.buffer[Q++];if(this.ended)return;await this.nextFrame()}}async*[Symbol.asyncIterator](){for await(let $ of this.frames())yield $.event}toResponse($){let Q=this.frames($?.from),Z=new TextEncoder,J=!1,G,W=new ReadableStream({start:async(V)=>{G=wZ(V);try{for await(let Y of Q){if(J)break;V.enqueue(Z.encode(`id: ${Y.seq}
|
|
11
15
|
data: ${JSON.stringify(Y.event)}
|
|
12
16
|
|
|
13
|
-
`)),
|
|
17
|
+
`)),G.touch()}}catch{}G.stop();try{V.close()}catch{}},cancel:()=>{J=!0,G.stop()}});return new Response(W,{headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}result($){if(!$?.throwOnError)return this.settled;return this.settled.then((Q)=>{if(Q.error)throw new L9({...Q,error:Q.error});return Q})}stop($){if(this.ended||this.controller.signal.aborted)return;this.stopReason=$?.reason,this.controller.abort()}expire($){if(this.ended||this.controller.signal.aborted)return;this.timedOutAfter=$,this.stopReason=`The run reached its time limit of ${v$($)} 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 Q=await this.resolveToolSchemas(),Z=Q?[]:await this.ingestTurn();if(Q)this.fail(Q),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(Q){if(Q instanceof w||this.controller.signal.aborted)await this.finalizeAborted();else this.fail(this.config.provider.normalizeError(Q),b(Q)),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(),this.precompact();let $=this.finishReason==="error"?this.failure:void 0;if($&&this.config.logErrors)this.logFailure($);return{runId:this.runId,messages:this.produced,finishReason:this.finishReason,usage:this.usage,output:this.output,...$?{error:$}:{}}}async resolveToolSchemas(){let $=[...this.config.registry.values()].filter((H)=>!H.inputSchema);if($.length===0)return;let Q={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($.map(async(H)=>{try{let X=H.tool.inputSchema,K=await X(Q);m$(K,`The tool "${H.tool.name}"`,"inputSchema"),Z.set(H.tool.name,K);return}catch(X){return`"${H.tool.name}": ${X instanceof Error?X.message:String(X)}`}}));if(this.controller.signal.aborted)throw new w;let G=J.filter((H)=>H!==void 0);if(G.length>0)return{code:"tool_error",message:`Could not resolve the input schema of ${G.join("; ")}`,retryable:!1};let W=new Map;for(let[H,X]of this.config.registry)W.set(H,Z.has(H)?{...X,inputSchema:Z.get(H)}:X);let V=(H)=>Z.has(H.name)?y$(W.get(H.name)):H,Y=this.config.providerTools.map((H)=>("tools"in H)?{...H,tools:H.tools.map(V)}:V(H));this.config={...this.config,registry:W,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=bZ(this.params.redactError,$,Q,(J)=>this.writeLog(`[gemi/ai] agent "${this.config.name}" redactError threw`,{error:J}));return fZ(Z,$),Z}logFailure($){let Q=`[gemi/ai] agent "${this.config.name}" run failed (${$.code}${$.status!==void 0?` ${$.status}`:""}): ${$.message}`;this.writeLog(Q,{error:$})}logToolFailure($,Q){let Z=Q instanceof Error?Q.message:String(Q);this.writeLog(`[gemi/ai] agent "${this.config.name}" tool "${String($.name)}" threw: ${Z}`,{toolCallId:$.toolCallId,error:Q})}writeLog($,Q){let Z={agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},...this.depth>0?{chain:this.chain}:{},...Q},J=!1;try{D9.error($,Z),J=!0}catch{}if(!J||Bun.env.NODE_ENV==="development")console.error($,Z)}async loop(){let $=Math.max(1,this.config.maxSteps);for(let Q=1;Q<=$;Q++){let Z=this.startMessage(),J=await this.runStep(Z,Q);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 G=Z.content.filter((V)=>V.type==="tool-call");if(G.length===0){this.finishReason=J.reason,await this.finalizeMessage(J.reason);return}let W=await this.runTools(Z,G,Q);if(W.length>0){this.finishReason="awaiting-input",await this.finalizeMessage("awaiting-input"),this.emit({type:"awaiting-input",runId:this.runId,pending:W});return}if(Q===$){this.finishReason="max-steps",await this.finalizeMessage("max-steps");return}await this.finalizeMessage(J.reason)}}startMessage(){let $={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()};return this.current=$,this.history.push($),this.produced.push($),this.emit({type:"message-start",messageId:$.id,role:"assistant"}),$}async finalizeMessage($){let Q=this.current;if(!Q)return;this.current=null;let Z=this.outputTruncated;if(this.outputTruncated=!1,Q.finishReason=$,Z)Q.outputTruncated=!0;for(let J of Q.content)if(J.type==="text"||J.type==="reasoning"){if(typeof J.text==="string")J.text=b9(J.text)}this.emit({type:"message-end",messageId:Q.id,finishReason:$,...Z?{outputTruncated:!0}:{},...Q.usage?{usage:Q.usage}:{}}),await this.report(Q),await this.reportDeferred()}async report($){if(!this.params.onMessage)return;try{await this.params.onMessage($)}catch{}}async runStep($,Q){let Z=this.controller.signal,J=this.config.provider,G=await this.prepareRequest($,Q);if("error"in G)return{reason:"error",error:G.error};let W={reason:"stop"},V=new Map,Y=[],H=()=>{if(Y.length===0)return{};let D=Y;return Y=[],{toolSearches:D}},X="",B=J.stream({messages:G.messages,systemPrompt:G.instructions,tools:this.config.providerTools.length>0?this.config.providerTools:void 0,output:this.config.output?I9(this.config.output):void 0,reasoning:this.config.reasoning,maxOutputTokens:this.config.maxOutputTokens,temperature:this.config.temperature,signal:Z})[Symbol.asyncIterator]();for(;;){let D=await m(Promise.resolve(B.next()),Z);if(D.done)break;let L=D.value;switch(L.type){case"text-delta":{B9($,"text",L.delta),this.emit({type:"text-delta",messageId:$.id,delta:L.delta});break}case"reasoning-delta":{f9($,L.id,L.delta),this.emit({type:"reasoning-delta",messageId:$.id,delta:L.delta,id:L.id});break}case"output-delta":{X+=L.delta,this.emit({type:"output-delta",messageId:$.id,delta:L.delta,snapshot:x9(X)});break}case"tool-search":{Y.push({namespaces:L.namespaces,loaded:L.loaded,...L.arguments!==void 0?{arguments:L.arguments}:{}}),this.emit({type:"tool-search",loaded:L.loaded});break}case"tool-call-delta":{let F=V.get(L.toolCallId)??{name:L.name,args:""};F.args+=L.argsDelta,F.name=L.name||F.name,F.namespace=L.namespace||F.namespace,V.set(L.toolCallId,F),this.emit({type:"tool-call",messageId:$.id,part:{type:"tool-call",toolCallId:L.toolCallId,name:F.name,input:x9(F.args),partial:!0,...F.namespace?{namespace:F.namespace}:{}}});break}case"tool-call":{let F=L.namespace||V.get(L.toolCallId)?.namespace;V.delete(L.toolCallId);let U={type:"tool-call",toolCallId:L.toolCallId,name:L.name,input:IZ(L.args),...F?{namespace:F}:{},...H()};$.content.push(U),this.emit({type:"tool-call",messageId:$.id,part:U});break}case"finish":{if(this.usage=M(this.usage,L.usage),$.usage=M($.usage??R(),L.usage),!W.error)W={reason:L.reason};break}case"error":{W={reason:"error",error:L.error,detail:b(L)};break}case"file-rejected":{this.markFileRejected(L.fileId,L.message,b(L));break}}}for(let[D,L]of V){let F={type:"tool-call",toolCallId:D,name:L.name,input:IZ(L.args),...L.namespace?{namespace:L.namespace}:{},...H()};$.content.push(F),this.emit({type:"tool-call",messageId:$.id,part:F})}let z=W.reason==="length";if(z)this.outputTruncated=!0;if(this.config.output&&X&&!W.error&&!z){let D=w9(this.config.output,X);if(D.ok===!0)this.output=D.value,$.content.push({type:"output",value:D.value});else this.emit({type:"error",error:D.error})}return W}compactJobParams($,Q){let Z=this.config.contextWindow;if(!Z?.compact||!this.params.threadId||this.depth!==0)return;let J=Z.compact===!0?{}:Z.compact;return{history:$,stored:this.history.filter((G)=>G!==Q),window:Z,compact:J,threadId:this.params.threadId,provider:this.config.provider,store:J.store||this.params.summaryStore||f$}}precompact(){let $=this.config.contextWindow;if(!$?.compact||$.compact!==!0&&$.compact.background===!1)return;try{let Q=this.compactJobParams(this.historyForProvider(void 0),void 0);if(Q)_Z(Q)}catch{}}async prepareRequest($,Q){let Z=this.historyForProvider($),J=this.config.contextWindow,G=this.compactJobParams(Z,$),W=!J?Z:G?await NZ({...G,signal:this.controller.signal,onUsage:(Y)=>{this.usage=M(this.usage,Y)},memo:this.compactMemo}):J9(Z,J).messages,V=await this.systemPrompt();for(let Y of this.config.prepareStep){let H;try{H=await Y({step:Q,messages:[...W],history:[...Z],instructions:V,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(X){if(X instanceof w||this.controller.signal.aborted)throw X;return{error:{code:"unknown",message:`prepareStep threw: ${X instanceof Error?X.message:String(X)}`,retryable:!1}}}if(!H)continue;if(H.messages!==void 0){if(!Array.isArray(H.messages))return{error:{code:"unknown",message:"prepareStep answered `messages` that is not an array.",retryable:!1}};W=H.messages}if(H.instructions!==void 0)V=H.instructions||void 0}return{messages:W,instructions:V}}async systemPrompt(){let $=[this.config.instructions,this.params.instructions].filter((Q)=>Boolean(Q&&Q.trim()));return $.length>0?$.join(`
|
|
14
18
|
|
|
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
|
-
`)
|
|
17
|
-
|
|
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
|
+
`):void 0}async runTools($,Q,Z){let J=[],G=[];for(let W of Q){let V=this.config.registry.get(String(W.name));if(!V){this.addResult($,{type:"tool-result",toolCallId:W.toolCallId,name:W.name,status:"error",error:{code:"tool_error",message:`There is no tool named "${String(W.name)}".`,toolCallId:W.toolCallId,retryable:!0}});continue}let Y=V.inputSchema.safeParse(W.input);if(Y.ok===!1){this.addResult($,{type:"tool-result",toolCallId:W.toolCallId,name:W.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${String(W.name)}": ${Y.errors.join(", ")}`,toolCallId:W.toolCallId,retryable:!0}});continue}W.input=Y.value;let H=xZ(V.tool);if(H){if(this.onPending==="deny"){this.addResult($,this.deniedByPolicy(W));continue}J.push({toolCallId:W.toolCallId,name:W.name,input:Y.value,kind:H,signature:tQ(this.claimsFor(W.toolCallId,String(W.name),H,Y.value)),...this.pathPrefix.length>0?{path:[...this.pathPrefix]}:{}});continue}G.push(this.executeTool(V,$.id,W,Y.value,Z).then(async(X)=>{this.addResult($,X),await this.settleShown(W.toolCallId)}).catch((X)=>{if(X instanceof n){if(this.onPending==="deny"){this.addResult($,this.deniedByPolicy(W));return}J.push(...X.pending);return}}))}return await m(Promise.all(G).then(()=>{return}),this.controller.signal),J}claimsFor($,Q,Z,J){return{runId:this.signingRunId,toolCallId:$,name:Q,kind:Z,input:J,path:this.pathPrefix.length>0?[...this.pathPrefix]:void 0,subject:this.params.subject??null}}deniedByPolicy($){return{type:"tool-result",toolCallId:$.toolCallId,name:$.name,status:"denied",cause:"refused",reason:`"${String($.name)}" needs the user, and this run was started with onPending: "deny". Answer from what you already have.`}}async executeTool($,Q,Z,J,G,W){let V=$.tool.timeoutMs;if(V===void 0)return this.runToolBody($,Q,Z,J,G,W,this.controller.signal,()=>!1);let Y=new AbortController,H=this.controller.signal,X=()=>Y.abort(H.reason);if(H.aborted)X();else H.addEventListener("abort",X,{once:!0});let K=!1,B=this.runToolBody($,Q,Z,J,G,W,Y.signal,()=>K),z=()=>{},D=new Promise((L)=>{z=jZ(V,()=>{let F=`"${String(Z.name)}" did not finish within ${v$(V)} (timeoutMs: ${V}) and was cancelled.`;Y.abort(new DOMException(F,"TimeoutError")),L({type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:{code:"timeout",message:F,toolCallId:Z.toolCallId,retryable:!0}})})});B.catch(()=>{});try{return await Promise.race([B,D])}finally{K=!0,z()}}async runToolBody($,Q,Z,J,G,W,V,Y){let H=this.toolFiles(Z,V),X={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,toolCallId:Z.toolCallId,signal:V,step:G,depth:this.depth,resumed:W!==void 0,attachments:H.attachments,generateImage:H.generateImage,editImage:H.editImage,turn:this.toolTurn(Q),runAgent:this.nestedRunner(Q,Z,V,W),generate:(K)=>this.generateForTool(K,V,Z.toolCallId),jobs:uQ({jobs:this.depth===0?this.params.jobs:void 0,threadId:this.params.threadId,runId:this.runId,toolCallId:Z.toolCallId,toolName:String(Z.name),depth:this.depth,async:$.tool.async,attachments:this.params.attachments??null})};try{let K=$.tool.execute(J,X),B;if(d8(K)){let z=await K.next();while(!z.done){if(Y())throw K.return(void 0).catch(()=>{}),new w;this.emit({type:"tool-progress",toolCallId:Z.toolCallId,data:z.value}),z=await K.next()}B=z.value}else B=await K;if(yQ(B)){if(B.toolCallId!==Z.toolCallId)throw new S(`"${String(Z.name)}" returned the handle of a job another tool call started. Return the handle from this call's own ctx.jobs.`,{retryable:!1});return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"running",job:{id:B.id,...B.summary!==void 0?{summary:B.summary}:{}}}}return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"ok",output:B}}catch(K){if(K instanceof w||this.controller.signal.aborted)throw new w;if(K instanceof n)throw K;let B=K instanceof S;if(!B&&this.config.logErrors)this.logToolFailure(Z,K);let z={code:"tool_error",message:K instanceof Error?K.message:String(K),toolCallId:Z.toolCallId,retryable:B?K.retryable:!0};return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:this.redact(z,{source:"tool",toolName:String(Z.name),cause:K})}}}async generateForTool($,Q,Z){let J=this.controller.signal;return F9({...$,signal:$.signal?AbortSignal.any([Q,$.signal]):Q},{origin:{agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},toolCallId:Z},settled:(G)=>{if(this.usage=M(this.usage,G.usage),J.aborted)throw new w}})}nestedRunner($,Q,Z,J){let G=new g$(()=>Q.nested,()=>Q.nested=[]);return async(W,V={})=>{let{at:Y,recorded:H,write:X}=G.next();if(H){let K=o8(H,W,V);if(K)throw new S(`Nested run ${Y} of "${String(Q.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??R(),output:AZ(H.messages),nested:H}}return this.runNested($,Q,Z,W,V,X,H,J?.answers??[])}}async runNested($,Q,Z,J,G,W,V,Y){let H=[...this.chain,J.name];if(this.chain.includes(J.name))throw new S(`"${J.name}" is already running further up this chain: ${H.join(" -> ")}. An agent cannot run itself, directly or through another agent.`);let X=this.depth+1;if(X>this.maxDepth)throw new S(`Nested agent runs are ${this.maxDepth} deep at most and this one would be ${X}: ${H.join(" -> ")}. Raise maxDepth on the agent at the root of the run if the tree is meant to be this deep.`);let K=G.label,B=[...this.pathPrefix,Q.toolCallId],z=this.onPending==="deny"?"deny":G.onPending??"escalate",D=V!==void 0,L=D?s9(V.messages):new Set,F=D?Y.filter((O)=>{let C=EZ(O.path,B);if(C===null)return!1;return L.has(C.length>0?C[0]:O.toolCallId)}):[],U=J.stream({messages:D?V.messages:G.messages??[],turn:D?{toolResults:F}:G.prompt?{text:G.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:G.instructions,maxOutputTokens:G.maxOutputTokens,temperature:G.temperature,runId:D?V.runId:void 0,nesting:{depth:X,maxDepth:this.maxDepth,chain:H,signingRunId:this.signingRunId,signingPath:B,onPending:z}}),P=[],q=(O)=>this.emit({type:"nested-event",toolCallId:Q.toolCallId,runId:U.runId,agent:J.name,label:K,event:O}),_=(async()=>{for await(let O of U){if(O.type==="awaiting-input")P=O.pending;if(q(O),O.type==="run-start"&&!D)for(let C of G.messages??[])q({type:"message",message:C});if(O.type==="error")this.emit({type:"error",error:O.error,nested:{toolCallId:Q.toolCallId,runId:U.runId,agent:J.name}})}})(),N=(async()=>{let O=await U.result();await _;let C=D?SZ(V.messages,O.messages):SZ(G.messages??[],O.messages),T={runId:U.runId,agent:J.name,label:K,messages:C,finishReason:O.finishReason,usage:D?M(V.usage??R(),O.usage):O.usage,...O.finishReason==="awaiting-input"?{signature:QZ({runId:this.signingRunId,path:B,nestedRunId:U.runId,open:[...s9(C)],input:Q.input,subject:this.params.subject??null})}:{}};return W(T),this.usage=M(this.usage,O.usage),{result:O,record:T}})(),A=N.then(()=>{return},()=>{return});this.nestedSettling.add(A);let E,x;try{({result:E,record:x}=await N)}finally{this.nestedSettling.delete(A)}if(this.controller.signal.aborted)throw new w;if(E.finishReason==="awaiting-input"){if(P.length===0)throw new S(`"${J.name}" ended awaiting input but asked nothing, so there is no question to escalate.`);throw this.emit({type:"tool-call",messageId:$,part:Q,resent:!0}),new n({pending:P,path:B,nested:x})}return{runId:x.runId,agent:J.name,messages:x.messages,finishReason:E.finishReason,usage:x.usage??R(),output:E.output??AZ(x.messages),...E.error?{error:E.error}:{},nested:x}}addResult($,Q){$.content.push(Q),this.emit({type:"tool-result",messageId:$.id,part:Q})}toolFiles($,Q){let Z=this.params.attachments??null,J=new g$(()=>$.attachments,()=>$.attachments=[],()=>({failed:!0})),G=()=>{if(!Z)throw new u("This request has no attachment scope, so a tool cannot store or read files on it. `attachmentScope()` returned null \u2014 put the chat route behind authentication, send a `threadId`, or override `attachmentScope()` on the controller.");return Z},W=async(X,K,B)=>{let z=G(),D=K.mimeType||X.type||"",L=K.name??(X instanceof File?X.name:"attachment"),F;if(K.showModel){let P=this.config.provider;if(!P.capabilities.fileInput)throw new S(`"${String($.name)}" asked to show a file to ${P.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.`);F=await P.upload(new File([X],L,{type:D||void 0}))}return{attachment:await z.put(X,{name:L,mimeType:D,fileId:F}),...B?{generated:B}:{},...F?{shown:{fileId:F,messageId:`msg_${crypto.randomUUID()}`,createdAt:new Date().toISOString()}}:{}}},V=(X,K,B)=>{let z=X.generated?"image":"put";if(z===K)return;throw new S(`Attachment ${B} of "${String($.name)}" was ${z==="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(X,K,B)=>{let{at:z,recorded:D,write:L}=J.next();if(D&&"attachment"in D){if(V(D,"image",z),D.shown)this.queueShown($.toolCallId,D);return{attachment:D.attachment,size:D.generated.size,mimeType:D.attachment.mimeType,usage:D.generated.usage}}let F=await B();this.usage=M(this.usage,F.usage);let U=F.mimeType==="image/jpeg"?"jpg":"png",P=await W(F.image,{name:K.name??`${X.name}.${U}`,mimeType:F.mimeType,...K.showModel?{showModel:!0}:{}},{size:F.size,usage:F.usage});if(L(P),P.shown)this.queueShown($.toolCallId,P);return{attachment:P.attachment,size:F.size,mimeType:F.mimeType,usage:F.usage}},H=async(X)=>typeof X==="string"?await G().file(X):X;return{generateImage:(X,K)=>Y(X,K,()=>X.generate({...K,signal:Q})),editImage:(X,K)=>Y(X,K,async()=>{let{images:B,mask:z,...D}=K;return await X.edit({...D,images:await Promise.all(B.map(H)),...z?{mask:await H(z)}:{},signal:Q})}),attachments:{get:(X)=>G().get(X),read:(X)=>G().read(X),file:(X)=>G().file(X),put:async(X,K={})=>{let{at:B,recorded:z,write:D}=J.next();if(z&&"attachment"in z){V(z,"put",B);let F=n8(z,X,K);if(F)throw new S(`Attachment ${B} of "${String($.name)}" ${F}. `+"ctx.attachments.put is memoized by call index within a tool call, so a body whose put calls depend on a condition that changed between turns cannot be replayed \u2014 the model would be shown a file under an id that names different bytes. "+"Make the sequence of put calls the same every time this tool runs, or branch on ctx.resumed.");if(z.shown)this.queueShown($.toolCallId,z);return z.attachment}let L=await W(X,K);if(D(L),L.shown)this.queueShown($.toolCallId,L);return L.attachment}}}}toolTurn($){let Q=this.history.findIndex((W)=>W.id===$),Z=d(this.history),J;for(let W=Q-1;W>=0;W--){let V=this.history[W];if(V.role!=="user"||Z.has(V.id))continue;J=V;break}let G=[];for(let W of J?.content??[]){if(W.type!=="file")continue;let V=W.attachmentId;if(typeof V!=="string"||!V.startsWith(h))continue;if(!G.includes(V))G.push(V)}return Object.freeze({attachments:Object.freeze(G)})}queueShown($,Q){let Z=Q.shown;if(!Z)return;let J=this.shownQueue.get($)??[];if(J.some((G)=>G.id===Z.messageId))return;J.push({id:Z.messageId,role:"user",content:[{type:"file",fileId:Z.fileId,name:Q.attachment.name,mimeType:Q.attachment.mimeType,attachmentId:Q.attachment.id}],createdAt:Z.createdAt,finishReason:"stop"}),this.shownQueue.set($,J)}async settleShown($){let Q=this.shownQueue.get($);if(!Q||Q.length===0)return;if(this.shownQueue.delete($),this.ended||this.controller.signal.aborted)return;for(let Z of Q){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($){let Q=this.history.filter((W)=>W!==$),Z=d(Q),J=[];for(let W of Q){if(!Z.has(W.id))continue;for(let V of W.content)if(V.type==="file")J.push(V)}if(J.length<=kZ)return Q;let G=new Set(J.slice(0,J.length-kZ));return Q.map((W)=>{if(!W.content.some((V)=>V.type==="file"&&G.has(V)))return W;return{...W,content:W.content.map((V)=>V.type==="file"&&G.has(V)?{type:"text",text:`[A ${V.mimeType||"file"} produced by a tool (attachment ${V.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.]`}:V)}})}async ingestTurn(){let $=this.params.turn,Q=this.openCalls(),Z=[];if(Q.length>0){let J=new Set,G=new Set,W=new Map;for(let V of $?.toolResults??[]){let Y=`${(V.path??[]).join("/")}#${V.toolCallId}`;if(G.has(Y))continue;G.add(Y);let H=(z)=>this.emit({type:"error",error:{code:"invalid_tool_result",message:z,toolCallId:V.toolCallId,retryable:!1}}),X=EZ(V.path,this.pathPrefix);if(X===null){H(`The answer for "${V.toolCallId}" is addressed to a tool call this run is not inside.`);continue}if(X.length>0){let z=X[0],D=Q.find((U)=>U.call.toolCallId===z);if(!D){H(`No pending tool call with id "${z}" to deliver a nested answer to.`);continue}let L=this.parkedBelow(D.call,X,V.toolCallId);if(L.ok===!1){let U=`The answer for "${V.toolCallId}" is addressed under "${z}", which`;H(L.reason==="unparked"?`${U} has no sub-agent run waiting on that question.`:L.reason==="expired"?`${U} parked a sub-agent run that has since expired. Ask again.`:`${U} carries a record of a parked sub-agent run the server did not sign.`);continue}let F=W.get(z);if(!F){if(!await this.spend(WZ,L.signature)){H(`The answer for "${V.toolCallId}" is addressed under "${z}", which has already been re-entered on that record. Ask again.`);continue}F=[],W.set(z,F),J.add(z)}F.push(V);continue}let K=Q.find((z)=>z.call.toolCallId===V.toolCallId);if(!K){H(`No pending tool call with id "${V.toolCallId}".`);continue}let B=await this.resolveAnswer(K,V,Z);if(B===null)continue;if(J.add(V.toolCallId),B!=="open")this.attachToHistory(K,B),await this.settleShown(V.toolCallId)}for(let[V,Y]of W){let H=Q.find((K)=>K.call.toolCallId===V),X=await this.reenter(H,Y,Z);if(X)this.attachToHistory(H,X),await this.settleShown(V)}for(let V of Q){if(J.has(V.call.toolCallId))continue;this.attachToHistory(V,{type:"tool-result",toolCallId:V.call.toolCallId,name:V.call.name,status:"denied",cause:"refused"})}await this.reportDeferred()}if($&&($.text||$.files&&$.files.length>0)){let J={id:`msg_${crypto.randomUUID()}`,role:"user",content:[...$.text?[{type:"text",text:$.text}]:[],...($.files??[]).map((G)=>({type:"file",...G.fileId?{fileId:G.fileId}:{},name:G.name,mimeType:G.mimeType,...G.attachmentId?{attachmentId:G.attachmentId}:{}}))],createdAt:new Date().toISOString(),finishReason:"stop"};if(this.history.push(J),this.produced.push(J),this.depth>0)this.emit({type:"message",message:J});else if($.localId)this.emit({type:"message-id",localId:$.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=Q.length>1?Q[1]:Z,G=[...this.pathPrefix,$.toolCallId],W=($.nested??[]).find((Y)=>Y.finishReason==="awaiting-input"&&s9(Y.messages).has(J));if(!W)return{ok:!1,reason:"unparked"};if(typeof W.signature!=="string")return{ok:!1,reason:"unsigned"};let V=ZZ(W.signature,{path:G,nestedRunId:W.runId,open:[...s9(W.messages)],input:$.input,subject:this.params.subject??null});if(V.ok===!1)return{ok:!1,reason:V.reason==="expired"?"expired":"unsigned"};return{ok:!0,signature:W.signature}}async reenter($,Q,Z){let J=String($.call.name),G=this.config.registry.get(J);if(!G||!G.tool.execute)return{type:"tool-result",toolCallId:$.call.toolCallId,name:$.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:$.call.toolCallId,retryable:!1}};let W=G.inputSchema.safeParse($.call.input);if(W.ok===!1)return{type:"tool-result",toolCallId:$.call.toolCallId,name:$.call.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${J}": ${W.errors.join(", ")}`,toolCallId:$.call.toolCallId,retryable:!0}};let V=this.amendCall($);V.input=W.value;try{return await m(this.executeTool(G,$.message.id,V,W.value,0,{answers:Q}),this.controller.signal)}catch(Y){if(Y instanceof n)return Z.push(...Y.pending),null;throw Y}}amendCall($){let Q=this.amend($.message),Z=Q.content.indexOf($.call),J={...$.call,nested:($.call.nested??[]).map((G)=>({...G})),...$.call.attachments?{attachments:$.call.attachments.map((G)=>({...G}))}:{}};if(Z>=0)Q.content[Z]=J;return this.unreported.add(Q),J}openCalls(){let $=new Set;for(let Z of this.history)for(let J of Z.content)if(J.type==="tool-result")$.add(J.toolCallId);let Q=[];for(let Z of this.history)for(let J of Z.content)if(J.type==="tool-call"&&!$.has(J.toolCallId))Q.push({message:Z,call:J});return Q}async spend($,Q){try{return await $(Q,this.params.nonces??Z9)}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 Q;try{await $.store.complete($.id,Z,$.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=$.call,G=String(J.name),W=this.config.registry.get(G),V=(B)=>{return this.emit({type:"error",error:{code:"invalid_tool_result",message:B,toolCallId:J.toolCallId,retryable:!1}}),null};if(!W)return V(`The tool "${G}" no longer exists, so its answer cannot be checked.`);let Y=xZ(W.tool);if(!Y)return V(`"${G}" is a server tool with no pending question.`);if(typeof Q.signature!=="string"||Q.signature.length===0)return V(`The answer for "${G}" carried no signature.`);let H=k$(Q.signature);if(!H)return V(`The signature for "${G}" is malformed.`);let X=aQ(Q.signature,{...this.claimsFor(J.toolCallId,G,Y,J.input),runId:H.runId});if(X.ok===!1)return V(X.reason==="expired"?`The approval for "${G}" has expired. Ask again.`:`The answer for "${G}" does not match the call the server made.`);let K;if(this.params.receipts&&Y==="approval"&&"approve"in Q&&Q.approve===!0){let B=this.params.receipts,z=JZ(this.config.name,{...this.claimsFor(J.toolCallId,G,Y,J.input),runId:H.runId}),D;try{D=await B.claim(z,H.expiresAt)}catch(L){return this.writeLog(`[gemi/ai] agent "${this.config.name}" could not claim a tool receipt`,{error:L}),V(`The approval for "${G}" could not be checked. Ask again.`)}if(D.status==="replay")return{...D.result,toolCallId:J.toolCallId,name:J.name};if(D.status==="blocked")return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"error",error:{code:"tool_error",message:`"${G}" 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:B,id:z,expiresAt:H.expiresAt}}if(!await this.spend(GZ,Q.signature))return await K?.store.release(K.id).catch((B)=>{this.writeLog(`[gemi/ai] agent "${this.config.name}" could not release a tool receipt`,{error:B})}),V(`The answer for "${G}" has already been used. Ask again.`);if("approve"in Q){if(Y!=="approval")return V(`"${G}" is answered by the client, not approved.`);if(Q.approve===!0){let B=this.amendCall($),z=this.executeTool(W,$.message.id,B,B.input,0);try{return await m(K?this.recordReceipt(K,z):z,this.controller.signal)}catch(D){if(D instanceof n)return Z.push(...D.pending),"open";throw D}}return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"denied",cause:"refused",reason:Q.reason}}if("output"in Q){if(Y==="approval")return V(`"${G}" is approved, not answered: the server produces its result.`);let B=W.tool.outputSchema,z=B?B.safeParse(Q.output):{ok:!0,value:Q.output};if(z.ok===!1)return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"error",error:{code:"invalid_tool_result",message:`The answer for "${G}" did not match its output schema: ${z.errors.join(", ")}`,toolCallId:J.toolCallId,retryable:!0}};return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"ok",output:z.value}}return V(`The answer for "${G}" carried neither an approval nor an output.`)}attachToHistory($,Q){let Z=this.amend($.message);Z.content.push(Q),this.unreported.add(Z),this.emit({type:"tool-result",messageId:Z.id,part:Q})}markFileRejected($,Q,Z){for(let V of this.history){if(!V.content.some((X)=>X.type==="file"&&X.fileId===$&&!X.providerRejected))continue;let H=this.produced.includes(V)?V:this.amend(V);if(H.content=H.content.map((X)=>X.type==="file"&&X.fileId===$&&!X.providerRejected?{...X,providerRejected:!0}:X),H!==this.current)this.unreported.add(H)}if(!this.config.logErrors)return;let J=`[gemi/ai] agent "${this.config.name}": the provider refused file ${$}${Z.status!==void 0?` (${Z.status})`:""}; it was left out of the request and will not be sent again: ${Q}`,G={agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},fileId:$,...Z},W=!1;try{D9.warning(J,G),W=!0}catch{}if(!W||Bun.env.NODE_ENV==="development")console.warn(J,G)}amend($){let Q=this.amended.get($.id);if(Q)return Q;let Z={...$,content:[...$.content]},J=this.history.indexOf($);if(J>=0)this.history[J]=Z;return this.produced.push(Z),this.amended.set($.id,Z),Z}async reportDeferred(){let $=[...this.unreported];this.unreported.clear();for(let Q of $)await this.report(Q)}async finalizeAborted(){if(this.nestedSettling.size>0)await Promise.all([...this.nestedSettling]);for(let Q of this.openCalls()){if(Q.message===this.current)continue;this.attachToHistory(Q,{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"denied",cause:"stopped",reason:this.stopReason})}await this.reportDeferred();let $=this.current;if($){let Q=new Set($.content.filter((Z)=>Z.type==="tool-result").map((Z)=>Z.toolCallId));for(let Z of[...$.content]){if(Z.type!=="tool-call"||Q.has(Z.toolCallId))continue;delete Z.partial,this.addResult($,{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 ${v$(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 xZ($){if($.answeredBy==="client")return $.inputSchema===u$?"question":"client";return $.requiresApproval?"approval":null}function IZ($){if(!$||!$.trim())return{};try{return JSON.parse($)}catch{return $}}class i$ extends yZ{name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await y.sweep({limit:100})===100);}}var r9=20;function uZ($,Q){if(Q<=0||$.length===0)return null;let Z=(W,V)=>V.createdAt-W.createdAt||(W.id<V.id?1:-1);return["<jobs>","Background jobs that tools started in this conversation, running ones first. A running job's result replaces its tool result when it finishes. Do not start the same work again while a job for it is running.",...[...$.filter((W)=>W.state==="running").sort(Z),...$.filter((W)=>W.state!=="running").sort(Z)].slice(0,Q).map((W)=>{let V=[`- ${W.id} (${W.toolName})`];if(W.state==="running")V.push(`running since ${n$(W.createdAt)}`);else if(W.state==="ok")V.push(`finished at ${n$(W.settledAt??W.updatedAt)}`);else{let Y=W.error?`${W.error.code}: ${gZ(W.error.message,200)}`:"failed";V.push(`failed at ${n$(W.settledAt??W.updatedAt)} (${Y})`)}if(W.summary!==void 0)V.push(`summary: ${gZ(JSON.stringify(W.summary),300)}`);if(W.orphaned)V.push("its tool call was lost when the turn that started it was cut short");return V.join("; ")}),"</jobs>"].join(`
|
|
20
|
+
`)}function n$($){return new Date($).toISOString().replace(/\.\d{3}Z$/,"Z")}function gZ($,Q){return $.length<=Q?$:`${$.slice(0,Q-1)}\u2026`}class s${table;sql;dialect;connection;constructor($,Q={}){let Z=Q.table??"gemi_agent_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Z))throw Error(`The agent jobs table name "${Z}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Z,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name}async createTable(){for(let $ of s8(this.dialect,this.table))await this.sql.unsafe($)}async transaction($){if(this.connection===void 0||this.joinable())return $();return dZ(this.sql,()=>$(),{connection:this.connection})}async create($){let Q=this.q(),Z=this.clock(Q);await Q`
|
|
21
|
+
INSERT INTO ${this.name(Q)}
|
|
22
|
+
(id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,
|
|
23
|
+
orphaned, attachment_scope, created_at, updated_at, deadline_at)
|
|
24
|
+
VALUES
|
|
25
|
+
(${$.id}, ${$.threadId}, ${$.runId}, ${$.toolCallId}, ${$.toolName},
|
|
26
|
+
${$.owner}, ${$.job}, ${e9($.summary)}, 'running', 0, ${$.attachmentScope},
|
|
27
|
+
${Z}, ${Z}, ${Z} + ${this.ms(Q,$.deadlineMs)})
|
|
28
|
+
`;let J=await this.get($.id);if(!J)throw Error(`The background job ${$.id} was not found after it was written.`);return J}async get($){let Q=this.q(),Z=await Q`SELECT * FROM ${this.name(Q)} WHERE id = ${$}`;return Z[0]?o$(Z[0]):null}async listForThread($,Q={}){let Z=this.q(),J=Q.states===void 0?Z`1 = 1`:Q.states.length===0?Z`1 = 0`:Z`state IN (${cZ(Z,Q.states)})`;return(Q.limit===void 0?await Z`
|
|
29
|
+
SELECT * FROM ${this.name(Z)}
|
|
30
|
+
WHERE thread_id = ${$} AND ${J}
|
|
31
|
+
ORDER BY created_at DESC, id DESC
|
|
32
|
+
`:await Z`
|
|
33
|
+
SELECT * FROM ${this.name(Z)}
|
|
34
|
+
WHERE thread_id = ${$} AND ${J}
|
|
35
|
+
ORDER BY created_at DESC, id DESC
|
|
36
|
+
LIMIT ${Math.max(0,Math.floor(Q.limit))}
|
|
37
|
+
`).map(o$)}async transition($,Q,Z){if(Q.length===0)return!1;let J=this.q(),G=this.clock(J),W=[J`updated_at = ${G}`];if(Z.state!==void 0)W.push(J`state = ${Z.state}`);if("output"in Z)W.push(J`output = ${e9(Z.output)}`);if("error"in Z)W.push(J`error = ${e9(Z.error)}`);if("usage"in Z)W.push(J`${this.column(J,"usage")} = ${e9(Z.usage)}`);if("orphaned"in Z)W.push(J`orphaned = ${Z.orphaned?1:0}`);if(Z.state!==void 0&&Z.state!=="running")W.push(Z.settledAt!==void 0?J`settled_at = COALESCE(settled_at, ${this.ms(J,Z.settledAt)})`:J`settled_at = COALESCE(settled_at, ${G})`);let V=W.reduce((H,X)=>J`${H}, ${X}`),Y=await J`
|
|
38
|
+
UPDATE ${this.name(J)} SET ${V}
|
|
39
|
+
WHERE id = ${$} AND state IN (${cZ(J,Q)})
|
|
40
|
+
`;return mZ(Y)>0}async overdue($,Q){let Z=this.q();return(await Z`
|
|
41
|
+
SELECT * FROM ${this.name(Z)}
|
|
42
|
+
WHERE state = 'running' AND deadline_at <= ${this.ms(Z,$)}
|
|
43
|
+
ORDER BY deadline_at, id
|
|
44
|
+
LIMIT ${Math.max(0,Math.floor(Q))}
|
|
45
|
+
`).map(o$)}async now(){let $=this.q(),[Q]=await $`SELECT ${this.clock($)} AS now`;return Number(Q.now)}async prune($){let Q=this.q(),Z=await Q`
|
|
46
|
+
DELETE FROM ${this.name(Q)}
|
|
47
|
+
WHERE state <> 'running' AND settled_at <= ${this.clock(Q)} - ${this.ms(Q,$)}
|
|
48
|
+
`;return mZ(Z)}joinable(){if(this.connection===void 0)return;let $=pZ();if($===void 0||lZ()!==this.connection)return;return $}q(){return this.joinable()??this.sql}column($,Q){let Z=this.dialect==="mysql"||this.dialect==="mariadb";return $.unsafe(Z?`\`${Q}\``:`"${Q}"`)}name($){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return $.unsafe(Q?`\`${this.table}\``:`"${this.table}"`)}clock($){switch(this.dialect){case"postgres":return $`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return $`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return $`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms($,Q){let Z=Math.max(0,Math.round(Q));return this.dialect==="mysql"||this.dialect==="mariadb"?$`CAST(${Z} AS SIGNED)`:$`CAST(${Z} AS BIGINT)`}}function cZ($,Q){return Q.map((Z)=>$`${Z}`).reduce((Z,J)=>$`${Z}, ${J}`)}function e9($){return $===void 0?null:JSON.stringify($)}function $$($){if($===null||$===void 0)return;return JSON.parse(String($))}function o$($){let Q=$$($.summary),Z=$$($.output),J=$$($.error),G=$$($.usage);return{id:String($.id),threadId:String($.thread_id),runId:String($.run_id),toolCallId:String($.tool_call_id),toolName:String($.tool_name),owner:$.owner===null||$.owner===void 0?null:String($.owner),job:$.job===null||$.job===void 0?null:String($.job),...Q!==void 0?{summary:Q}:{},state:String($.state),...Z!==void 0?{output:Z}:{},...J!==void 0?{error:J}:{},...G!==void 0?{usage:G}:{},...Number($.orphaned)===1?{orphaned:!0}:{},attachmentScope:$.attachment_scope===null||$.attachment_scope===void 0?null:String($.attachment_scope),createdAt:Number($.created_at),updatedAt:Number($.updated_at),deadlineAt:Number($.deadline_at),...$.settled_at===null||$.settled_at===void 0?{}:{settledAt:Number($.settled_at)}}}function mZ($){let Q=$;return Math.max(Number(Q.count??0),Number(Q.affectedRows??0))}function s8($,Q){if($==="mysql"||$==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Q}\` (
|
|
49
|
+
\`id\` VARCHAR(191) NOT NULL,
|
|
50
|
+
\`thread_id\` VARCHAR(191) NOT NULL,
|
|
51
|
+
\`run_id\` VARCHAR(191) NOT NULL,
|
|
52
|
+
\`tool_call_id\` VARCHAR(191) NOT NULL,
|
|
53
|
+
\`tool_name\` VARCHAR(191) NOT NULL,
|
|
54
|
+
\`owner\` VARCHAR(191) NULL,
|
|
55
|
+
\`job\` VARCHAR(191) NULL,
|
|
56
|
+
\`summary\` LONGTEXT NULL,
|
|
57
|
+
\`state\` VARCHAR(191) NOT NULL,
|
|
58
|
+
\`output\` LONGTEXT NULL,
|
|
59
|
+
\`error\` LONGTEXT NULL,
|
|
60
|
+
\`usage\` LONGTEXT NULL,
|
|
61
|
+
\`orphaned\` INTEGER NOT NULL DEFAULT 0,
|
|
62
|
+
\`attachment_scope\` VARCHAR(191) NULL,
|
|
63
|
+
\`created_at\` BIGINT NOT NULL,
|
|
64
|
+
\`updated_at\` BIGINT NOT NULL,
|
|
65
|
+
\`deadline_at\` BIGINT NOT NULL,
|
|
66
|
+
\`settled_at\` BIGINT NULL,
|
|
67
|
+
|
|
68
|
+
INDEX \`${Q}_thread_id_created_at_idx\`(\`thread_id\`, \`created_at\`),
|
|
69
|
+
INDEX \`${Q}_state_deadline_at_idx\`(\`state\`, \`deadline_at\`),
|
|
70
|
+
PRIMARY KEY (\`id\`)
|
|
71
|
+
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`];let Z=$==="sqlite"?'"id" TEXT NOT NULL PRIMARY KEY,':'"id" TEXT NOT NULL,',J=$==="sqlite"?"":`,
|
|
72
|
+
|
|
73
|
+
CONSTRAINT "${Q}_pkey" PRIMARY KEY ("id")`;return[`CREATE TABLE IF NOT EXISTS "${Q}" (
|
|
74
|
+
${Z}
|
|
75
|
+
"thread_id" TEXT NOT NULL,
|
|
76
|
+
"run_id" TEXT NOT NULL,
|
|
77
|
+
"tool_call_id" TEXT NOT NULL,
|
|
78
|
+
"tool_name" TEXT NOT NULL,
|
|
79
|
+
"owner" TEXT,
|
|
80
|
+
"job" TEXT,
|
|
81
|
+
"summary" TEXT,
|
|
82
|
+
"state" TEXT NOT NULL,
|
|
83
|
+
"output" TEXT,
|
|
84
|
+
"error" TEXT,
|
|
85
|
+
"usage" TEXT,
|
|
86
|
+
"orphaned" INTEGER NOT NULL DEFAULT 0,
|
|
87
|
+
"attachment_scope" TEXT,
|
|
88
|
+
"created_at" BIGINT NOT NULL,
|
|
89
|
+
"updated_at" BIGINT NOT NULL,
|
|
90
|
+
"deadline_at" BIGINT NOT NULL,
|
|
91
|
+
"settled_at" BIGINT${J}
|
|
92
|
+
)`,`CREATE INDEX IF NOT EXISTS "${Q}_thread_id_created_at_idx" ON "${Q}"("thread_id", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Q}_state_deadline_at_idx" ON "${Q}"("state", "deadline_at")`]}var t8=/^[A-Za-z0-9_-]{1,64}$/;function a8($,Q){let Z=r8(Q)?Q:{filter:Q},J=Z.deferred===!0,G=$.descriptors(Z.filter);if(!Z.namespaces)return G.map((K)=>t$($,K,J));let W=Object.entries(Z.namespaces),V=new Set($.descriptors().flatMap((K)=>K.tags));for(let[K,B]of W){if(!t8.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 B?.description!=="string"||B.description.trim()==="")throw Error(`toAgentTools: the namespace "${K}" needs a description. It is what the model reads to decide whether to look inside.`);if(!V.has(K))throw Error(`toAgentTools: no tool is tagged "${K}", so its namespace would be empty.`)}let Y=new Map(W.map(([K])=>[K,[]])),H=[];for(let K of G){let B=W.find(([z])=>K.tags.includes(z))?.[0];if(B===void 0)H.push(t$($,K,J));else Y.get(B).push(t$($,K,!1))}let X=[];for(let[K,B]of W){let z=Y.get(K);if(z.length===0)continue;X.push(G9.create({name:K,description:B.description,tools:z,deferred:B.deferred??J}))}return[...X,...H]}function r8($){return typeof $==="object"&&$!==null&&(("filter"in $)||("namespaces"in $)||("deferred"in $))}function t$($,Q,Z){return o.create({name:Q.name,description:Q.description,inputSchema:Q.inputSchema,...Q.outputSchema?{outputSchema:Q.outputSchema}:{},requiresApproval:Q.requiresApproval,deferred:Z,execute:(J,G)=>{let W=a9.getStore()?.req;if(!W)throw new S(`"${Q.name}" calls an api route as the user who started this run, and this run was not started inside a request. Run it from an AgentController, or give this agent tools that do not go through the MCP registry.`);return $.execute({kind:"local",req:W},Q.name,J,G)}})}function e8($){if($==="auto")return;let Q=/^(\d+)x(\d+)$/.exec($);if(!Q)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify($)}.`);let Z=Number(Q[1]),J=Number(Q[2]);if(Z%16!==0||J%16!==0)throw Error(`Image size ${$} is not supported: width and height must both be divisible by 16.`);if(Math.max(Z/J,J/Z)>3)throw Error(`Image size ${$} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function iZ($,Q){if($.size!==void 0)try{e8($.size)}catch(Z){throw Error(`${Q}: ${Z.message}`)}if($.background==="transparent"&&$.format==="jpeg")throw Error(`${Q}: a transparent background needs "png"; JPEG has no alpha channel.`);if($.compression!==void 0){let Z=$.compression;if(!Number.isInteger(Z)||Z<0||Z>100)throw Error(`${Q}: compression is an integer from 0 to 100; got ${Z}.`)}}function nZ($,Q){if($ instanceof File)return $;let Z=$.type||"image/png",J=Z==="image/jpeg"?"jpg":Z.split("/")[1]??"png";return new File([$],`${Q}.${J}`,{type:Z})}class a${name;provider;settings;constructor($){let{name:Q,provider:Z,...J}=$;iZ(J,`ImageModel "${Q}"`),this.name=Q,this.provider=Z,this.settings=J}static create($){return new a$($)}async generate($){let Q=this.merge($);return oZ(await this.provider.generate({prompt:$.prompt,...Q,signal:$.signal}))}async edit($){let Q=this.merge($);return oZ(await this.provider.edit({prompt:$.prompt,...Q,images:$.images.map((Z,J)=>nZ(Z,`image-${J}`)),...$.mask?{mask:nZ($.mask,"mask")}:{},signal:$.signal}))}merge($){let Q={...this.settings,...$.size!==void 0?{size:$.size}:{},...$.quality!==void 0?{quality:$.quality}:{},...$.background!==void 0?{background:$.background}:{},...$.format!==void 0?{format:$.format}:{},...$.compression!==void 0?{compression:$.compression}:{}};return iZ(Q,`ImageModel "${this.name}"`),Q}}function oZ($){return{image:new Blob([$.bytes],{type:$.mimeType}),mimeType:$.mimeType,size:$.size,usage:$.usage}}function s($){return typeof process>"u"?void 0:process.env?.[$]}var $0="preview";function sZ($){let Q=$.trim().replace(/\/+$/,"");if(!Q)return"";return`${Q.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function Q0($){return/^\d{4}-\d{2}-\d{2}/.test($)?"":"/v1"}function Q$($,Q={}){return{base:($.baseURL??s("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let J=$.apiKey??s("OPENAI_API_KEY");return{...J?{authorization:`Bearer ${J}`}:{},...$.headers}},timeoutMs:$.timeoutMs??Q.timeoutMs??120000,maxRetries:$.maxRetries??2}}function Z0($){let Q=$.baseURL??$.endpoint??s("AZURE_OPENAI_ENDPOINT");if(Q)return sZ(Q);let Z=$.resourceName??s("AZURE_OPENAI_RESOURCE_NAME")??s("AZURE_RESOURCE_NAME");return Z?sZ(`https://${Z.trim()}.cognitiveservices.azure.com`):""}function Z$($,Q={}){let Z=$.apiVersion??s("AZURE_OPENAI_API_VERSION")??$0;return{base:`${Z0($)}${Q0(Z)}`,query:`?api-version=${encodeURIComponent(Z)}`,headers:async()=>{if($.getToken)return{authorization:`Bearer ${await $.getToken()}`,...$.headers};let J=$.apiKey??s("AZURE_OPENAI_API_KEY");return{...J?{"api-key":J}:{},...$.headers}},timeoutMs:$.timeoutMs??Q.timeoutMs??120000,maxRetries:$.maxRetries??2}}var J0=500,aZ=20000;function G0($,Q){if(!$)return;let Z=$.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-Q)}function tZ($,Q){let Z=Math.min(aZ,J0*2**$);return Math.round(Z*(0.5+Q()*0.5))}function W0($){return $===429||$===408||$===409||$>=500}function V0($,Q){return W0($)&&I(Q).retryable}function rZ($){return $.reason??new DOMException("The operation was aborted.","AbortError")}function X0($,Q){return new Promise((Z,J)=>{let G=setTimeout(Z,$);Q?.addEventListener("abort",()=>{clearTimeout(G),J(rZ(Q))},{once:!0})})}async function S9($,Q,Z){let J=Z.fetchImpl??((K,B)=>fetch(K,B)),G=Z.sleep??X0,W=Z.random??Math.random,V=Z.now??Date.now,Y=Math.max(0,Z.maxRetries),H=async(K)=>{let B=Z.signal;if(!B)return await G(K);B.throwIfAborted();let z;try{await Promise.race([G(K,B),new Promise((D,L)=>{z=()=>L(rZ(B)),B.addEventListener("abort",z,{once:!0})})])}finally{if(z)B.removeEventListener("abort",z)}},X;for(let K=0;K<=Y;K++){Z.signal?.throwIfAborted();let B=new AbortController,z=()=>B.abort(Z.signal?.reason);Z.signal?.addEventListener("abort",z,{once:!0});let D=!1,L=Z.timeoutMs>0?setTimeout(()=>{D=!0,B.abort()},Z.timeoutMs):void 0,F;try{F=await J($,{...Q,signal:B.signal})}catch(_){if(L!==void 0)clearTimeout(L);if(Z.signal?.removeEventListener("abort",z),Z.signal?.aborted)throw _;if(X=D?new E9(Z.timeoutMs):_,D&&Z.retryTimeouts===!1)throw X;if(K===Y)throw X;await H(tZ(K,W));continue}if(L!==void 0)clearTimeout(L);if(F.ok)return F;Z.signal?.removeEventListener("abort",z);let U=await Y0(F),P=new g(F.status,U,F.headers.get("x-request-id")??void 0);if(K===Y||!V0(F.status,P))throw P;let q=G0(F.headers.get("retry-after"),V());await H(q===void 0?tZ(K,W):Math.min(q,aZ)),X=P}throw X??Error("Provider request failed with no response.")}async function Y0($){let Q;try{Q=await $.text()}catch{return null}try{return JSON.parse(Q)}catch{return Q}}var r$=300000;function e$($){return{generationsUrl:`${$.base}/images/generations${$.query}`,editsUrl:`${$.base}/images/edits${$.query}`,headers:$.headers,timeoutMs:$.timeoutMs,maxRetries:$.maxRetries}}class J$ extends Error{code;retryable;constructor($,Q={}){super($.message,Q);this.name="ImageRequestError",this.code=$.code,this.retryable=$.retryable}}var H0={png:"image/png",jpeg:"image/jpeg"};function K0($){let Q=Number($?.input_tokens??0),Z=Number($?.output_tokens??0),J={inputTokens:Q,outputTokens:Z,totalTokens:Number($?.total_tokens??Q+Z)},G=$?.input_tokens_details?.image_tokens;if(typeof G==="number")J.imageInputTokens=G;let W=$?.output_tokens_details?.image_tokens;if(typeof W==="number")J.imageOutputTokens=W;return J}function z0($){let Q=atob($),Z=new Uint8Array(Q.length);for(let J=0;J<Q.length;J++)Z[J]=Q.charCodeAt(J);return Z}function B0($){let Z=$?.data?.[0]?.b64_json;if(typeof Z!=="string"||Z.length===0)throw new J$({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let J=typeof $.output_format==="string"?$.output_format:"png";return{bytes:z0(Z),mimeType:H0[J]??`image/${J}`,size:typeof $.size==="string"?$.size:"",...typeof $.background==="string"?{background:$.background}:{},usage:K0($.usage)}}async function eZ($,Q,Z,J){let G;try{G=await S9($,Q,{maxRetries:Z.maxRetries,timeoutMs:Z.timeoutMs,retryTimeouts:!1,signal:J.signal,fetchImpl:Z.fetchImpl})}catch(W){if(J.signal?.aborted)throw W;throw new J$(I(W),{cause:W})}return B0(await G.json())}async function $6($,Q,Z={}){return await eZ($.generationsUrl,{method:"POST",headers:{...await $.headers(),"content-type":"application/json"},body:JSON.stringify(Q)},$,Z)}async function Q6($,Q,Z={}){return await eZ($.editsUrl,{method:"POST",headers:await $.headers(),body:Q},$,Z)}class G${static models(){return[]}modelName(){return this.model}async generate($){return await $6(this.endpoint(),this.body($),{signal:$.signal})}async edit($){let Q=new FormData;for(let[Z,J]of Object.entries(this.body($)))if(J!==void 0)Q.set(Z,String(J));for(let Z of $.images)Q.append("image[]",Z,Z.name);if($.mask)Q.set("mask",$.mask,$.mask.name);return await Q6(this.endpoint(),Q,{signal:$.signal})}body($){return{model:this.modelName(),prompt:$.prompt,...$.size?{size:$.size}:{},...$.quality?{quality:$.quality}:{},...$.background?{background:$.background}:{},...$.format?{output_format:$.format}:{},...$.compression!==void 0?{output_compression:$.compression}:{}}}normalizeError($){return I($)}}var Z6=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class $Q extends G${model;config;constructor($,Q={}){super();this.model=$,this.config=Q}static model($,Q){return new $Q($,Q)}static models(){return Z6}endpoint(){return e$(Q$(this.config,{timeoutMs:r$}))}}class QQ extends G${model;config;constructor($,Q={}){super();this.model=$,this.config=Q}static model($,Q){return new QQ($,Q)}static models(){return Z6}modelName(){return this.config.deployment??this.model}endpoint(){return e$(Z$(this.config,{timeoutMs:r$}))}}var W6=3;function ZQ($){let Q=new Map;for(let Z of $)for(let J of Z.content??[]){if(J.type!=="file"||!J.fileId||Q.has(J.fileId))continue;Q.set(J.fileId,{name:J.name,mimeType:J.mimeType})}return Q}function V6($,Q,Z=new Map){if(!(Q instanceof g))return[];if(Q.status!==400&&Q.status!==404)return[];let J=F0(Q.body);if(!J)return[];let G=D0($.input);if(G.length===0)return[];let W=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(J.param??"");if(W){let X=$.input[Number(W[1])],K=GQ(X)[Number(W[2])],B=K&&typeof K.file_id==="string"?K.file_id:void 0;if(B)return[B]}let V=J.message??"",Y=G6(G.map((X)=>X.fileId).filter((X)=>L0(V,X)));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(V);if(H){let X=H[1].toLowerCase()==="image type"?"input_image":"input_file",K=H[2].toLowerCase(),B=G6(G.filter((D)=>D.type===X).map((D)=>D.fileId)),z=B.filter((D)=>(Z.get(D)?.name??"").trim().toLowerCase().endsWith(`.${K}`));if(z.length===1)return z;if(z.length===0&&B.length===1)return B}return[]}function X6($,Q,Z=new Map){return{...$,input:$.input.map((J)=>{let G=GQ(J);if(!G.some((W)=>J6(W,Q)))return J;return{...J,content:G.map((W)=>J6(W,Q)?{type:"input_text",text:JQ(Z.get(String(W.file_id))?.name)}:W)}})}}function JQ($){return`[${$?`attachment ${JSON.stringify($)}`:"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 J6($,Q){return typeof $.file_id==="string"&&Q.has($.file_id)}function GQ($){let Q=$?.content;return Array.isArray(Q)?Q:[]}function D0($){let Q=[];for(let Z of $)for(let J of GQ(Z))if(typeof J.file_id==="string"&&J.file_id)Q.push({type:String(J.type),fileId:J.file_id});return Q}function F0($){if(!$||typeof $!=="object")return null;let Q=$,Z=Q.error&&typeof Q.error==="object"?Q.error:$;return{message:typeof Z.message==="string"?Z.message:void 0,param:typeof Z.param==="string"?Z.param:void 0}}function L0($,Q){let Z=Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${Z}($|[^A-Za-z0-9_-])`).test($)}function G6($){return[...new Set($)]}async function*U0($){let Q="",Z="",J=[],G,W=()=>{if(J.length===0&&!Z)return null;let H={event:Z,data:J.join(`
|
|
93
|
+
`),id:G};return Z="",J=[],G=void 0,H.data?H:null},V=(H)=>{let X=H.endsWith("\r")?H.slice(0,-1):H;if(X==="")return W();if(X.startsWith(":"))return null;let K=X.indexOf(":"),B=K===-1?X:X.slice(0,K),z=K===-1?"":X.slice(K+1);if(z.startsWith(" "))z=z.slice(1);if(B==="event")Z=z;else if(B==="data")J.push(z);else if(B==="id")G=z;return null};for await(let H of $){Q+=H;let X=Q.indexOf(`
|
|
94
|
+
`);while(X!==-1){let K=Q.slice(0,X);Q=Q.slice(X+1);let B=V(K);if(B)yield B;X=Q.indexOf(`
|
|
95
|
+
`)}}if(Q.length>0){let H=V(Q);if(H)yield H}let Y=W();if(Y)yield Y}async function*Y6($,Q={}){let Z=new Map,J=new Set,G,W=!1,V,Y=(H,X)=>({type:"finish",reason:H,usage:X,...V?{model:V}:{}});for await(let H of U0($)){if(H.data==="[DONE]")break;let X;try{X=JSON.parse(H.data)}catch{continue}let K=typeof X.type==="string"?X.type:H.event,B=X.response?.model;if(typeof B==="string"&&B)V=B;switch(K){case"response.output_text.delta":{let z=String(X.delta??"");if(!z)break;yield Q.structuredOutput?{type:"output-delta",delta:z}:{type:"text-delta",delta:z};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let z=String(X.delta??"");if(!z)break;yield{type:"reasoning-delta",delta:z,id:X.item_id};break}case"response.output_item.added":{let z=X.item;if(!z)break;if(z.type==="function_call"){let D=String(z.id??X.item_id??z.call_id??"");Z.set(D,{callId:String(z.call_id??D),name:String(z.name??""),namespace:typeof z.namespace==="string"&&z.namespace?z.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let z=Z.get(String(X.item_id??""));if(!z)break;let D=String(X.delta??"");if(!D)break;yield{type:"tool-call-delta",toolCallId:z.callId,name:z.name,argsDelta:D,...z.namespace?{namespace:z.namespace}:{}};break}case"response.function_call_arguments.done":{let z=String(X.item_id??""),D=Z.get(z);if(!D)break;D.done=!0,yield{type:"tool-call",toolCallId:D.callId,name:D.name,args:String(X.arguments??""),...D.namespace?{namespace:D.namespace}:{}};break}case"response.output_item.done":{let z=X.item;if(!z)break;if(z.type==="function_call"){let D=String(z.id??X.item_id??z.call_id??""),L=Z.get(D);if(L?.done)break;let F=(typeof z.namespace==="string"?z.namespace:"")||L?.namespace;if(yield{type:"tool-call",toolCallId:String(z.call_id??D),name:String(z.name??L?.name??""),args:String(z.arguments??""),...F?{namespace:F}:{}},L)L.done=!0;break}if(z.type==="tool_search_call"||z.type==="tool_search_output"){if(z.type==="tool_search_call"&&z.arguments!==void 0)G=z.arguments;let D=P0(z);if(D.loaded.length===0&&D.namespaces.length===0)break;let L=String(z.tool_search_call_id??z.id??"");if(J.has(L))break;J.add(L);let F=G;G=void 0,yield{type:"tool-search",...D,...F!==void 0&&F!==null?{arguments:F}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(X.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{W=!0,yield Y("stop",WQ(X.response?.usage));break}case"response.incomplete":{W=!0;let z=WQ(X.response?.usage),D=X.response?.incomplete_details?.reason;if(D==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:C0(X.response?.content_filters),retryable:!1}},yield Y("error",z);break}yield Y(D==="max_output_tokens"?"length":"stop",z);break}case"response.failed":case"error":{W=!0;let z=X.response?.error??X.error??X;yield{type:"error",error:O0(z)},yield Y("error",WQ(X.response?.usage));break}}if(W)return}if(!W)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield Y("error",W9())}function P0($){let Q=[],Z=[];return H6($.results??$.tools??$.loaded??$.output,Q,Z,0),{loaded:VQ(Q),namespaces:VQ(Z)}}function H6($,Q,Z,J){if(!Array.isArray($)||J>4)return;for(let G of $){if(typeof G==="string"){Q.push(G);continue}if(!G||typeof G!=="object")continue;let W=G,V=typeof W.name==="string"?W.name:typeof W.tool_name==="string"?W.tool_name:"",Y=W.tools??W.functions;if(Array.isArray(Y)){if(V)Z.push(V);H6(Y,Q,Z,J+1);continue}if(V)Q.push(V)}}function VQ($){return $.filter((Q,Z)=>$.indexOf(Q)===Z)}function C0($){if(!Array.isArray($))return"The provider's content filter blocked this request.";let Z=[];for(let J of $){if(!J||typeof J!=="object")continue;let G=J,W=G.content_filter_results;if(!W||typeof W!=="object")continue;for(let[V,Y]of Object.entries(W))if(Y&&typeof Y==="object"&&Y.filtered===!0)Z.push(`${V} (${String(G.source_type??"unknown")})`)}return Z.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${VQ(Z).join(", ")}.`}function O0($){let Q=typeof $?.message==="string"?$.message:"The provider stream failed.",Z=String($?.code??"").toLowerCase();if(Z==="rate_limit_exceeded")return{code:"rate_limited",message:Q,retryable:!0};if(Z==="context_length_exceeded")return{code:"context_length_exceeded",message:Q,retryable:!1};if(Z.includes("content_filter"))return{code:"content_filtered",message:Q,retryable:!1};return{code:"provider_error",message:Q,retryable:!0}}function W9(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function WQ($){if(!$)return W9();let Q=Number($.input_tokens??0),Z=Number($.output_tokens??0),J={inputTokens:Q,outputTokens:Z,totalTokens:Number($.total_tokens??Q+Z)},G=$.output_tokens_details?.reasoning_tokens;if(typeof G==="number")J.reasoningTokens=G;let W=$.input_tokens_details?.cached_tokens;if(typeof W==="number")J.cachedInputTokens=W;return J}async function*K6($){if(!$)return;let Q=$.getReader(),Z=new TextDecoder;try{while(!0){let{done:G,value:W}=await Q.read();if(G)break;if(W)yield Z.decode(W,{stream:!0})}let J=Z.decode();if(J)yield J}finally{Q.releaseLock()}}function XQ($){return{responsesUrl:`${$.base}/responses${$.query}`,filesUrl:`${$.base}/files${$.query}`,headers:$.headers,timeoutMs:$.timeoutMs,maxRetries:$.maxRetries}}async function*YQ($,Q,Z){let J,G=Q,W=new Set;for(let V=0;J===void 0;V++)try{J=await S9($.responsesUrl,{method:"POST",headers:{...await $.headers(),"content-type":"application/json"},body:JSON.stringify(G)},{maxRetries:$.maxRetries,timeoutMs:$.timeoutMs,signal:Z.signal,fetchImpl:$.fetchImpl})}catch(Y){let H=V<W6?V6(G,Y,Z.files).filter((K)=>!W.has(K)):[];if(H.length>0){let K=I(Y).message;for(let B of H)W.add(B),yield{type:"file-rejected",fileId:B,message:K,...b(Y)};G=X6(G,new Set(H),Z.files);continue}let X=I(Y);if(X.code!=="aborted")yield{type:"error",error:X,...b(Y)};yield{type:"finish",reason:X.code==="aborted"?"aborted":"error",usage:W9()};return}try{yield*Y6(K6(J.body),{structuredOutput:Z.structuredOutput})}catch(V){let Y=I(V);if(Y.code==="aborted"){yield{type:"finish",reason:"aborted",usage:W9()};return}yield{type:"error",error:Y},yield{type:"finish",reason:"error",usage:W9()}}}async function HQ($,Q,Z="user_data"){let J=new FormData;J.set("purpose",Z),J.set("file",Q);let W=await(await S9($.filesUrl,{method:"POST",headers:await $.headers(),body:J},{maxRetries:$.maxRetries,timeoutMs:$.timeoutMs,fetchImpl:$.fetchImpl})).json();if(!W?.id)throw Error("The provider accepted the upload but returned no file id.");return W.id}function KQ($){let Q=N0($);if(Q.startsWith("gpt-3.5")||Q.startsWith("text-")||Q.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Z=_0(Q);if(Z?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Z.major>1,toolSearch:z6(Z)};if(Z?.kind==="gpt")return{reasoning:Z.major>=5,structuredOutput:Z.major>4||Q.startsWith("gpt-4o")||Q.startsWith("gpt-4.1"),fileInput:Z.major>4||Q.startsWith("gpt-4o")||Q.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:z6(Z)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function z6($){if($.kind==="o")return $.major>=5;return $.major>5||$.major===5&&$.minor>=2}function N0($){return $.trim().toLowerCase()}function _0($){let Q=/^gpt-(\d+)(?:\.(\d+))?/.exec($);if(Q?.[1])return{kind:"gpt",major:Number(Q[1]),minor:Number(Q[2]??0)};let Z=/^o(\d+)(?:[-.]|$)/.exec($);if(Z?.[1])return{kind:"o",major:Number(Z[1]),minor:0};return null}function BQ($,Q){let{capabilities:Z}=Q,J={model:Q.model,input:q0($.messages,Z,$.tools),stream:!0};if($.systemPrompt)J.instructions=$.systemPrompt;let G=I0($.tools,Z);if(G.length>0){if(J.tools=G,!Z.parallelToolCalls)J.parallel_tool_calls=!1}if($.output)J.text={format:{type:"json_schema",name:$.output.name,schema:$.output.schema,strict:$.output.strict}};if($.reasoning&&Z.reasoning)J.reasoning=$.reasoning==="none"?{effort:"none"}:{effort:$.reasoning,summary:"auto"};if(typeof $.temperature==="number")J.temperature=$.temperature;if(typeof $.maxOutputTokens==="number")J.max_output_tokens=$.maxOutputTokens;return J}function q0($,Q,Z){let J=[],G=new Map;if(Q.toolSearch){for(let W of Z??[])if(W$(W))G.set(W.name,W)}for(let W of $){let V=W.role,Y=[],H=()=>{if(Y.length===0)return;J.push({type:"message",role:V,content:Y}),Y=[]};for(let X of W.content??[])switch(X.type){case"text":{if(!X.text)break;Y.push(V9(V,X.text));break}case"output":{if(X.partial)break;Y.push(V9(V,JSON.stringify(X.value)));break}case"file":{if(V==="assistant")break;let K=j0(X);if(!Q.fileInput){if(K)Y.push(V9(V,zQ(X,!1)));break}if(X.fileId?.startsWith(h))throw Error(`FilePart.fileId holds a gemi attachment id (${X.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!X.fileId&&!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(X.providerRejected){if(K)Y.push(V9(V,zQ(X,!1)));Y.push(V9(V,JQ(X.name)));break}if(K)Y.push(V9(V,zQ(X,!!X.fileId)));if(X.fileId)Y.push(S0(X));break}case"reasoning":{H();let K=k0(X);if(K)J.push(K);break}case"tool-call":{if(X.partial)break;if(H(),Q.toolSearch&&Array.isArray(X.toolSearches))for(let B of X.toolSearches)J.push(...x0(B,Z??[]));let K={type:"function_call",call_id:X.toolCallId,name:String(X.name),arguments:JSON.stringify(X.input??{})};if(X.namespace&&G.has(X.namespace))K.namespace=X.namespace;J.push(K);break}case"tool-result":{H(),J.push({type:"function_call_output",call_id:X.toolCallId,output:E0(X)});break}}H()}return R0(J)}var M0="No result was recorded for this tool call. Assume it did not complete.";function R0($){let Q=new Set,Z=new Set,J=[];for(let W of $){if(W.type==="function_call"){let V=String(W.call_id);if(Q.has(V))continue;Q.add(V)}else if(W.type==="function_call_output"){let V=String(W.call_id);if(!Q.has(V)||Z.has(V))continue;Z.add(V)}J.push(W)}if(Z.size===Q.size)return J;let G=[];for(let W of J){if(G.push(W),W.type!=="function_call")continue;let V=String(W.call_id);if(Z.has(V))continue;Z.add(V),G.push({type:"function_call_output",call_id:V,output:M0})}return G}function V9($,Q){return{type:$==="assistant"?"output_text":"input_text",text:Q}}function j0($){let Q=$.attachmentId;return typeof Q==="string"&&Q.startsWith(h)?Q:void 0}function zQ($,Q){let Z=[`id=${JSON.stringify($.attachmentId)}`];if($.name)Z.push(`name=${JSON.stringify($.name)}`);if($.mimeType)Z.push(`mimeType=${JSON.stringify($.mimeType)}`);let J=`attachment ${Z.join(" ")}`;return Q?`[${J}]`:`[${J} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function S0($){let Q=$.mimeType?.trim().toLowerCase()??"";return{type:(Q?Q.startsWith("image/")&&Q!=="image/svg+xml":A0($.name))?"input_image":"input_file",file_id:$.fileId}}function A0($){let Q=/\.([a-z0-9]+)$/.exec($?.trim().toLowerCase()??"");return Q?.[1]!==void 0&&T0.has(Q[1])}var T0=new Set(["jpeg","jpg","png","gif","webp"]);function k0($){if(!$.id)return null;let Q={type:"reasoning",id:$.id};return Q.summary=$.text?[{type:"summary_text",text:$.text}]:[],Q}function E0($){if($.status==="ok")return typeof $.output==="string"?$.output:JSON.stringify($.output??null);if($.status==="running"){let Q=$.job?.summary===void 0?"":` Started with: ${JSON.stringify($.job.summary)}.`;return`Started background job ${$.job?.id??"(unknown)"}. It is still running, so there is no result yet: this message will be replaced by the result when it finishes. Do not start it again.${Q}`}if($.status==="denied"){let Q=$.reason?` Reason given: ${$.reason}`:"";if($.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${Q}`;if($.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${Q}`;return`The user declined this tool call, so it did not run.${Q}`}return`The tool call failed and produced no result. Error (${$.error?.code??"unknown"}): ${$.error?.message??"no message"}`}function x0($,Q){let Z=new Set(B6($?.loaded)),J=B6($?.namespaces),G=new Set(J),W=[];for(let Y of Q)if(W$(Y)){if(!G.has(Y.name))continue;let H=Y.tools.filter((X)=>Z.size===0||Z.has(X.name));if(H.length===0)continue;W.push({type:"namespace",name:Y.name,description:Y.description,tools:H.map((X)=>X9(X,!0))})}else if(Y.deferred&&Z.has(Y.name))W.push(X9(Y,!0));if(W.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:$.arguments&&typeof $.arguments==="object"?$.arguments:{paths:J.length>0?J:[...Z]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:W}]}function B6($){return Array.isArray($)?$.filter((Q)=>typeof Q==="string"):[]}function W$($){return Array.isArray($.tools)}function I0($,Q){if(!$||$.length===0)return[];if(!Q.toolSearch){let G=[];for(let W of $)if(W$(W))for(let V of W.tools)G.push(X9(V,!1));else G.push(X9(W,!1));return G}let Z=[],J=!1;for(let G of $)if(W$(G)){let W=G.tools.map((V)=>{if(V.deferred)J=!0;return X9(V,!0)});Z.push({type:"namespace",name:G.name,description:G.description,tools:W})}else{if(G.deferred)J=!0;Z.push(X9(G,!0))}if(J)Z.push({type:"tool_search"});return Z}function X9($,Q){let Z={type:"function",name:$.name,description:$.description,parameters:$.parameters,strict:$.strict};if(Q&&$.deferred)Z.defer_loading=!0;return Z}class Y9{static models(){return[]}normalizeError($){return I($)}}var D6=["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 DQ extends Y9{model;capabilities;config;constructor($,Q={}){super();this.model=$,this.capabilities=KQ($),this.config=Q}static model($,Q){return new DQ($,Q)}static models(){return D6}stream($){let Q=BQ($,{model:this.model,capabilities:this.capabilities});return YQ(this.endpoint(),Q,{signal:$.signal,structuredOutput:Boolean($.output),files:ZQ($.messages)})}upload($){return HQ(this.endpoint(),$)}endpoint(){return XQ(Q$(this.config))}}class FQ extends Y9{model;capabilities;config;constructor($,Q={}){super();this.model=$,this.capabilities=KQ($),this.config=Q}static model($,Q){return new FQ($,Q)}static models(){return D6}stream($){let Q=BQ($,{model:this.deployment(),capabilities:this.capabilities});return YQ(this.endpoint(),Q,{signal:$.signal,structuredOutput:Boolean($.output),files:ZQ($.messages)})}upload($){return HQ(this.endpoint(),$,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return XQ(Z$(this.config))}}class V${now;entries=new Map;constructor($=Date.now){this.now=$}allow($,Q){let Z=this.entries.get($);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+Q.cooldownMs,!0}record($,Q,Z){let J=this.entries.get($)??{failures:0},G=J.openUntil!==void 0;if(Q==="success")return this.entries.delete($),G?"closed":void 0;if(Q==="none"){delete J.probeUntil;return}if(J.failures+=1,this.entries.set($,J),G||J.failures>=Z.failures)return J.openUntil=this.now()+Z.cooldownMs,delete J.probeUntil,G?void 0:"open";return}state($){let Q=this.entries.get($);if(Q?.openUntil===void 0)return"closed";return this.now()<Q.openUntil?"open":"half-open"}}function w0($){switch($.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 F6=Symbol("timed-out");class A9 extends Y9{model;capabilities;entries;options;circuit;constructor($,Q={}){super();if($.length===0)throw Error("FallbackProvider needs at least one provider.");for(let J of $)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=[...$];let Z=Q.circuit;if(Z){let J=Z.failures??3,G=Z.cooldownMs??30000;if(!Number.isInteger(J)||J<1)throw Error(`FallbackProvider: circuit.failures must be a positive integer, got ${J}.`);if(!(G>0))throw Error(`FallbackProvider: circuit.cooldownMs must be a positive number, got ${G}.`);let W=new Set;for(let Y of $){let H=LQ(Y);if(W.has(H))throw Error(`FallbackProvider: two legs share the circuit key "${H}". Give one of them a \`circuitKey\`.`);W.add(H)}let V=Z.store??new V$;this.options={...Q,circuit:{...Z,store:V}},this.circuit={policy:{failures:J,cooldownMs:G},store:V,...Z.onStateChange?{onStateChange:Z.onStateChange}:{}}}else this.options=Q,this.circuit=void 0;this.model=$[0].provider.model,this.capabilities=b0($.map((J)=>J.provider.capabilities))}static chain($,Q){return new A9($,Q)}from($){if(!Number.isInteger($)||$<0||$>=this.entries.length)throw RangeError(`FallbackProvider.from(${$}): the chain has ${this.entries.length} entries.`);return new A9(this.entries.slice($),this.options)}leg($){let Q=this.from($).entries[0];return new A9([Q],this.options)}upload($){return this.entries[0].provider.upload($)}normalizeError($){return this.entries[0].provider.normalizeError($)}stream($){return this.run($)}async*run($){let Q,Z=$.signal,J=0;for(let G=0;G<this.entries.length;G++){let W=this.entries[G],V=G===this.entries.length-1,Y=W.provider.model;if(this.circuit&&!V&&!await this.allow(W))continue;J+=1;let H=!1,X=async(C)=>{if(H)return;H=!0,await this.record(G,W,C)},K=new AbortController,B=()=>K.abort(Z?.reason);if(Z?.aborted)K.abort(Z.reason);else Z?.addEventListener("abort",B,{once:!0});let z=[],D=!1,L=!1,F,U,P,q=!1,_,N=!1,A=(C)=>{let T=Q?M(M(R(),Q),C.usage):C.usage;return Q=void 0,{...C,usage:T}};try{_=W.provider.stream({...$,...W.reasoning!==void 0?{reasoning:W.reasoning}:{},signal:K.signal})[Symbol.asyncIterator]();let C=!0;for(;;){let T=C&&W.timeoutMs!==void 0?await f0(_.next(),W.timeoutMs):await _.next();if(T===F6){q=!0,P={error:{code:"provider_error",message:`${Y} sent nothing within ${W.timeoutMs}ms.`,retryable:!0}};break}if(C=!1,T.done){N=!0;break}let j=T.value;if(j.type==="finish"&&j.model)U=j.model;if(D){if(j.type==="finish")F=M(F??R(),j.usage),L=!0,yield A(j);else{if(j.type==="error")P={error:j.error};yield j}continue}if(w0(j)){D=!0,await X("success"),yield*z.splice(0),yield j;continue}if(j.type==="error")P={error:j.error,...j.status!==void 0?{status:j.status}:{},...j.requestId!==void 0?{requestId:j.requestId}:{}};else if(j.type==="finish"){if(F=M(F??R(),j.usage),j.reason==="error"&&!P)P={error:{code:"provider_error",message:`${Y} ended the call with an error and did not say which.`,retryable:!1}}}z.push(j)}}catch(C){let T=W.provider.normalizeError(C);if(D){if(T.code!=="aborted")yield{type:"error",error:T,...b(C)};this.report({index:G,model:Y,responseModel:U,attempt:J,usage:F,outcome:UQ(T),error:T}),yield A({type:"finish",reason:T.code==="aborted"?"aborted":"error",usage:R(),...U?{model:U}:{}});return}P={error:T,...b(C)}}finally{if(Z?.removeEventListener("abort",B),!N)K.abort(),_?.return?.()?.catch(()=>{})}if(D){if(!L&&Q)yield{type:"finish",reason:P?"error":"stop",usage:Q},Q=void 0;this.report({index:G,model:Y,responseModel:U,attempt:J,usage:F,outcome:P?UQ(P.error):"ok",...P?{error:P.error}:{}});return}if(Z?.aborted){await X("none"),this.report({index:G,model:Y,responseModel:U,attempt:J,usage:F,outcome:"aborted"}),yield A({type:"finish",reason:"aborted",usage:F??R(),...U?{model:U}:{}});return}if(!P){await X("success"),this.report({index:G,model:Y,responseModel:U,attempt:J,usage:F,outcome:"ok"});for(let C of z)yield C.type==="finish"?A(C):C;return}let E=!V&&P.error.code!=="aborted"&&this.shouldFallBack(P.error,{index:G,model:Y,timedOut:q,...P.status!==void 0?{status:P.status}:{},...P.requestId!==void 0?{requestId:P.requestId}:{}});if(await X(E?"failure":"none"),this.report({index:G,model:Y,responseModel:U,attempt:J,usage:F,outcome:E?"fallback":UQ(P.error),error:P.error}),E){if(F)Q=M(Q??R(),F);continue}let x=!1,O;for(let C of z){if(C.type==="finish"){O=C;continue}if(C.type==="error")x=!0;yield C}if(!x&&P.error.code!=="aborted")yield{type:"error",error:P.error,...P.status!==void 0?{status:P.status}:{},...P.requestId!==void 0?{requestId:P.requestId}:{}};yield A({type:"finish",reason:P.error.code==="aborted"?"aborted":O?.reason??"error",usage:F??R(),...U?{model:U}:{}});return}}async allow($){if(!this.circuit)return!0;try{return await this.circuit.store.allow(LQ($),this.circuit.policy)}catch{return!0}}async record($,Q,Z){if(!this.circuit)return;let J=LQ(Q),G;try{G=await this.circuit.store.record(J,Z,this.circuit.policy)}catch{return}if(!G)return;try{this.circuit.onStateChange?.({index:$,model:Q.provider.model,key:J,state:G})}catch{}}shouldFallBack($,Q){let Z=this.options.fallbackOn??((J)=>J.retryable);try{return Z($,Q)}catch{return!1}}report($){if($.usage===void 0)delete $.usage;if($.responseModel===void 0)delete $.responseModel;try{this.options.onUsage?.($)}catch{}}}function LQ($){return $.circuitKey??$.provider.model}function UQ($){return $.code==="aborted"?"aborted":"failed"}function b0($){return{reasoning:$.every((Q)=>Q.reasoning),structuredOutput:$.every((Q)=>Q.structuredOutput),fileInput:$.every((Q)=>Q.fileInput),parallelToolCalls:$.every((Q)=>Q.parallelToolCalls),toolSearch:$.every((Q)=>Q.toolSearch)}}function f0($,Q){let Z,J=new Promise((G)=>{Z=setTimeout(()=>G(F6),Q)});return Promise.race([$,J]).finally(()=>clearTimeout(Z))}async function v0($,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 G=[];for(let W=0;W<$.entries.length;W++){let V=$.leg(W),Y={index:W,model:V.model,results:[],errors:[]};for(let H=0;H<J;H++)try{Y.results.push(await Q(V,{index:W,sample:H}))}catch(X){Y.errors.push({sample:H,error:X})}G.push(Y)}return G}class H9 extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor($,Q,Z){super(`Frame ${Q} of run ${$} has been evicted; the oldest frame still buffered is ${Z}. Reload the thread instead of resuming.`);this.runId=$;this.requested=Q;this.oldest=Z}}class T9 extends Error{runId;code="live_run_not_found";constructor($){super(`No live run ${$} in this process.`);this.runId=$}}class X${ttlMs;maxFrames;maxAgeMs;runs=new Map;byThread=new Map;byClientRun=new Map;constructor($={}){this.ttlMs=$.ttlMs??60000,this.maxFrames=$.maxFrames??4096,this.maxAgeMs=$.maxAgeMs===void 0?3600000:$.maxAgeMs}register($,Q={}){let Z={run:$,threadId:Q.threadId,owner:Q.owner??null,clientRunId:Q.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evicted:!1,evictAt:null,expireAt:null,wake:new Set,version:0};if(this.runs.set($.runId,Z),Q.threadId)this.byThread.set(Q.threadId,$.runId);if(Q.clientRunId)this.byClientRun.set(Q.clientRunId,$.runId);return this.scheduleExpiry(Z,Q.maxRunDurationMs),this.pump(Z,Q)}findByClientRunId($){let Q=this.byClientRun.get($);return Q&&this.runs.has(Q)?Q:null}async find($){let Q=this.byThread.get($.threadId);if(!Q)return null;let Z=this.runs.get(Q);if(!Z)return null;return{runId:Q,seq:Z.lastSeq}}get($){return this.runs.get($)?.run??null}ownerOf($){return this.runs.get($)?.owner??null}mayAccess($,Q){let Z=this.ownerOf($);return Z===null||Z===Q}isRunning($){let Q=this.runs.get($);return!!Q&&!Q.ended&&!Q.evicted}replay($,Q){let Z=this.runs.get($);if(!Z)throw new T9($);if(Q!==void 0&&Q<Z.lostBefore)throw new H9($,Q,Z.lostBefore);let J=Z.frames[0]?.seq;return this.drain(Z,$,Q??J??Z.lastSeq+1)}clear(){for(let $ of this.runs.values()){if($.evictAt)clearTimeout($.evictAt);if($.expireAt)clearTimeout($.expireAt);$.ended=!0,this.notify($)}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 $.run.frames()){if($.evicted){let W=Q.onEvent;if(W)Z=Z.then(()=>W(J.event)).catch((V)=>PQ(Q,V));continue}if($.frames.push(J),$.lastSeq=J.seq,$.frames.length>this.maxFrames){let W=$.frames.shift();if(W)$.lostBefore=W.seq+1}this.notify($);let G=Q.onEvent;if(G)Z=Z.then(()=>G(J.event)).catch((W)=>PQ(Q,W))}}catch(J){PQ(Q,J)}finally{if($.ended=!0,$.expireAt)clearTimeout($.expireAt),$.expireAt=null;this.notify($),this.scheduleEviction($),await Z}}async*drain($,Q,Z){let J=Z;while(!0){let G=$.version;for(;;){if(J<$.lostBefore)throw new H9(Q,J,$.lostBefore);let W=$.frames,V=W[0]?.seq;if(V===void 0)break;let Y=Math.max(0,J-V);if(Y>=W.length)break;let H=W[Y];yield H,J=H.seq+1}if($.ended&&J>$.lastSeq||$.evicted)return;await this.wait($,G)}}wait($,Q){if($.version!==Q)return Promise.resolve();return new Promise((Z)=>$.wake.add(Z))}notify($){$.version++;let Q=Array.from($.wake);$.wake.clear();for(let Z of Q)Z()}scheduleEviction($){if($.evictAt)return;let Q=setTimeout(()=>{let Z=$.run.runId;if(!$.ended)$.evicted=!0,$.frames=[];if(this.runs.get(Z)===$)this.runs.delete(Z);if($.threadId&&this.byThread.get($.threadId)===Z)this.byThread.delete($.threadId);if($.clientRunId&&this.byClientRun.get($.clientRunId)===Z)this.byClientRun.delete($.clientRunId);this.notify($)},this.ttlMs);Q.unref?.(),$.evictAt=Q}scheduleExpiry($,Q){if(this.maxAgeMs===null||Q===null)return;let Z=Q===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,Q+this.ttlMs);if(!Number.isFinite(Z)||Z>2147483647)return;let J=setTimeout(()=>{if($.expireAt=null,$.ended)return;try{$.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($)},Z);J.unref?.(),$.expireAt=J}}var CQ=new X$;function PQ($,Q){try{$.onInternalError?.(Q)}catch{}}class Y${maxEntries;records=new Map;constructor($=1e5){this.maxEntries=$}async record($,Q){if(this.records.has($))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($){let Q=this.records.get($);return Q?{...Q}:null}}var OQ=new Y$;class _Q{now;receipts=new Map;sweepAt=1024;constructor($=Date.now){this.now=$}async claim($,Q){let Z=this.now();if(this.receipts.size>=this.sweepAt)this.sweep(Z);let J=this.receipts.get($);if(J&&J.expiresAt>Z)return J.result?{status:"replay",result:structuredClone(J.result)}:{status:"blocked"};return this.receipts.set($,{expiresAt:Q}),{status:"claimed"}}async complete($,Q,Z){this.receipts.set($,{result:structuredClone(Q),expiresAt:Z})}async release($){let Q=this.receipts.get($);if(Q&&!Q.result)this.receipts.delete($)}get size(){return this.receipts.size}sweep($){for(let[Q,Z]of this.receipts)if(Z.expiresAt<=$)this.receipts.delete(Q);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var L6="pending",NQ="done:",h0=`
|
|
19
96
|
if redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2], 'NX') then return 'claimed' end
|
|
20
97
|
local held = redis.call('GET', KEYS[1])
|
|
21
98
|
if not held then return ARGV[1] end
|
|
22
|
-
return held`,
|
|
99
|
+
return held`,y0=`
|
|
23
100
|
if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end
|
|
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};
|
|
101
|
+
return 0`;class qQ{injectedClient;prefix;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:ai:receipt"}async claim($,Q){let Z=await this.client.send("EVAL",[h0,"1",this.key($),L6,U6(Q)]);if(Z==="claimed")return{status:"claimed"};let J=String(Z??"");if(J.startsWith(NQ))return{status:"replay",result:JSON.parse(J.slice(NQ.length))};return{status:"blocked"}}async complete($,Q,Z){await this.client.send("SET",[this.key($),NQ+JSON.stringify(Q),"PX",U6(Z)])}async release($){await this.client.send("EVAL",[y0,"1",this.key($),L6])}key($){return`${this.prefix}:${$}`}get client(){if(this.injectedClient)return this.injectedClient;let $=$9(),Q=$.bound(Q9)?$.make(Q9).client:void 0;if(!Q)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return Q}}function U6($){return String(Math.max(1,Math.ceil($-Date.now())))}var g0=86400000,u0=60000;class H${ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor($={}){this.ttlMs=$.ttlMs??g0,this.clientOwnedIds=$.clientOwnedIds??!1}async createThread($){let Q=crypto.randomUUID();return this.threads.set(Q,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:Q}}async loadThread($){this.sweep();let Q=this.threads.get($);if(!Q)return this.clientOwnedIds?[]:null;return Q.touchedAt=Date.now(),Q.messages.slice()}async appendMessages($,Q){this.sweep();let Z=this.threads.get($);if(!Z){if(!this.clientOwnedIds)throw Error(`Thread ${$} does not exist here, or has expired.`);Z={messages:[],touchedAt:Date.now()},this.threads.set($,Z)}for(let J of Q){let G=Z.messages.findIndex((W)=>W.id===J.id);if(G===-1)Z.messages.push(J);else Z.messages[G]=J}Z.touchedAt=Date.now()}async removeMessages($,Q){this.sweep();let Z=this.threads.get($);if(!Z)return;let J=new Set(Q);Z.messages=Z.messages.filter((G)=>!J.has(G.id)),Z.touchedAt=Date.now()}async loadSummaries($){return this.threads.get($)?.summaries?.slice()??[]}async saveSummary($,Q){let Z=this.threads.get($);if(!Z)return;Z.summaries=n9(Z.summaries??[],Q)}delete($){this.threads.delete($)}get size(){return this.threads.size}sweep($=Date.now()){if($-this.lastSweep<u0)return;this.lastSweep=$;for(let[Q,Z]of this.threads)if($-Z.touchedAt>this.ttlMs)this.threads.delete(Q)}}var MQ=new H$;function N6($={}){return{messages:$.messages?[...$.messages]:[],pending:$.pending?[...$.pending]:[],error:null,threadId:$.threadId,seq:$.seq??-1,cursorRunId:$.cursorRunId,runMessageIds:[],loadedTools:[]}}function _6($,Q,Z=new Date().toISOString()){if(!(Q.event.type==="run-start"&&Q.event.runId!==$.cursorRunId)&&Q.seq<=$.seq)return $;return{...q6($,Q.event,Z),seq:Q.seq}}function q6($,Q,Z){switch(Q.type){case"run-start":return{...$,messages:c0($.messages,Q.runId),runId:Q.runId,cursorRunId:Q.runId,threadId:Q.threadId??$.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return t($,Q.messageId,Z,(J)=>({...J,role:Q.role}));case"text-delta":if(C6($,Q.messageId))return $;return t($,Q.messageId,Z,(J)=>({...J,content:i0(J.content,Q.delta)}));case"reasoning-delta":if(C6($,Q.messageId))return $;return t($,Q.messageId,Z,(J)=>({...J,content:n0(J.content,Q.delta,Q.id)}));case"output-delta":return t($,Q.messageId,Z,(J)=>({...J,content:O6(J.content,{type:"output",value:Q.snapshot,partial:!0},(G)=>G.type==="output")}));case"tool-call":return t($,Q.messageId,Z,(J)=>{let G=J.content.findIndex((B)=>B.type==="tool-call"&&B.toolCallId===Q.part.toolCallId),W=G===-1?void 0:J.content[G],V=Q.part.progress??W?.progress,Y=Q.part.nested??W?.nested,H=Q.part.attachments??W?.attachments,X={...Q.part,...V?{progress:V}:{},...Y?{nested:Y}:{},...H?{attachments:H}:{}},K=J.content.slice();if(G===-1)K.push(X);else K[G]=X;return{...J,content:K}});case"tool-search":{let J=Q.loaded.filter((G)=>!$.loadedTools.includes(G));if(J.length===0)return $;return{...$,loadedTools:[...$.loadedTools,...J]}}case"tool-progress":return P6($,Q.toolCallId,(J)=>({...J,progress:[...J.progress??[],Q.data]}));case"nested-event":{let J=Q;return P6($,Q.toolCallId,(G)=>{let W=G.nested??[],V=W.findIndex((K)=>K.runId===J.runId),Y=W[V]??{runId:J.runId,agent:J.agent,messages:[]},H=l0(Y,J,Z),X=V===-1?[...W,H]:W.map((K,B)=>B===V?H:K);return{...G,nested:X}})}case"tool-result":{let J=t($,Q.messageId,Z,(G)=>({...G,content:O6(G.content,Q.part,(W)=>W.type==="tool-result"&&W.toolCallId===Q.part.toolCallId)}));return{...J,pending:J.pending.filter((G)=>G.toolCallId!==Q.part.toolCallId)}}case"message":{let J=$.messages.findIndex((V)=>V.id===Q.message.id),G=$.messages.slice();if(J===-1)G.push(Q.message);else G[J]=Q.message;let W=$.runMessageIds.includes(Q.message.id)?$.runMessageIds:[...$.runMessageIds,Q.message.id];return{...$,messages:G,runMessageIds:W}}case"message-id":{let J=$.messages.findIndex((W)=>W.id===Q.localId);if(J===-1){if(!Q.message||$.messages.some((W)=>W.id===Q.messageId))return $;return{...$,messages:[...$.messages,Q.message]}}let G=$.messages.some((W)=>W.id===Q.messageId)?$.messages.filter((W,V)=>V!==J):$.messages.map((W,V)=>V===J?{...W,id:Q.messageId}:W);return{...$,messages:G}}case"awaiting-input":return{...$,runId:Q.runId,pending:[...Q.pending]};case"message-end":return t($,Q.messageId,Z,(J)=>({...J,finishReason:Q.finishReason,...Q.outputTruncated?{outputTruncated:!0}:{},...Q.usage?{usage:Q.usage}:{},content:Q.outputTruncated||Q.finishReason==="length"?J.content.filter((G)=>!(G.type==="output"&&G.partial)):J.content.map((G)=>G.type==="output"&&G.partial?{...G,partial:!1}:G)}));case"usage":return{...$,usage:Q.usage};case"error":return{...$,error:Q.error,pending:[]};case"run-end":return{...$,runId:void 0,finishReason:Q.finishReason,messages:M6($,Q.finishReason)};default:return $}}function c0($,Q){if(!$.some((Z)=>Z.runId===Q&&Z.finishReason===void 0))return $;return $.map((Z)=>{if(Z.runId!==Q||Z.finishReason!==void 0)return Z;let{runId:J,...G}=Z;return{...G,content:[]}})}function M6($,Q){return $.messages.map((Z)=>Z.role==="assistant"&&$.runMessageIds.includes(Z.id)?m0(Z,Q):Z)}function m0($,Q){let Z=$.content.map((G)=>G.type==="tool-call"&&G.nested?.some((W)=>W.finishReason===void 0)?{...G,nested:G.nested.map((W)=>W.finishReason===void 0?p0(W,Q):W)}:G);if($.finishReason===void 0)return{...$,finishReason:Q,content:Z};return Z.some((G,W)=>G!==$.content[W])?{...$,content:Z}:$}function p0($,Q){let Z={messages:$.messages,pending:[],error:null,seq:-1,runMessageIds:$.messages.map((J)=>J.id),loadedTools:[]};return{...$,finishReason:Q,messages:M6(Z,Q)}}function P6($,Q,Z){for(let J=$.messages.length-1;J>=0;J--){let G=$.messages[J],W=G.content.findIndex((X)=>X.type==="tool-call"&&X.toolCallId===Q);if(W===-1)continue;if(G.finishReason!==void 0&&!d0($,G,Q))return $;let V=G.content.slice();V[W]=Z(V[W]);let Y=$.messages.slice();Y[J]={...G,content:V};let H=$.runMessageIds.includes(G.id)?$.runMessageIds:[...$.runMessageIds,G.id];return{...$,runMessageIds:H,messages:Y}}return $}function l0($,Q,Z){let J={messages:$.messages,pending:[],error:null,seq:-1,runMessageIds:$.messages.map((W)=>W.id),loadedTools:[],finishReason:$.finishReason},G=q6(J,Q.event,Z);return{...$,...Q.label!==void 0?{label:Q.label}:{},messages:G.messages,...G.finishReason!==void 0?{finishReason:G.finishReason}:{},...G.usage!==void 0?{usage:G.usage}:{}}}function d0($,Q,Z){if(Q.finishReason!=="awaiting-input")return!1;return!$.messages.some((J)=>J.content.some((G)=>G.type==="tool-result"&&G.toolCallId===Z))}function C6($,Q){let Z=$.messages.find((J)=>J.id===Q);return Z!==void 0&&Z.finishReason!==void 0}function t($,Q,Z,J){let G=$.messages.findIndex((Y)=>Y.id===Q),W=$.runMessageIds.includes(Q)?$.runMessageIds:[...$.runMessageIds,Q];if(G===-1){let Y={id:Q,role:"assistant",content:[],createdAt:Z};return{...$,runMessageIds:W,messages:[...$.messages,J(Y)]}}let V=$.messages.slice();return V[G]=J(V[G]),{...$,runMessageIds:W,messages:V}}function i0($,Q){let Z=$[$.length-1];if(Z&&Z.type==="text")return[...$.slice(0,-1),{type:"text",text:Z.text+Q}];return[...$,{type:"text",text:Q}]}function n0($,Q,Z){let J=$[$.length-1];if(J&&J.type==="reasoning"&&J.id===Z)return[...$.slice(0,-1),{...J,text:(J.text??"")+Q}];return[...$,Z?{type:"reasoning",id:Z,text:Q}:{type:"reasoning",text:Q}]}function O6($,Q,Z){let J=$.findIndex(Z);if(J===-1)return[...$,Q];let G=$.slice();return G[J]=Q,G}class jQ{store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor($,Q,Z,J){this.store=$;this.threadId=Q;this.report=J;this.state=N6({messages:Z})}finish($){if(this.closed)return;this.done.add($.id),this.write(()=>[RQ($)])}frame($){if(this.closed)return;let Q=$.event;if(Q.type==="run-start")this.runId=Q.runId;switch(this.state=_6(this.state,$),Q.type){case"message":this.write(()=>[RQ(Q.message)]);return;case"tool-call":if(Q.part.partial)return;this.checkpoint(Q.messageId);return;case"message-start":case"tool-result":this.checkpoint(Q.messageId);return;default:return}}close($=[]){this.closed=!0;for(let Q of $)this.done.add(Q.id)}settled(){return this.chain}checkpoint($){if(this.done.has($))return;let Q=this.state.messages.find((J)=>J.id===$);if(!Q)return;let Z=this.runId;this.write(()=>{let J=RQ(Q);if(J.finishReason===void 0&&Z)J.runId=Z;return[J]})}write($){let Q;try{Q=$()}catch(Z){this.report(Z);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,Q)).catch((Z)=>this.report(Z))}}function RQ($){return structuredClone($)}async function R6($,Q){let Z=[],J=null,G=$.slice();for(let W=0;W<G.length;W++){let V=G[W];if(V.role!=="assistant"||V.finishReason!==void 0)continue;if(V.runId&&await Q(V.runId))continue;J??=new Set($.flatMap((X)=>X.content.flatMap((K)=>K.type==="tool-result"?[K.toolCallId]:[])));let Y=V.content.map((X)=>X.type==="tool-call"?j6(X):X);for(let X of V.content){if(X.type!=="tool-call"||J.has(X.toolCallId))continue;let K={type:"tool-result",toolCallId:X.toolCallId,name:X.name,status:"denied",cause:"interrupted"};Y.push(K)}let H={...V,content:Y,finishReason:"interrupted"};G[W]=H,Z.push(H)}return{messages:G,settled:Z}}function j6($){let{partial:Q,...Z}=$;if(!Z.nested?.some((J)=>J.finishReason===void 0))return Z;return{...Z,nested:Z.nested.map(o0)}}function o0($){if($.finishReason!==void 0)return $;return{...$,finishReason:"interrupted",messages:$.messages.map((Q)=>Q.role==="assistant"&&Q.finishReason===void 0?{...Q,finishReason:"interrupted",content:Q.content.map((Z)=>Z.type==="tool-call"?j6(Z):Z)}:Q)}}var s0=50,t0=["running","ok","error"];async function S6($,Q){let{store:Z,threadId:J}=Q,G=Math.max(s0,Q.scan??0),W=await Z.listForThread(J,{limit:G}),V,Y=async(D)=>{if(D.state!=="running")return D;if(V??=await N$(Z),D.deadlineAt>V)return D;return await _$(Z,D),await Z.get(D.id)??D};for(let D=0;D<W.length;D++)W[D]=await Y(W[D]);let H=new Map(W.map((D)=>[D.id,D])),X=$.slice(),K=[],B=new Set;for(let D=0;D<X.length;D++){let L=X[D],F=null;for(let U=0;U<L.content.length;U++){let P=L.content[U];if(P.type==="tool-call")B.add(P.toolCallId);if(P.type!=="tool-result"||P.status!=="running")continue;let q=P.job?.id,_=q?H.get(q):void 0;if(q&&_===void 0){let N=await Z.get(q);if(_=N?await Y(N):void 0,_)H.set(q,_)}if(_?.state==="running")continue;F??=L.content.slice(),F[U]=a0(P,_,Q.outputSchemaFor)}if(F){let U={...L,content:F};X[D]=U,K.push(U)}}let z=[];for(let D of W){if(D.orphaned||B.has(D.toolCallId))continue;if(await Q.isRunLive(D.runId))continue;z.push(D)}return{messages:X,settled:K,orphans:z,jobs:W}}async function A6($,Q,Z){for(let J of Q)try{await $.transition(J.id,t0,{orphaned:!0})}catch(G){Z(G)}}function a0($,Q,Z){let J={type:"tool-result",toolCallId:$.toolCallId,name:$.name};if(!Q)return{...J,status:"error",job:$.job,error:{code:"tool_error",message:`The background job for "${String($.name)}" can no longer be found, so its result was lost. It may have run in part or in full: check its effects before repeating it.`,toolCallId:$.toolCallId,retryable:!0}};let G={id:Q.id,...Q.summary!==void 0?{summary:Q.summary}:{},...Q.usage?{usage:Q.usage}:{}};if(Q.state==="error")return{...J,status:"error",job:G,error:Q.error??{code:"tool_error",message:`The background job for "${String($.name)}" failed.`,toolCallId:$.toolCallId,retryable:!0}};let W=Z?.(String($.name));if(W){let V=W.safeParse(Q.output);if(V.ok===!1)return{...J,status:"error",job:G,error:{code:"invalid_tool_result",message:`The background job for "${String($.name)}" finished with an output that does not match the tool's output schema: ${V.errors.join(", ")}`,toolCallId:$.toolCallId,retryable:!0}};return{...J,status:"ok",job:G,output:V.value}}return{...J,status:"ok",job:G,output:Q.output}}var r0=y6,K$=new Map,T6=new WeakMap,z$=new Map,e0=4194304,$1=1000,Q1=5,k6=65536,p6=()=>{};class l6{byKey=new Map;take($,Q,Z){let J=this.byKey.get($);if(!J?.has(Q)&&(J?.size??0)>=Z)return null;if(!J)J=new Map,this.byKey.set($,J);J.set(Q,(J.get(Q)??0)+1);let G=!1;return()=>{if(G)return;G=!0;let W=this.byKey.get($),V=(W?.get(Q)??1)-1;if(!W)return;if(V>0)W.set(Q,V);else if(W.delete(Q),W.size===0)this.byKey.delete($)}}}var E6=new WeakMap;function Z1($){let Q=E6.get($);if(!Q)Q=new l6,E6.set($,Q);return Q}class EQ extends r0{static kind="agent-controller";store=MQ;liveRuns=CQ;attachments=r;attachmentStorage=y9;fileOwners=OQ;nonces=Z9;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions($,Q){}context($,Q){return{}}requireThread=!1;maxBodyBytes=e0;maxHistoryMessages=$1;contextWindow=void 0;prepareStep($,Q){}maxConcurrentRuns=Q1;runLimitKey($,Q){return Q.owner}authorizeRequest($,Q){return this.resource?.authorize($,Q)}resource;runOwner($){let Q=$.ctx?.()?.user,Z=Q?.id??Q?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}async stream($=new k9){let Q=await SQ($,this.maxBodyBytes);if(Q.error)return B$(Q);let Z=Q.body,J=typeof Z.threadId==="string"?Z.threadId:void 0,G=K1(Z);if(G.error)return B$({body:{},error:G.error});let W=G.turn,V=J!==void 0&&Z.regenerate===!0,Y=typeof Z.clientRunId==="string"?Z.clientRunId:void 0,H=d6(Z);if(this.requireThread&&!J)return f(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(V&&!this.store.removeMessages)return f(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 kQ(413,"history_too_long",`The conversation has ${Z.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let X=await this.runOwner($),K=Y?{cancelled:!1,owner:X}:null;if(K)z$.set(Y,K);let B=null,z=[],D=async()=>{try{return await L()}finally{if(J&&z.length>0&&B===null)await this.store.appendMessages(J,z).catch((F)=>this.reportHookFailure(F))}},L=async()=>{let F,U=null;if(J){let k=await this.store.loadThread(J);if(!k)return f(404,{code:"thread_not_found",message:`Thread ${J} does not exist here, or has expired.`});let a=await this.settleThread(J,k,{write:!0});if(F=a.messages,U=this.jobsBlock(a.jobs),V){let K9=F1(F);if(!K9)return f(409,{code:"nothing_to_regenerate",message:`Thread ${J} has no user turn to answer again.`});z=F.slice(K9.index),await this.store.removeMessages(J,z.map((s6)=>s6.id)),F=F.slice(0,K9.index),W=W?.localId?{...K9.turn,localId:W.localId}:K9.turn}}else F=Array.isArray(Z.messages)?Z.messages:[],_1(this.nonces);let P=[await this.instructions($,{body:H})||void 0,U??void 0].filter(Boolean).join(`
|
|
102
|
+
|
|
103
|
+
`)||void 0,q=await this.context($,{body:H}),_=await this.attachmentsFor($,J,{body:H});if(K?.cancelled)return f6();let N=J?new jQ(this.store,J,F,(k)=>this.reportHookFailure(k)):null,A=`run_${crypto.randomUUID()}`,E={req:$,runId:A,threadId:J},x={id:null,notified:Promise.resolve()},O=this.agent.stream({runId:A,messages:F,turn:W,threadId:J,...N?{onMessage:(k)=>N.finish(k)}:{},onTurn:(k)=>{if(x.id!==null)return;x.id=k.id;let a=N?N.settled():Promise.resolve();x.notified=a.then(()=>this.safely(()=>this.onMessage(k,E)))},instructions:P,context:q,attachments:_,body:H,redactError:(k,a)=>this.redactError(k,a,E),nonces:this.nonces,receipts:this.receipts,subject:X,...J?{jobs:{owner:X}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...J&&CZ(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==EQ.prototype.prepareStep?{prepareStep:(k)=>this.prepareStep(k,E)}:{}}),C=this.liveRuns.register(O,{threadId:J,owner:X,clientRunId:Y,onEvent:(k)=>this.dispatchEvent(k,E),onInternalError:(k)=>this.reportHookFailure(k),maxRunDurationMs:this.agent.maxRunDurationMs});if(B=O,N)this.follow(O,N);let{stored:T,hooks:j}=this.persistRun(O,E,C,N,x);return T6.set(O,T),$.ctx?.()?.waitUntil(j),O.toResponse()};try{await this.authorizeRequest($,{route:"stream",threadId:J,body:H});let F=await this.foreignFile([...W?.files??[],...J?[]:U1(Z.messages)],X);if(F)return F;if(K?.cancelled)return f6();let U=await this.runLimitKey($,{owner:X,threadId:J}),P=U===null?p6:Z1(this.liveRuns).take(U,J?`thread:${J}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!P)return kQ(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,X,D):await D()}finally{let q=B;if(q)q.result().then(P,P);else P()}}finally{if(K&&z$.get(Y)===K)z$.delete(Y)}}async withThread($,Q,Z){let J=K$.get($)??Promise.resolve(),G,W=new Promise((Y)=>{G=Y}),V=J.then(()=>W);K$.set($,V),await J;try{let Y=await this.liveRuns.find({threadId:$});if(Y&&this.liveRuns.isRunning(Y.runId)&&!this.liveRuns.mayAccess(Y.runId,Q))return D$();let H=Y?this.liveRuns.get(Y.runId):null;if(H)H.stop({reason:"superseded by a later turn on this thread"}),await T6.get(H);return await Z()}finally{if(G(),K$.get($)===V)K$.delete($)}}async attach($=new k9){let Q=await SQ($,k6);if(Q.error)return B$(Q);let Z=Q.body,J=typeof Z.threadId==="string"?Z.threadId:D1($,"threadId");if(!J)return f(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest($,{route:"attach",threadId:J});let G=await this.liveRuns.find({threadId:J});if(G&&!this.liveRuns.mayAccess(G.runId,await this.runOwner($)))return D$();if(!G)return f(404,{code:"no_live_run",message:`No run in progress for thread ${J} in this process.`});let W=typeof Z.runId==="string"?Z.runId:void 0,V=W&&W!==G.runId?void 0:B1($,Z);try{return c6(this.liveRuns.replay(G.runId,V))}catch(Y){if(Y instanceof H9)return f(410,{code:Y.code,message:Y.message,oldestSeq:Y.oldest});if(Y instanceof T9)return f(404,{code:Y.code,message:Y.message});throw Y}}async stop($=new k9){let Q=await SQ($,k6);if(Q.error)return B$(Q);let Z=Q.body;await this.authorizeRequest($,{route:"stop",threadId:typeof Z.threadId==="string"?Z.threadId:void 0});let J=await this.runOwner($),G=typeof Z.runId==="string"?Z.runId:void 0;if(!G&&typeof Z.clientRunId==="string"){if(G=this.liveRuns.findByClientRunId(Z.clientRunId)??void 0,!G){let V=z$.get(Z.clientRunId);if(V){if(V.owner!==null&&V.owner!==J)return D$();return V.cancelled=!0,{stopped:!0}}}}if(!G&&typeof Z.threadId==="string")G=(await this.liveRuns.find({threadId:Z.threadId}))?.runId;let W=G?this.liveRuns.get(G):null;if(!W)return{stopped:!1};if(!this.liveRuns.mayAccess(W.runId,J))return D$();return W.stop({reason:typeof Z.reason==="string"?Z.reason:void 0}),{stopped:!0}}attachmentScope($,Q,Z){let J=$.ctx()?.user,G=J?.id??J?.publicId;if(G!==void 0&&G!==null&&String(G)!=="")return{key:`user:${String(G)}`};if(Q)return{key:`thread:${Q}`};return null}attachmentLimits($){return null}attachmentDestination($,Q){return"both"}async attachmentsFor($,Q,Z={body:{}}){let J=await this.attachmentScope($,Q,Z);if(!J)return null;return new p(this.attachments,this.attachmentStorage,J)}async upload($=new k9){let Q=await $.rawRequest.formData(),Z=Q.get("file");if(!(Z instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let J=Z instanceof File&&Z.name?Z.name:"upload",G=Z.type||"application/octet-stream",W=G1(Q.get("body")),V=Q.get("threadId");await this.authorizeRequest($,{route:"upload",threadId:typeof V==="string"&&V.length>0?V:void 0,body:W});let Y=V1(await this.attachmentLimits($),Z,J,G);if(Y)throw new i6(Y.code,Y.message);let H=typeof V==="string"&&V.length>0&&await this.store.loadThread(V)!==null?V:void 0,X=await this.runOwner($),K=(_)=>this.fileOwners.record(_,{owner:X,name:J,mimeType:G,size:Z.size,createdAt:new Date().toISOString()}),B=await this.attachmentDestination(Z,$),z=P1(B,Q.get("destination")),D=await this.attachmentScope($,H,{body:W}),L=z!=="provider"&&!D;if(L){if(z==="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(z==="provider"||!D){let _=await x6(this.agent.provider,Z);await K(_);let N={fileId:_,name:J,mimeType:G,size:Z.size,destination:"provider"};if(L)N.downgraded="no_scope";return N}let F=C$(),U=await this.attachmentStorage.put({name:O$(F,J),body:Z,contentType:G}),P=z==="both"?await x6(this.agent.provider,Z):void 0;if(P)await K(P);let q={id:F,scopeKey:D.key,fileId:P,objectName:U,name:J,mimeType:G,size:Z.size,createdAt:new Date().toISOString(),destination:z};return await this.attachments.put(D,q),{fileId:P,attachmentId:F,name:J,mimeType:G,size:Z.size,destination:z}}async foreignFile($,Q){let Z=new Set($.map((J)=>J.fileId).filter((J)=>typeof J==="string"));for(let J of Z){let G=await this.fileOwners.get(J);if(G?G.owner!==null&&G.owner!==Q:this.requireKnownFiles)return L1()}return null}onMessage($,Q){}onToolCall($,Q){}onAwaitingInput($,Q){}redactError($,Q,Z){return O9($,Q)}onError($,Q){}onStreamComplete($,Q){}reportHookFailure($){console.error("[gemi/ai] agent controller hook failed",$)}async dispatchEvent($,Q){switch($.type){case"tool-call":if(!$.part.partial&&!$.resent)await this.onToolCall({toolCallId:$.part.toolCallId,name:String($.part.name),input:$.part.input},Q);return;case"awaiting-input":await this.onAwaitingInput($.pending,Q);return;case"error":await this.onError(m6($.error),Q);return;default:return}}async readThread($){let Q=await this.store.loadThread($);return Q?(await this.settleThread($,Q,{write:!1})).messages:null}isRunLive($,Q){return this.liveRuns.get($)!==null}async settleThread($,Q,{write:Z}){let J=(H)=>this.isRunLive(H,$),G=await R6(Q,J),W=G.messages,V=[],Y=new Map(G.settled.map((H)=>[H.id,H]));if(q1(W)||Z)try{let H=await S6(W,{threadId:$,store:y.store,isRunLive:J,outputSchemaFor:(X)=>this.toolOutputSchema(X),scan:this.jobsBlockMax()});W=H.messages,V=H.jobs;for(let X of H.settled)Y.set(X.id,X);if(Z&&H.orphans.length>0){await A6(y.store,H.orphans,(K)=>this.reportHookFailure(K));let X=new Set(H.orphans.map((K)=>K.id));V=V.map((K)=>X.has(K.id)?{...K,orphaned:!0}:K)}}catch(H){this.reportHookFailure(H)}if(Z&&Y.size>0)try{await this.store.appendMessages($,[...Y.values()])}catch(H){this.reportHookFailure(H)}return{messages:W,jobs:V}}jobsBlockMax(){let $=this.agent.jobs?.contextBlock;if($===!1)return 0;return $?.max??r9}jobsBlock($){return uZ($,this.jobsBlockMax())}toolOutputSchema($){let Q=(Z)=>{for(let J of Z){let G=J;if(Array.isArray(G.tools)){let W=Q(G.tools);if(W)return W}else if(G.name===$)return G.outputSchema}return};return Q(this.agent.tools??[])}follow($,Q){(async()=>{try{for await(let Z of $.frames())Q.frame(Z)}catch(Z){this.reportHookFailure(Z)}})()}persistRun($,Q,Z,J=null,G={id:null,notified:Promise.resolve()}){let W=Promise.resolve(),V=(async()=>{let H;try{H=await $.result()}catch(K){J?.close(),await J?.settled(),W=G.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:K instanceof Error?K.message:String(K),retryable:!1},Q)));return}let X=H.messages;if(J?.close(X),await J?.settled(),Q.threadId&&X.length>0)try{await this.store.appendMessages(Q.threadId,X)}catch(K){this.reportHookFailure(K)}W=this.notifyRun(H,X,Q,G)})(),Y=V.then(()=>N1(Promise.all([W,Z]).then(()=>{}),this.hookHoldMs));return{stored:V,hooks:Y}}async notifyRun($,Q,Z,J){await J.notified;for(let G of Q){if(G.id===J.id)continue;await this.safely(()=>this.onMessage(G,Z))}await this.safely(()=>this.onStreamComplete($,Z))}async safely($){try{await $()}catch(Q){this.reportHookFailure(Q)}}}var AQ=["turn","clientRunId","threadId","messages","regenerate"],J1=["text","files","toolResults"];function d6($,Q=o6($)?AQ:[...AQ,...J1]){let Z={};for(let[J,G]of Object.entries($)){if(Q.includes(J))continue;Object.defineProperty(Z,J,{value:G,writable:!0,enumerable:!0,configurable:!0})}return Z}function G1($){if($===null)return{};let Q;if(typeof $==="string")try{Q=JSON.parse($)}catch{throw new TQ("The upload's `body` field is not valid JSON.")}if(Q===null||typeof Q!=="object"||Array.isArray(Q))throw new TQ("The upload's `body` field must be a JSON object.");return d6(Q,AQ)}class TQ extends F${constructor($){super($);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:$}}},view:{}}}}async function x6($,Q){try{return await $.upload(Q)}catch(Z){if(Z instanceof g&&W1.has(Z.status))throw new n6(I(Z).message);throw Z}}var W1=new Set([400,413,415,422]);class i6 extends F${constructor($,Q){super(Q);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:$,message:Q}}},view:{}}}}function V1($,Q,Z,J){if(!$)return null;let{maxBytes:G,accept:W}=$;if(typeof G==="number"&&Q.size>G)return{code:"file_too_large",message:`${JSON.stringify(Z)} is ${I6(Q.size)}; the limit is ${I6(G)}.`};if(W&&W.length>0&&!W.some((V)=>X1(V,Z,J)))return{code:"unsupported_file_type",message:`${JSON.stringify(Z)} is not a type this chat accepts. Accepted: ${W.join(", ")}.`};return null}function X1($,Q,Z){let J=$.trim().toLowerCase();if(!J)return!1;if(J.startsWith("."))return Q.toLowerCase().endsWith(J);let G=Z.toLowerCase().split(";")[0].trim();if(J.endsWith("/*"))return G.startsWith(J.slice(0,-1));return G===J}function I6($){if($<1024)return`${$} B`;let Q=["KB","MB","GB"],Z=$/1024,J=0;while(Z>=1024&&J<Q.length-1)Z/=1024,J++;return`${Math.round(Z*10)/10} ${Q[J]}`}class n6 extends F${constructor($){super($);this.name="RejectedUploadError";let Q=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test($)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:Q,message:$}}},view:{}}}}async function SQ($,Q){let Z=$?.rawRequest;if(!Z||Z.method==="GET"||Z.method==="HEAD"||!Z.body)return{body:{}};if(!Y1(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>Q)return w6(Q);let G;try{let V=await H1(Z,Q);if(V===null)return w6(Q);G=V}catch{return{body:{},error:"The request body could not be read."}}if(!G.trim())return{body:{}};let W;try{W=JSON.parse(G)}catch{return{body:{},error:"The request body is not valid JSON."}}if(W===null||typeof W!=="object"||Array.isArray(W))return{body:{},error:"The request body must be a JSON object."};return{body:W}}function Y1($){return u6($)==="application/json"}async function H1($,Q){if(!Number.isFinite(Q)||!$.body)return await $.text();let Z=$.body.getReader(),J=[],G=0;for(;;){let{done:Y,value:H}=await Z.read();if(Y)break;if(G+=H.byteLength,G>Q)return await Z.cancel().catch(p6),null;J.push(H)}let W=new Uint8Array(G),V=0;for(let Y of J)W.set(Y,V),V+=Y.byteLength;return new TextDecoder().decode(W)}function w6($){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${$} bytes).`}}function kQ($,Q,Z){return f($,{...L$(g6($),Z,$),code:Q})}function B$($){if($.status===413)return kQ(413,$.code??"body_too_large",$.error??"");return f($.status??400,{code:$.code??"invalid_request",message:$.error})}function o6($){return Boolean($.turn)&&typeof $.turn==="object"}function K1($){let Q=o6($)?$.turn:$,Z={};if(typeof Q.text==="string")Z.text=Q.text;if(Array.isArray(Q.files)){let J=z1(Q.files);if(typeof J==="string")return{error:J};Z.files=J}if(Array.isArray(Q.toolResults))Z.toolResults=Q.toolResults;if(Object.keys(Z).length===0)return{};if(Q===$.turn&&Q.localId!==void 0&&Q.localId!==null&&Q.localId!==""){let{localId:J}=Q;if(typeof J!=="string")return{error:"turn.localId must be a string."};if(J.length>b6)return{error:`turn.localId is longer than ${b6} characters.`};Z.localId=J}return{turn:Z}}var b6=200;function z1($){let Q=[];for(let[Z,J]of $.entries()){let G=`turn.files[${Z}]`;if(!J||typeof J!=="object"||Array.isArray(J))return`${G} must be an object.`;let W={};for(let K of["fileId","attachmentId","name","mimeType"]){let B=J[K];if(B===void 0||B===null||B==="")continue;if(typeof B!=="string")return`${G}.${K} must be a string.`;W[K]=B}let{fileId:V,attachmentId:Y,name:H,mimeType:X}=W;if(V?.startsWith(h))return`${G}.fileId holds a gemi attachment id (${V}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(Y!==void 0&&!Y.startsWith(h))return`${G}.attachmentId is not a gemi attachment id: it must start with "${h}".`;if(!V&&!Y)return`${G} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;Q.push({...V?{fileId:V}:{},...Y?{attachmentId:Y}:{},...H!==void 0?{name:H}:{},...X!==void 0?{mimeType:X}:{}})}return Q}function B1($,Q){if(typeof Q.from==="number"&&Number.isFinite(Q.from))return Math.max(0,Math.floor(Q.from));if(typeof Q.cursor==="number"&&Number.isFinite(Q.cursor)){let J=Math.floor(Q.cursor);if(J>=0)return J+1;return}let Z=$?.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 D1($,Q){let Z=$?.search?.get(Q);return typeof Z==="string"?Z:void 0}function F1($){let Q=d($);for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J.role!=="user"||Q.has(J.id))continue;let G="",W=[];for(let V of J.content){if(V.type==="text")G+=V.text;if(V.type==="file")W.push({...V.fileId?{fileId:V.fileId}:{},...V.attachmentId?{attachmentId:V.attachmentId}:{},...V.name?{name:V.name}:{},...V.mimeType?{mimeType:V.mimeType}:{}})}if(!G&&W.length===0)continue;return{index:Z,turn:{...G?{text:G}:{},...W.length>0?{files:W}:{}}}}return null}function f6(){return f(409,{code:"stopped",message:"The turn was stopped before it started."})}function D$(){return f(403,L$("permission","This run belongs to someone else.",403))}function L1(){return f(403,L$("permission","A file in this turn was uploaded by someone else.",403))}function U1($){if(!Array.isArray($))return[];let Q=[];for(let Z of $){let J=Z?.content;if(!Array.isArray(J))continue;for(let G of J)if(G&&typeof G==="object"&&typeof G.fileId==="string")Q.push({fileId:G.fileId})}return Q}function f($,Q){return new Response(JSON.stringify({error:Q}),{status:$,headers:{"Content-Type":"application/json"}})}function P1($,Q){if(typeof Q!=="string"||Q.length===0)return $;if(Q!=="both"&&Q!=="provider"&&Q!=="storage")throw Error(`Unknown attachment destination "${Q}". Expected "both", "provider" or "storage".`);if(Q===$||$==="both"&&Q==="storage")return Q;if($==="both"&&Q==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${Q}" destination, but the server's policy for it is "${$}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var v6=!1;function C1(){if(v6)return;v6=!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 O1=2147483647;function N1($,Q){let Z=$.then(()=>{},()=>{});if(!(Q<=O1))return Z;let J,G=new Promise((W)=>{J=setTimeout(W,Q)});return Promise.race([Z,G]).finally(()=>clearTimeout(J))}var h6=!1;function _1($){if(h6||Bun.env.NODE_ENV!=="production")return;if(!($ instanceof N9))return;h6=!0,console.warn("[gemi/ai] A stateless agent chat is spending approval nonces in process memory. With more than one instance a replayed approval is accepted once per instance. Set `nonces = new RedisNonceStore()` (or your own NonceStore) on the AgentController.")}function q1($){return $.some((Q)=>Q.content.some((Z)=>Z.type==="tool-result"&&Z.status==="running"))}export{J9 as windowMessages,q9 as turnStarts,a8 as toAgentTools,z9 as supportsStrict,U8 as splitTurns,S8 as settleSummaries,d9 as s,O9 as redactError,YZ as messageSize,CQ as liveRuns,n9 as keepSummary,d as injectedMessageIds,U$ as generate,v0 as evalChain,f$ as defaultSummaryStore,Z9 as defaultNonceStore,OQ as defaultFileOwners,r as defaultAttachmentStore,MQ as defaultAgentStore,G9 as ToolNamespace,S as ToolError,c$ as Skill,p as ScopedAttachments,j9 as SKILLS_NAMESPACE,qQ as RedisReceiptStore,R$ as RedisNonceStore,n as PendingEscalation,DQ as OpenAIProvider,$Q as OpenAIImageProvider,b$ as MemorySummaryStore,_Q as MemoryReceiptStore,N9 as MemoryNonceStore,X$ as MemoryLiveRuns,Y$ as MemoryFileOwners,V$ as MemoryCircuitStore,v9 as MemoryAttachmentStore,H$ as MemoryAgentStore,P9 as MemoryAgentJobStore,T9 as LiveRunNotFoundError,C9 as JobsRequireThreadError,g9 as JobHandle,M1 as JSONSchemaError,u as InvalidAttachmentScopeError,J$ as ImageRequestError,G$ as ImageProvider,a$ as ImageModel,H9 as FrameCursorEvictedError,A9 as FallbackProvider,s$ as DatabaseAgentJobStore,FZ as DEFAULT_MAX_SUMMARY_TOKENS,l$ as DEFAULT_MAX_RUN_DURATION_MS,q$ as DEFAULT_JOB_DEADLINE_MS,r9 as DEFAULT_JOBS_CONTEXT_MAX,HZ as DEFAULT_CONTEXT_WINDOW_STEP,KZ as DEFAULT_CONTEXT_WINDOW_NOTE,LZ as DEFAULT_COMPACT_TRIGGER_TOKENS,UZ as DEFAULT_COMPACT_INSTRUCTIONS,PZ as COMPACT_SUMMARY_HEADER,FQ as AzureOpenAIProvider,QQ as AzureOpenAIImageProvider,U9 as AttachmentNotFoundError,o as AgentTool,L9 as AgentRunError,Y9 as AgentProvider,y as AgentJobs,i$ as AgentJobDeadlineSweep,M$ as AgentJob,EQ as AgentController,d$ as Agent};
|
|
25
104
|
|
|
26
|
-
//# debugId=
|
|
105
|
+
//# debugId=4886125D4947C82664756E2164756E21
|