gemi 0.63.0-rc.0 → 0.63.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/AgentController.d.ts +35 -0
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/index.js +9 -9
- package/dist/ai/index.js.map +3 -3
- package/dist/app/App.d.ts +20 -0
- package/dist/app/App.d.ts.map +1 -1
- package/dist/app/index.js +2 -2
- package/dist/app/index.js.map +1 -1
- package/dist/auth/AuthController.d.ts +21 -0
- package/dist/auth/AuthController.d.ts.map +1 -1
- package/dist/auth/AuthManager.d.ts +16 -0
- package/dist/auth/AuthManager.d.ts.map +1 -1
- package/dist/auth/UserProvider.d.ts +24 -1
- package/dist/auth/UserProvider.d.ts.map +1 -1
- package/dist/auth/config.d.ts +22 -0
- package/dist/auth/config.d.ts.map +1 -1
- package/dist/auth/oauth/GoogleOAuthProvider.d.ts +5 -0
- package/dist/auth/oauth/GoogleOAuthProvider.d.ts.map +1 -1
- package/dist/auth/oauth/OAuthProvider.d.ts +8 -0
- package/dist/auth/oauth/OAuthProvider.d.ts.map +1 -1
- package/dist/auth/routes.d.ts +4 -0
- package/dist/auth/routes.d.ts.map +1 -1
- package/dist/auth/signInRedirect.d.ts +18 -0
- package/dist/auth/signInRedirect.d.ts.map +1 -0
- package/dist/auth/types.d.ts +9 -0
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/bin/gemi.js +170 -27
- package/dist/bin/gemi.js.map +11 -8
- package/dist/broadcasting/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +2 -2
- package/dist/bun/preload.js.map +1 -1
- package/dist/chunk-0081bz9c.js +5 -0
- package/dist/{chunk-zq2v9fgf.js.map → chunk-0081bz9c.js.map} +10 -10
- package/dist/chunk-0amv13g6.js +5 -0
- package/dist/chunk-0amv13g6.js.map +25 -0
- package/dist/chunk-0e5z1x9w.js +18 -0
- package/dist/{chunk-v7y8zm61.js.map → chunk-0e5z1x9w.js.map} +5 -4
- package/dist/{chunk-yspg0cvk.js → chunk-0qchadp1.js} +2 -2
- package/dist/{chunk-yspg0cvk.js.map → chunk-0qchadp1.js.map} +1 -1
- package/dist/chunk-1s1cd1e8.js +5 -0
- package/dist/chunk-1s1cd1e8.js.map +12 -0
- package/dist/{chunk-hr90mpy9.js → chunk-2d92pev2.js} +2 -2
- package/dist/{chunk-hr90mpy9.js.map → chunk-2d92pev2.js.map} +1 -1
- package/dist/chunk-35fbxgjh.js +4 -0
- package/dist/chunk-35fbxgjh.js.map +10 -0
- package/dist/chunk-39p7ge47.js +24 -0
- package/dist/chunk-39p7ge47.js.map +16 -0
- package/dist/{chunk-q4zvp9b9.js → chunk-43xw9n4f.js} +2 -2
- package/dist/{chunk-q4zvp9b9.js.map → chunk-43xw9n4f.js.map} +1 -1
- package/dist/{chunk-kpy138e2.js → chunk-454c7vn3.js} +2 -2
- package/dist/chunk-454c7vn3.js.map +10 -0
- package/dist/{chunk-hvm1aamv.js → chunk-4728yrmt.js} +2 -2
- package/dist/{chunk-hvm1aamv.js.map → chunk-4728yrmt.js.map} +1 -1
- package/dist/{chunk-qrb9d1fs.js → chunk-48qybp63.js} +2 -2
- package/dist/{chunk-qrb9d1fs.js.map → chunk-48qybp63.js.map} +1 -1
- package/dist/{chunk-fjs7ad18.js → chunk-4sv5zpb4.js} +2 -2
- package/dist/{chunk-fjs7ad18.js.map → chunk-4sv5zpb4.js.map} +1 -1
- package/dist/{chunk-qskcpfpf.js → chunk-5wzyx4ts.js} +2 -2
- package/dist/{chunk-qskcpfpf.js.map → chunk-5wzyx4ts.js.map} +1 -1
- package/dist/{chunk-etgsft9d.js → chunk-62xjrz5e.js} +3 -3
- package/dist/{chunk-etgsft9d.js.map → chunk-62xjrz5e.js.map} +1 -1
- package/dist/chunk-6j129573.js +54 -0
- package/dist/{chunk-kj5xryzy.js.map → chunk-6j129573.js.map} +5 -8
- package/dist/chunk-71yhw8aw.js +5 -0
- package/dist/chunk-71yhw8aw.js.map +10 -0
- package/dist/{chunk-p3v76b6c.js → chunk-773qa4av.js} +3 -3
- package/dist/{chunk-p3v76b6c.js.map → chunk-773qa4av.js.map} +1 -1
- package/dist/chunk-78cvy4je.js +5 -0
- package/dist/chunk-78cvy4je.js.map +11 -0
- package/dist/chunk-7hbhbht2.js +5 -0
- package/dist/chunk-7hbhbht2.js.map +12 -0
- package/dist/{chunk-6afc71kp.js → chunk-7qfzrkab.js} +2 -2
- package/dist/{chunk-6afc71kp.js.map → chunk-7qfzrkab.js.map} +1 -1
- package/dist/{chunk-t5kbqva2.js → chunk-81yzec62.js} +2 -2
- package/dist/{chunk-t5kbqva2.js.map → chunk-81yzec62.js.map} +1 -1
- package/dist/{chunk-nt9685gz.js → chunk-8wpccvbt.js} +3 -3
- package/dist/{chunk-nt9685gz.js.map → chunk-8wpccvbt.js.map} +1 -1
- package/dist/{chunk-tkdxv6cq.js → chunk-8z37k28d.js} +2 -2
- package/dist/{chunk-tkdxv6cq.js.map → chunk-8z37k28d.js.map} +1 -1
- package/dist/{chunk-nv93zp3x.js → chunk-95d8jj11.js} +2 -2
- package/dist/{chunk-nv93zp3x.js.map → chunk-95d8jj11.js.map} +1 -1
- package/dist/{chunk-5ad8era8.js → chunk-9a8qz3s7.js} +2 -2
- package/dist/{chunk-5ad8era8.js.map → chunk-9a8qz3s7.js.map} +1 -1
- package/dist/{chunk-2ctdp7ry.js → chunk-9e5c5e15.js} +2 -2
- package/dist/{chunk-2ctdp7ry.js.map → chunk-9e5c5e15.js.map} +1 -1
- package/dist/{chunk-43nt6e36.js → chunk-9e5v1t73.js} +2 -2
- package/dist/{chunk-43nt6e36.js.map → chunk-9e5v1t73.js.map} +1 -1
- package/dist/chunk-9k5daets.js +5 -0
- package/dist/chunk-9k5daets.js.map +11 -0
- package/dist/chunk-anfs5mwm.js +19 -0
- package/dist/chunk-anfs5mwm.js.map +90 -0
- package/dist/{chunk-ktnaj5c4.js → chunk-b6948dnh.js} +2 -2
- package/dist/{chunk-ktnaj5c4.js.map → chunk-b6948dnh.js.map} +1 -1
- package/dist/{chunk-38zft53j.js → chunk-bxtx4y4w.js} +2 -2
- package/dist/{chunk-38zft53j.js.map → chunk-bxtx4y4w.js.map} +1 -1
- package/dist/chunk-cdpeh7tt.js +6 -0
- package/dist/{chunk-81se9gak.js.map → chunk-cdpeh7tt.js.map} +2 -2
- package/dist/chunk-dfv5eqma.js +5 -0
- package/dist/chunk-dfv5eqma.js.map +10 -0
- package/dist/{chunk-xjfpnmgn.js → chunk-dhe1hsyz.js} +2 -2
- package/dist/{chunk-xjfpnmgn.js.map → chunk-dhe1hsyz.js.map} +1 -1
- package/dist/chunk-dq2hgzje.js +5 -0
- package/dist/{chunk-njrjnkab.js.map → chunk-dq2hgzje.js.map} +1 -1
- package/dist/{chunk-e2441vnc.js → chunk-dqbm9vd0.js} +3 -3
- package/dist/{chunk-e2441vnc.js.map → chunk-dqbm9vd0.js.map} +1 -1
- package/dist/{chunk-0p1zytn6.js → chunk-e41vdprh.js} +3 -3
- package/dist/{chunk-0p1zytn6.js.map → chunk-e41vdprh.js.map} +1 -1
- package/dist/{chunk-xth9vh46.js → chunk-e785380d.js} +2 -2
- package/dist/chunk-e785380d.js.map +10 -0
- package/dist/{chunk-pa4cbxnf.js → chunk-exwbtfe9.js} +2 -2
- package/dist/{chunk-pa4cbxnf.js.map → chunk-exwbtfe9.js.map} +1 -1
- package/dist/chunk-f9ccncar.js +5 -0
- package/dist/chunk-f9ccncar.js.map +13 -0
- package/dist/{chunk-pza618j0.js → chunk-feyr4851.js} +2 -2
- package/dist/{chunk-pza618j0.js.map → chunk-feyr4851.js.map} +1 -1
- package/dist/{chunk-dv772dyn.js → chunk-fv223805.js} +3 -3
- package/dist/{chunk-dv772dyn.js.map → chunk-fv223805.js.map} +1 -1
- package/dist/{chunk-ejrcyzx8.js → chunk-gvkydx8r.js} +2 -2
- package/dist/{chunk-ejrcyzx8.js.map → chunk-gvkydx8r.js.map} +1 -1
- package/dist/{chunk-bmfm7dyp.js → chunk-hkhxkeeb.js} +3 -3
- package/dist/{chunk-bmfm7dyp.js.map → chunk-hkhxkeeb.js.map} +1 -1
- package/dist/chunk-jk8mn861.js +5 -0
- package/dist/chunk-jk8mn861.js.map +10 -0
- package/dist/{chunk-ph5n045f.js → chunk-jmbdr550.js} +2 -2
- package/dist/{chunk-ph5n045f.js.map → chunk-jmbdr550.js.map} +1 -1
- package/dist/{chunk-v8m61g5d.js → chunk-jmse5hec.js} +3 -3
- package/dist/{chunk-v8m61g5d.js.map → chunk-jmse5hec.js.map} +1 -1
- package/dist/{chunk-4qgwyjwz.js → chunk-jv9k1qfr.js} +3 -3
- package/dist/{chunk-4qgwyjwz.js.map → chunk-jv9k1qfr.js.map} +1 -1
- package/dist/chunk-k1wkvrj0.js +9 -0
- package/dist/chunk-k1wkvrj0.js.map +10 -0
- package/dist/chunk-kx7vgcjp.js +19 -0
- package/dist/{chunk-1mf5vw0z.js.map → chunk-kx7vgcjp.js.map} +5 -7
- package/dist/chunk-maxd55a0.js +6 -0
- package/dist/{chunk-35p0gqmf.js.map → chunk-maxd55a0.js.map} +2 -2
- package/dist/chunk-nnc40mf3.js +5 -0
- package/dist/chunk-nnc40mf3.js.map +11 -0
- package/dist/{chunk-mxbtd91q.js → chunk-p57x55qd.js} +2 -2
- package/dist/{chunk-mxbtd91q.js.map → chunk-p57x55qd.js.map} +1 -1
- package/dist/chunk-pbx9p6g0.js +80 -0
- package/dist/chunk-pbx9p6g0.js.map +14 -0
- package/dist/{chunk-kvr6e9md.js → chunk-ptjexzn1.js} +2 -2
- package/dist/{chunk-kvr6e9md.js.map → chunk-ptjexzn1.js.map} +1 -1
- package/dist/{chunk-q3zthdy7.js → chunk-q4wdg0y3.js} +2 -2
- package/dist/{chunk-q3zthdy7.js.map → chunk-q4wdg0y3.js.map} +1 -1
- package/dist/{chunk-tabcfsep.js → chunk-q8msf1gf.js} +2 -2
- package/dist/{chunk-tabcfsep.js.map → chunk-q8msf1gf.js.map} +1 -1
- package/dist/{chunk-fy5s4yse.js → chunk-qcbtr7hm.js} +2 -2
- package/dist/{chunk-fy5s4yse.js.map → chunk-qcbtr7hm.js.map} +1 -1
- package/dist/{chunk-8jjw9hqf.js → chunk-qrfp7pg2.js} +4 -4
- package/dist/{chunk-8jjw9hqf.js.map → chunk-qrfp7pg2.js.map} +1 -1
- package/dist/{chunk-faj0stp9.js → chunk-rhr8qavq.js} +2 -2
- package/dist/{chunk-faj0stp9.js.map → chunk-rhr8qavq.js.map} +1 -1
- package/dist/{chunk-jg6vmate.js → chunk-rj3fnc4h.js} +1 -1
- package/dist/chunk-ssg20z9s.js +142 -0
- package/dist/chunk-ssg20z9s.js.map +13 -0
- package/dist/chunk-tq92xqkk.js +55 -0
- package/dist/chunk-tq92xqkk.js.map +12 -0
- package/dist/{chunk-gktc4g6g.js → chunk-v6v03hy7.js} +3 -3
- package/dist/{chunk-gktc4g6g.js.map → chunk-v6v03hy7.js.map} +1 -1
- package/dist/{chunk-dpbxpyrs.js → chunk-wqmzad46.js} +2 -2
- package/dist/{chunk-dpbxpyrs.js.map → chunk-wqmzad46.js.map} +1 -1
- package/dist/{chunk-bykty4bm.js → chunk-xadk41cs.js} +4 -4
- package/dist/{chunk-bykty4bm.js.map → chunk-xadk41cs.js.map} +1 -1
- package/dist/{chunk-92j4tjjx.js → chunk-z2fnf49p.js} +1 -1
- package/dist/{chunk-y9wdr6h4.js → chunk-zdj2wmbj.js} +2 -2
- package/dist/{chunk-y9wdr6h4.js.map → chunk-zdj2wmbj.js.map} +1 -1
- package/dist/chunk-zq5m4scz.js +5 -0
- package/dist/chunk-zq5m4scz.js.map +10 -0
- package/dist/{chunk-yf8kxjr2.js → chunk-zytmxty5.js} +2 -2
- package/dist/{chunk-yf8kxjr2.js.map → chunk-zytmxty5.js.map} +1 -1
- package/dist/chunks/{ThemeProvider-BZ2SsSZ3.js → ThemeProvider-Bz-y1g2i.js} +62 -9
- package/dist/chunks/ThemeProvider-Bz-y1g2i.js.map +1 -0
- package/dist/client/ClientRouter.d.ts.map +1 -1
- package/dist/client/ClientRouterContext.d.ts +2 -0
- package/dist/client/ClientRouterContext.d.ts.map +1 -1
- package/dist/client/Link.d.ts +17 -2
- package/dist/client/Link.d.ts.map +1 -1
- package/dist/client/Mutation.d.ts.map +1 -1
- package/dist/client/ProgressManager.d.ts +1 -1
- package/dist/client/ServerDataProvider.d.ts +11 -0
- package/dist/client/ServerDataProvider.d.ts.map +1 -1
- package/dist/client/auth/useIntendedUrl.d.ts +14 -0
- package/dist/client/auth/useIntendedUrl.d.ts.map +1 -0
- package/dist/client/index.d.ts +2 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +153 -27
- package/dist/client/index.js.map +1 -1
- package/dist/client/useDictionary.d.ts.map +1 -1
- package/dist/client/useDomain.d.ts +17 -0
- package/dist/client/useDomain.d.ts.map +1 -0
- package/dist/client/useMutation.d.ts.map +1 -1
- package/dist/client/useNavigate.d.ts.map +1 -1
- package/dist/config/assetBase.d.ts +52 -0
- package/dist/config/assetBase.d.ts.map +1 -0
- package/dist/config/index.d.ts +9 -0
- package/dist/config/index.d.ts.map +1 -1
- package/dist/config/index.js +1 -1
- package/dist/config/index.js.map +2 -2
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +2 -2
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.d.ts +1 -0
- package/dist/database/index.d.ts.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/database/introspect/catalog.d.ts +41 -0
- package/dist/database/introspect/catalog.d.ts.map +1 -0
- package/dist/database/introspect/index.d.ts +5 -0
- package/dist/database/introspect/index.d.ts.map +1 -0
- package/dist/database/introspect/mysql.d.ts +4 -0
- package/dist/database/introspect/mysql.d.ts.map +1 -0
- package/dist/database/introspect/postgres.d.ts +4 -0
- package/dist/database/introspect/postgres.d.ts.map +1 -0
- package/dist/database/introspect/sqlite.d.ts +4 -0
- package/dist/database/introspect/sqlite.d.ts.map +1 -0
- package/dist/database/introspect/types.d.ts +55 -0
- package/dist/database/introspect/types.d.ts.map +1 -0
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +2 -2
- package/dist/facades/Auth.d.ts +15 -0
- package/dist/facades/Auth.d.ts.map +1 -1
- package/dist/facades/Cookie.d.ts +1 -1
- package/dist/facades/Cookie.d.ts.map +1 -1
- package/dist/facades/DB.d.ts +3 -0
- package/dist/facades/DB.d.ts.map +1 -1
- package/dist/facades/Redirect.d.ts.map +1 -1
- package/dist/facades/Url.d.ts +8 -0
- package/dist/facades/Url.d.ts.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/Application.d.ts +36 -0
- package/dist/foundation/Application.d.ts.map +1 -1
- package/dist/foundation/index.d.ts +1 -1
- package/dist/foundation/index.d.ts.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/AuthenticationMiddlware.d.ts +14 -2
- package/dist/http/AuthenticationMiddlware.d.ts.map +1 -1
- package/dist/http/Error.d.ts +6 -0
- package/dist/http/Error.d.ts.map +1 -1
- package/dist/http/HttpRequest.d.ts +10 -1
- package/dist/http/HttpRequest.d.ts.map +1 -1
- package/dist/http/errors.d.ts +28 -16
- package/dist/http/errors.d.ts.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/http/middleware-config.d.ts +10 -1
- package/dist/http/middleware-config.d.ts.map +1 -1
- package/dist/http/requestContext.d.ts +18 -2
- package/dist/http/requestContext.d.ts.map +1 -1
- package/dist/http/requestDomain.d.ts +5 -0
- package/dist/http/requestDomain.d.ts.map +1 -0
- package/dist/i18n/Translator.d.ts.map +1 -1
- package/dist/i18n/defineDictionary.d.ts +4 -2
- package/dist/i18n/defineDictionary.d.ts.map +1 -1
- package/dist/i18n/dictionaryRegistry.d.ts +18 -1
- package/dist/i18n/dictionaryRegistry.d.ts.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/i18n/resolveLocale.d.ts +12 -0
- package/dist/i18n/resolveLocale.d.ts.map +1 -0
- package/dist/kernel/Kernel.d.ts +14 -1
- package/dist/kernel/Kernel.d.ts.map +1 -1
- package/dist/kernel/index.js +3 -3
- package/dist/kernel/index.js.map +5 -4
- package/dist/orm/compile/unique.d.ts +1 -1
- package/dist/orm/context.d.ts +35 -0
- package/dist/orm/context.d.ts.map +1 -1
- package/dist/orm/dialect/postgres.d.ts.map +1 -1
- package/dist/orm/fixtures.d.ts +1 -1
- package/dist/orm/index.d.ts +1 -1
- package/dist/orm/index.d.ts.map +1 -1
- package/dist/orm/index.js +3 -3
- package/dist/orm/index.js.map +5 -5
- package/dist/server/Server.d.ts +27 -1
- package/dist/server/Server.d.ts.map +1 -1
- package/dist/server/devFetch.d.ts +46 -0
- package/dist/server/devFetch.d.ts.map +1 -0
- package/dist/server/httpDev.d.ts +1 -22
- package/dist/server/httpDev.d.ts.map +1 -1
- package/dist/server/httpProd.d.ts.map +1 -1
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +3 -3
- package/dist/server/modulePreloads.d.ts +4 -2
- package/dist/server/modulePreloads.d.ts.map +1 -1
- package/dist/server/shutdown.d.ts +142 -0
- package/dist/server/shutdown.d.ts.map +1 -0
- package/dist/server/staticAssetMiss.d.ts +36 -0
- package/dist/server/staticAssetMiss.d.ts.map +1 -0
- package/dist/services/cron/ScheduleServiceProvider.d.ts +18 -0
- package/dist/services/cron/ScheduleServiceProvider.d.ts.map +1 -1
- package/dist/services/cron/Scheduler.d.ts +54 -0
- package/dist/services/cron/Scheduler.d.ts.map +1 -1
- package/dist/services/events/EventManager.d.ts +1 -1
- package/dist/services/events/EventManager.d.ts.map +1 -1
- package/dist/services/events/Listener.d.ts +8 -0
- package/dist/services/events/Listener.d.ts.map +1 -1
- package/dist/services/events/listenerJob.d.ts +1 -1
- package/dist/services/events/listenerJob.d.ts.map +1 -1
- package/dist/services/index.d.ts +4 -1
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +9 -9
- package/dist/services/index.js.map +4 -4
- package/dist/services/middleware/MiddlewareRegistry.d.ts +17 -0
- package/dist/services/middleware/MiddlewareRegistry.d.ts.map +1 -1
- package/dist/services/middleware/MiddlewareServiceProvider.d.ts +1 -0
- package/dist/services/middleware/MiddlewareServiceProvider.d.ts.map +1 -1
- package/dist/services/queue/DatabaseQueueDriver.d.ts +253 -0
- package/dist/services/queue/DatabaseQueueDriver.d.ts.map +1 -0
- package/dist/services/queue/Job.d.ts +17 -1
- package/dist/services/queue/Job.d.ts.map +1 -1
- package/dist/services/queue/MemoryQueueDriver.d.ts +57 -0
- package/dist/services/queue/MemoryQueueDriver.d.ts.map +1 -0
- package/dist/services/queue/QueueDriver.d.ts +199 -0
- package/dist/services/queue/QueueDriver.d.ts.map +1 -0
- package/dist/services/queue/QueueManager.d.ts +236 -14
- package/dist/services/queue/QueueManager.d.ts.map +1 -1
- package/dist/services/queue/QueueServiceProvider.d.ts +47 -0
- package/dist/services/queue/QueueServiceProvider.d.ts.map +1 -1
- package/dist/services/queue/WorkerProcess.d.ts +69 -0
- package/dist/services/queue/WorkerProcess.d.ts.map +1 -0
- package/dist/services/queue/config.d.ts +68 -2
- package/dist/services/queue/config.d.ts.map +1 -1
- package/dist/services/queue/queueDriverContract.d.ts +42 -0
- package/dist/services/queue/queueDriverContract.d.ts.map +1 -0
- package/dist/services/queue/work.d.ts +2 -0
- package/dist/services/queue/work.d.ts.map +1 -0
- package/dist/services/queue/work.js +4 -0
- package/dist/services/queue/work.js.map +11 -0
- package/dist/services/router/ApiRouteDispatcher.d.ts +24 -7
- package/dist/services/router/ApiRouteDispatcher.d.ts.map +1 -1
- package/dist/services/router/DomainResolver.d.ts +73 -0
- package/dist/services/router/DomainResolver.d.ts.map +1 -0
- package/dist/services/router/DomainRouter.d.ts +59 -0
- package/dist/services/router/DomainRouter.d.ts.map +1 -0
- package/dist/services/router/RouteServiceProvider.d.ts +1 -1
- package/dist/services/router/RouteServiceProvider.d.ts.map +1 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts +20 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
- package/dist/services/router/config.d.ts +78 -0
- package/dist/services/router/config.d.ts.map +1 -1
- package/dist/services/router/globalMiddleware.d.ts +46 -0
- package/dist/services/router/globalMiddleware.d.ts.map +1 -0
- package/dist/services/router/serverQueryFetcher.d.ts.map +1 -1
- package/dist/support/ServiceProvider.d.ts +22 -3
- package/dist/support/ServiceProvider.d.ts.map +1 -1
- package/dist/support/discover.d.ts +2 -2
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +2 -2
- package/dist/testing/Page.d.ts +17 -0
- package/dist/testing/Page.d.ts.map +1 -1
- package/dist/testing/index.js +16 -3
- package/dist/testing/index.js.map +1 -1
- package/dist/utils/domainUrl.d.ts +25 -0
- package/dist/utils/domainUrl.d.ts.map +1 -0
- package/dist/utils/intendedUrl.d.ts +43 -0
- package/dist/utils/intendedUrl.d.ts.map +1 -0
- package/dist/vite/index.mjs +83 -2
- package/package.json +2 -1
- package/skills/gemi-react-best-practices/SKILL.md +1 -1
- package/skills/gemi-react-best-practices/rules/orm-transaction-no-io.md +2 -1
- package/skills/gemi-react-best-practices/rules/routing-middleware-dsl.md +5 -0
- package/skills/gemi-react-best-practices/rules/service-queue-is-in-memory.md +13 -4
- package/dist/chunk-1mf5vw0z.js +0 -37
- package/dist/chunk-2nq2006q.js +0 -5
- package/dist/chunk-2nq2006q.js.map +0 -10
- package/dist/chunk-35p0gqmf.js +0 -6
- package/dist/chunk-607j9dy9.js +0 -5
- package/dist/chunk-607j9dy9.js.map +0 -16
- package/dist/chunk-68wejdfc.js +0 -5
- package/dist/chunk-68wejdfc.js.map +0 -10
- package/dist/chunk-78fnykzh.js +0 -5
- package/dist/chunk-78fnykzh.js.map +0 -11
- package/dist/chunk-81se9gak.js +0 -6
- package/dist/chunk-995b5wsd.js +0 -5
- package/dist/chunk-995b5wsd.js.map +0 -17
- package/dist/chunk-9vj9b31s.js +0 -24
- package/dist/chunk-9vj9b31s.js.map +0 -15
- package/dist/chunk-as2dbney.js +0 -19
- package/dist/chunk-as2dbney.js.map +0 -60
- package/dist/chunk-f51yvjvr.js +0 -5
- package/dist/chunk-f51yvjvr.js.map +0 -11
- package/dist/chunk-fxnzvbf1.js +0 -50
- package/dist/chunk-fxnzvbf1.js.map +0 -10
- package/dist/chunk-gs99rnym.js +0 -5
- package/dist/chunk-gs99rnym.js.map +0 -13
- package/dist/chunk-kj5xryzy.js +0 -9
- package/dist/chunk-kpy138e2.js.map +0 -10
- package/dist/chunk-njrjnkab.js +0 -5
- package/dist/chunk-nmrynp02.js +0 -4
- package/dist/chunk-nmrynp02.js.map +0 -10
- package/dist/chunk-pspydm8f.js +0 -9
- package/dist/chunk-pspydm8f.js.map +0 -12
- package/dist/chunk-v7y8zm61.js +0 -17
- package/dist/chunk-w9zbaxc2.js +0 -5
- package/dist/chunk-w9zbaxc2.js.map +0 -10
- package/dist/chunk-wchrcptd.js +0 -4
- package/dist/chunk-wchrcptd.js.map +0 -34
- package/dist/chunk-xm7rva5w.js +0 -55
- package/dist/chunk-xm7rva5w.js.map +0 -11
- package/dist/chunk-xth9vh46.js.map +0 -10
- package/dist/chunk-zq2v9fgf.js +0 -5
- package/dist/chunks/ThemeProvider-BZ2SsSZ3.js.map +0 -1
- /package/dist/{chunk-jg6vmate.js.map → chunk-rj3fnc4h.js.map} +0 -0
- /package/dist/{chunk-92j4tjjx.js.map → chunk-z2fnf49p.js.map} +0 -0
|
@@ -221,6 +221,41 @@ export declare abstract class AgentController<A extends AnyAgent = AnyAgent> ext
|
|
|
221
221
|
/** Appended to the agent's static instructions for this request — the user's
|
|
222
222
|
* name, tenant, today's date. */
|
|
223
223
|
instructions(req: HttpRequest<any, any>): string | Promise<string> | void;
|
|
224
|
+
/**
|
|
225
|
+
* Refuse a turn that arrives without a `threadId`, with a 400
|
|
226
|
+
* `thread_required`, before anything runs.
|
|
227
|
+
*
|
|
228
|
+
* A stateless turn is otherwise open to any caller the route's middleware
|
|
229
|
+
* lets through: the client carries the history, so the model runs, and is
|
|
230
|
+
* billed, as a general-purpose chat. An app whose tools resolve their subject
|
|
231
|
+
* from the thread can make them refuse such a turn, but the model has still
|
|
232
|
+
* been paid for by then.
|
|
233
|
+
*
|
|
234
|
+
* It governs `stream` only. `upload` can still reach the provider without a
|
|
235
|
+
* thread (a `provider` destination); refuse that in `authorizeRequest`.
|
|
236
|
+
*/
|
|
237
|
+
protected requireThread: boolean;
|
|
238
|
+
/**
|
|
239
|
+
* Decides whether this caller may use this route, on every one of the four:
|
|
240
|
+
* `stream`, `attach`, `stop` and `upload` (#542). Throw a request breaker
|
|
241
|
+
* (`InsufficientPermissionsError`, say) to refuse; return to let it through.
|
|
242
|
+
*
|
|
243
|
+
* It runs before the route does any work of its own: on `stream`, ahead of
|
|
244
|
+
* the thread's lock and load, `instructions()` and the provider, so a refused
|
|
245
|
+
* turn is not charged for, waits behind no run and does not learn whether its
|
|
246
|
+
* thread exists; on `attach`, before a live run's frames are read.
|
|
247
|
+
*
|
|
248
|
+
* `threadId` is the one the client sent, taken on trust and not yet checked
|
|
249
|
+
* against the store — which is what makes this the place to check that the
|
|
250
|
+
* caller owns it. A thread-scoped app that checks it here on every route
|
|
251
|
+
* keeps a thread's live answer, its stop button and its attachments to its
|
|
252
|
+
* owner. It is `undefined` when the request names no thread: a stateless
|
|
253
|
+
* turn, an upload without one, a stop by `runId` or `clientRunId`.
|
|
254
|
+
*/
|
|
255
|
+
protected authorizeRequest(req: HttpRequest<any, any>, params: {
|
|
256
|
+
route: "stream" | "attach" | "stop" | "upload";
|
|
257
|
+
threadId?: string;
|
|
258
|
+
}): void | Promise<void>;
|
|
224
259
|
/**
|
|
225
260
|
* `POST /<path>` — one route for every client turn. A first message, an
|
|
226
261
|
* approval, an answer to a question and a client tool's result are all just
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AgentController.d.ts","sourceRoot":"","sources":["../../ai/AgentController.ts"],"names":[],"mappings":"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
|
|
1
|
+
{"version":3,"file":"AgentController.d.ts","sourceRoot":"","sources":["../../ai/AgentController.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,KAAK,EAAE,QAAQ,EAAE,cAAc,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAChF,OAAO,EAGL,KAAK,qBAAqB,EAE1B,KAAK,eAAe,EACpB,KAAK,iBAAiB,EACtB,KAAK,eAAe,EAGpB,iBAAiB,EAClB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,uBAAuB,EACvB,QAAQ,IAAI,eAAe,EAC3B,oBAAoB,EACpB,cAAc,EACf,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAE/E,OAAO,KAAK,EACV,UAAU,EACV,YAAY,EAGZ,eAAe,EACf,UAAU,EACX,MAAM,SAAS,CAAC;AAIjB;;;;;;;;GAQG;AACH,MAAM,WAAW,UAAU;IACzB;;;;;;;;OAQG;IACH,YAAY,CAAC,MAAM,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAClF;;;;;;;;;;OAUG;IACH,UAAU,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,EAAE,GAAG,IAAI,CAAC,CAAC;IAC7D;;;;;;;;;;;;OAYG;IACH,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3E;AAED,8DAA8D;AAC9D,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,CAAC;AAE/C,yEAAyE;AACzE,OAAO,EACL,KAAK,UAAU,EACf,KAAK,qBAAqB,EAC1B,uBAAuB,EACvB,KAAK,eAAe,EACpB,KAAK,iBAAiB,EACtB,KAAK,eAAe,EACpB,sBAAsB,EACtB,2BAA2B,EAC3B,qBAAqB,EACrB,KAAK,mBAAmB,EACxB,iBAAiB,EACjB,KAAK,iBAAiB,EACtB,KAAK,oBAAoB,EACzB,KAAK,eAAe,GACrB,MAAM,qBAAqB,CAAC;AAE7B;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,WAAW,QAAQ;IACvB,0EAA0E;IAC1E,IAAI,CAAC,MAAM,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC,CAAC;IACnF,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,QAAQ,GAAG,IAAI,CAAC;IACpC;oDACgD;IAChD,KAAK,EAAE,MAAM,CAAC;CACf;AAED,OAAO,EACL,uBAAuB,EACvB,oBAAoB,EACpB,cAAc,EACd,eAAe,IAAI,QAAQ,GAC5B,CAAC;AAIF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,GAAG,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB,kFAAkF;IAClF,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,mFAAmF;IACnF,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,qBAAqB,CAAC;IACnC;;;;;;;;;OASG;IACH,UAAU,CAAC,EAAE,UAAU,CAAC;CACzB,CAAC;AAEF;;;;;;GAMG;AACH,QAAA,MAAM,cAAc,EAAiB,UAAU,UAAU,CAAC;AA+B1D,8BAAsB,eAAe,CAAC,CAAC,SAAS,QAAQ,GAAG,QAAQ,CAAE,SAAQ,cAAc;IACzF,MAAM,CAAC,IAAI,EAAG,kBAAkB,CAAU;IAE1C;;6CAEyC;IACzC,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC;IAElB;;;;;;;;OAQG;IACH,KAAK,EAAE,UAAU,CAAqB;IAEtC;;;;;OAKG;IACH,QAAQ,EAAE,cAAc,CAAmB;IAE3C;;;;;OAKG;IACH,WAAW,EAAE,eAAe,CAA0B;IAEtD;;;;;;;;OAQG;IACH,iBAAiB,EAAE,iBAAiB,CAAW;IAE/C;;;;;;;;;;;;;;;;OAgBG;IACH,SAAS,CAAC,UAAU,SAAU;IAE9B;sCACkC;IAClC,YAAY,CAAC,GAAG,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,IAAI;IAIzE;;;;;;;;;;;;OAYG;IACH,SAAS,CAAC,aAAa,UAAS;IAEhC;;;;;;;;;;;;;;;;OAgBG;IACH,SAAS,CAAC,gBAAgB,CACxB,GAAG,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,CAAC,EAC1B,MAAM,EAAE;QAAE,KAAK,EAAE,QAAQ,GAAG,QAAQ,GAAG,MAAM,GAAG,QAAQ,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,GAC5E,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvB;;;;OAIG;IACG,MAAM,CAAC,GAAG,GAAE,WAAW,CAAC,GAAG,EAAE,GAAG,CAAqB,GAAG,OAAO,CAAC,QAAQ,CAAC;IAgK/E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAkCG;YACW,UAAU;IA2BxB;;;;;;;;;;OAUG;IACG,MAAM,CAAC,GAAG,GAAE,WAAW,CAAC,GAAG,EAAE,GAAG,CAAqB,GAAG,OAAO,CAAC,QAAQ,CAAC;IAuE/E;;;;;;;;;;;;;;OAcG;IACG,IAAI,CACR,GAAG,GAAE,WAAW,CAAC,GAAG,EAAE,GAAG,CAAqB,GAC7C,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,GAAG,QAAQ,CAAC;IA0D3C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA8DG;IACH,SAAS,CAAC,eAAe,CACvB,GAAG,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,CAAC,EAC1B,QAAQ,CAAC,EAAE,MAAM,GAChB,eAAe,GAAG,IAAI,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;IAY3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAiCG;IACH,SAAS,CAAC,qBAAqB,CAC7B,IAAI,EAAE,IAAI,EACV,GAAG,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,CAAC,GACzB,qBAAqB,GAAG,OAAO,CAAC,qBAAqB,CAAC;IAMzD;;;;;;;;OAQG;cACa,cAAc,CAC5B,GAAG,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,CAAC,EAC1B,QAAQ,CAAC,EAAE,MAAM,GAChB,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC;IAQpC;;;;;;;;;;;;;;;;;;;;;;;;;OAyBG;IACG,MAAM,CAAC,GAAG,GAAE,WAAW,CAAC,GAAG,EAAE,GAAG,CAAqB,GAAG,OAAO,CAAC,YAAY,CAAC;IA2GnF;;;;;;;;;OASG;IACH,SAAS,CAAC,SAAS,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,EAAE,gBAAgB,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvF,SAAS,CAAC,UAAU,CAClB,IAAI,EAAE;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,EAC1D,GAAG,EAAE,gBAAgB,GACpB,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvB;0EACsE;IACtE,SAAS,CAAC,eAAe,CACvB,OAAO,EAAE,eAAe,EAAE,EAC1B,GAAG,EAAE,gBAAgB,GACpB,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvB,SAAS,CAAC,OAAO,CAAC,KAAK,EAAE,UAAU,EAAE,GAAG,EAAE,gBAAgB,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAKjF,SAAS,CAAC,gBAAgB,CACxB,MAAM,EAAE,cAAc,CAAC,YAAY,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,EAAE,GAAG,CAAC,EACrD,GAAG,EAAE,gBAAgB,GACpB,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvB;;;;;;;;;;;;;;OAcG;IACH,SAAS,CAAC,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI;YAInC,aAAa;IA+B3B;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACH,OAAO,CAAC,UAAU;IAsDlB,0EAA0E;YAC5D,SAAS;YAYT,MAAM;CAOrB;AAwXD,MAAM,MAAM,gBAAgB,GAAG,QAAQ,GAAG,QAAQ,GAAG,MAAM,GAAG,QAAQ,CAAC;AAEvE,MAAM,MAAM,qBAAqB,GAAG,OAAO,CAAC,MAAM,CAAC,gBAAgB,EAAE,eAAe,CAAC,CAAC,CAAC;AAEvF,MAAM,MAAM,UAAU,CAAC,CAAC,SAAS,UAAU,eAAe,CAAC,GAAG,CAAC,IAAI;IACjE,gBAAgB,EAAE,YAAY,CAAC;IAC/B,UAAU,EAAE,CAAC,CAAC;IACd,UAAU,CAAC,MAAM,EAAE,qBAAqB,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;CAC1D,CAAC;AAEF;6EAC6E;AAC7E,MAAM,MAAM,aAAa,CAAC,CAAC,SAAS,UAAU,eAAe,CAAC,GAAG,CAAC,IAAI;IACpE,OAAO,EAAE,IAAI,CAAC;IACd,KAAK,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,QAAQ,GAC5C,YAAY,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,GAC/C,UAAU,CAAC;IACf,MAAM,EAAE,OAAO,CAAC;CACjB,CAAC"}
|
package/dist/ai/index.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Ib as v5}from"../chunk-4728yrmt.js";import{Be as S2,Se as g,df as R2}from"../chunk-0amv13g6.js";import"../chunk-9k5daets.js";import"../chunk-7hbhbht2.js";import"../chunk-jk8mn861.js";import"../chunk-wqmzad46.js";import"../chunk-ptjexzn1.js";import{createHmac as k2,randomBytes as wQ,timingSafeEqual as bQ}from"crypto";var VQ="agt1",vQ=86400000;function c(Q){let $=Q??process.env.SECRET;if(!$)throw Error("Signing a pending tool call needs an app secret. Set SECRET in the environment.");return $}function P(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(P).join(",")}]`;let $=Q;return`{${Object.keys($).filter((G)=>$[G]!==void 0).sort().map((G)=>`${JSON.stringify(G)}:${P($[G])}`).join(",")}}`}function E2(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function m(Q,$){return k2("sha256",Q).update(E2($)).digest()}function fQ(Q,$,Z){let G=[VQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),P(Q.input)];if(Q.path&&Q.path.length>0)G.push(P(Q.path));return G}var hQ=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),x2=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function yQ(Q,$={}){let Z=c($.secret),J=($.now??Date.now())+($.ttlMs??vQ),Y=wQ(12).toString("base64url"),W=m(Z,fQ(Q,Y,J)).toString("base64url");return[VQ,hQ(Q.runId),Y,J.toString(36),W].join(".")}function p(Q){return XQ(Q,VQ)}function XQ(Q,$){let Z=Q.split(".");if(Z.length!==5||Z[0]!==$)return null;let G=Number.parseInt(Z[3],36);if(!Number.isFinite(G))return null;try{return{runId:x2(Z[1]),nonce:Z[2],expiresAt:G}}catch{return null}}function gQ(Q,$,Z={}){let G=c(Z.secret),J=p(Q);if(!J)return{ok:!1,reason:"malformed"};let Y=Buffer.from(Q.split(".")[4],"base64url"),W=m(G,fQ($,J.nonce,J.expiresAt));if(Y.length!==W.length||!bQ(Y,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 i="agn1";function uQ(Q,$,Z){return[i,Q.runId,P(Q.path),Q.nestedRunId,$,String(Z),P([...Q.open].sort()),P(Q.input)]}function cQ(Q,$={}){let Z=c($.secret),J=($.now??Date.now())+($.ttlMs??vQ),Y=wQ(12).toString("base64url"),W=m(Z,uQ(Q,Y,J)).toString("base64url");return[i,hQ(Q.runId),Y,J.toString(36),W].join(".")}function mQ(Q,$,Z={}){let G=c(Z.secret),J=XQ(Q,i);if(!J)return{ok:!1,reason:"malformed"};let Y=Buffer.from(Q.split(".")[4],"base64url"),W=m(G,uQ({...$,runId:J.runId},J.nonce,J.expiresAt));if(Y.length!==W.length||!bQ(Y,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 E=new Map,pQ=1024;function A2(Q){for(let[$,Z]of E)if(Z<=Q)E.delete($);pQ=Math.max(1024,E.size*2)}function iQ(Q,$={}){return dQ(p(Q),$)}function lQ(Q,$={}){return dQ(XQ(Q,i),$)}function dQ(Q,$){if(!Q)return!1;let Z=$.now??Date.now();if(E.size>=pQ)A2(Z);let G=E.get(Q.nonce);if(G!==void 0&&G>Z)return!1;return E.set(Q.nonce,Q.expiresAt),!0}class v extends Error{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class x extends Error{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function BQ(Q){if(!Q||typeof Q.key!=="string"||Q.key.length===0)throw new x("An attachment scope needs a non-empty key. Return `null` from `attachmentScope()` for a request that has no subject \u2014 an empty key is a bucket every caller shares.");return Q}var C="gemi_att_";function KQ(){return`${C}${crypto.randomUUID()}`}class f{store;storage;scope;constructor(Q,$,Z){this.store=Q;this.storage=$;this.scope=Z;BQ(Z)}async get(Q){let $=await this.store.find(this.scope,Q);if(!$||$.scopeKey!==this.scope.key)throw new v(Q);return $}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,$){if(!$.objectName)throw new v(Q);return await this.storage.read({name:$.objectName})}async file(Q){let $=await this.get(Q),G=(await this.readRecord(Q,$)).body,J=G instanceof Blob?G:G?await new Response(G).blob():new Blob([]);return new File([J],$.name,{type:$.mimeType})}async put(Q,$={}){let Z=KQ(),G=$.mimeType??Q.type??"",J=$.name??(Q instanceof File?Q.name:Z),Y=await this.storage.put({name:HQ(Z,J),body:Q,contentType:G||void 0}),W={id:Z,scopeKey:this.scope.key,objectName:Y,name:J,mimeType:G||"application/octet-stream",size:Q.size,createdAt:new Date().toISOString(),destination:$.fileId?"both":"storage",...$.fileId?{fileId:$.fileId}:{}};return await this.store.put(this.scope,W),W}}function HQ(Q,$){let Z=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Q}${Z?`.${Z[1].toLowerCase()}`:""}`}class l{rows=new Map;async put(Q,$){BQ(Q),this.rows.set($.id,{...$,scopeKey:Q.key})}async find(Q,$){BQ(Q);let Z=this.rows.get($);if(!Z||Z.scopeKey!==Q.key)return null;return Z}get size(){return this.rows.size}}var d=new l;var zQ=new TextEncoder;function nQ(Q){return`id: ${Q.seq}
|
|
3
3
|
data: ${JSON.stringify(Q.event)}
|
|
4
4
|
|
|
5
|
-
`}var
|
|
5
|
+
`}var I2=5000,w2=`: keepalive
|
|
6
6
|
|
|
7
|
-
`;function UQ(Q,$=
|
|
8
|
-
${await
|
|
7
|
+
`;function UQ(Q,$=I2){let Z=null,G=!1,J=()=>{if(G)return;if(Z!==null)clearTimeout(Z);Z=setTimeout(()=>{if(Z=null,G)return;try{Q.enqueue(zQ.encode(w2))}catch{Y();return}J()},$)},Y=()=>{if(G=!0,Z!==null)clearTimeout(Z);Z=null};return J(),{touch:J,stop:Y}}function b2(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function oQ(Q,$=200){let Z=Q[Symbol.asyncIterator](),G=-1,J,Y=new ReadableStream({start(W){J=UQ(W)},async pull(W){try{let V=await Z.next();if(V.done){J.stop(),W.close();return}G=V.value.seq,W.enqueue(zQ.encode(nQ(V.value))),J.touch()}catch(V){let X={type:"error",error:v2(V)};J.stop(),W.enqueue(zQ.encode(nQ({seq:G+1,event:X}))),W.close()}},cancel(W){J.stop(),Z.return?.(W)}});return new Response(Y,{status:$,headers:b2()})}function v2(Q){return{code:"unknown",message:Q instanceof Error?Q.message:String(Q),retryable:!1}}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 S{name;description;inputSchema;outputSchema;requiresApproval;deferred;answeredBy;execute;constructor(Q){this.name=Q.name,this.description=Q.description,this.inputSchema=Q.inputSchema,this.outputSchema=Q.outputSchema,this.requiresApproval=Q.requiresApproval===!0,this.deferred=Q.deferred===!0,this.answeredBy=Q.answeredBy==="client"?"client":"server",this.execute=Q.execute??void 0}static create(Q){return new S(Q)}static ask(Q){return S.create({name:Q.name,description:Q.description,inputSchema:LQ,outputSchema:Q.outputSchema,answeredBy:"client"})}}var LQ={toJSONSchema:()=>({type:"object",properties:{question:{type:"string",description:"What to ask the user"}},required:["question"],additionalProperties:!1}),parse(Q){let $=LQ.safeParse(Q);if($.ok===!1)throw Error($.errors.join(", "));return $.value},safeParse(Q){if(typeof Q!=="object"||Q===null||typeof Q.question!=="string")return{ok:!1,errors:["question: expected a string"]};return{ok:!0,value:{question:Q.question}}}};class t{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 t(Q)}}class FQ{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 FQ(Q)}}var h="skills",f2="Instructions this agent can load on demand. Load the relevant one before acting in the area it covers.",J2={type:"object",properties:{},required:[],additionalProperties:!1},h2=8,y2=3;class CQ{name;tools;skills;provider;output;instructions;maxSteps;maxDepth;reasoning;config;constructor(Q){this.name=Q.name,this.instructions=Q.instructions,this.provider=Q.provider,this.tools=Q.tools??[],this.skills=Q.skills??[],this.output=Q.output,this.maxSteps=Q.maxSteps??h2,this.maxDepth=Q.maxDepth??y2,this.reasoning=Q.reasoning;let{registry:$,providerTools:Z}=g2(this.tools,this.skills);this.config={name:this.name,instructions:this.instructions,provider:this.provider,registry:$,providerTools:Z,output:Q.output,maxSteps:this.maxSteps,maxDepth:this.maxDepth,reasoning:this.reasoning}}static create(Q){return new CQ(Q)}stream(Q){let $={...this.config,provider:Q.provider??this.config.provider,maxSteps:Q.maxSteps??this.config.maxSteps,reasoning:Q.reasoning??this.config.reasoning};return new W2($,Q)}}function sQ(Q){return{name:Q.tool.name,description:Q.tool.description,parameters:Q.tool.inputSchema.toJSONSchema(),strict:!0,deferred:Q.deferred}}function g2(Q,$){let Z=new Map,G=[],J=(Y)=>{if(Z.has(Y.tool.name))throw Error(`Two tools are named "${Y.tool.name}". Tool names are global within an agent \u2014 the client discriminates a tool part by name alone.`);Z.set(Y.tool.name,Y)};for(let Y of Q){if(Y instanceof t){if(Y.name===h)throw Error(`"${h}" is reserved for the namespace skills are lowered into. Rename the namespace \u2014 silently shadowing it would make every skill unreachable with no error to read.`);let V=[];for(let X of Y.tools){let B={tool:X,namespace:Y.name,deferred:Y.deferred||X.deferred};J(B),V.push(sQ(B))}G.push({name:Y.name,description:Y.description,tools:V});continue}let W={tool:Y,deferred:Y.deferred};J(W),G.push(sQ(W))}if($.length>0){let Y=[];for(let W of $){let V=u2(W);J({tool:V,namespace:h,deferred:!1}),Y.push({name:W.name,description:W.description,parameters:J2,strict:!0,deferred:!1})}G.push({name:h,description:f2,tools:Y})}return{registry:Z,providerTools:G}}function u2(Q){return S.create({name:Q.name,description:Q.description,inputSchema:{toJSONSchema:()=>J2,parse:()=>({}),safeParse:()=>({ok:!0,value:{}})},execute:async()=>{let Z=[typeof Q.instructions==="function"?await Q.instructions():Q.instructions];for(let G of Q.files??[])Z.push(`--- ${G} ---
|
|
8
|
+
${await c2(G)}`);return Z.join(`
|
|
9
9
|
|
|
10
|
-
`)}})}async function
|
|
10
|
+
`)}})}async function c2(Q){try{return await Bun.file(Q).text()}catch($){return`(could not be read: ${$.message})`}}class q extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function n(Q,$){if($.aborted)return Promise.reject(new q);return new Promise((Z,G)=>{let J=()=>G(new q);$.addEventListener("abort",J,{once:!0}),Q.then(Z,G).finally(()=>$.removeEventListener("abort",J))})}function o(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function DQ(Q,$){if(!$)return Q;let Z={inputTokens:Q.inputTokens+($.inputTokens??0),outputTokens:Q.outputTokens+($.outputTokens??0),totalTokens:Q.totalTokens+($.totalTokens??0)};if($.reasoningTokens!==void 0||Q.reasoningTokens!==void 0)Z.reasoningTokens=(Q.reasoningTokens??0)+($.reasoningTokens??0);if($.cachedInputTokens!==void 0||Q.cachedInputTokens!==void 0)Z.cachedInputTokens=(Q.cachedInputTokens??0)+($.cachedInputTokens??0);return Z}function m2(Q){return typeof Q==="object"&&Q!==null&&typeof Q.next==="function"&&Symbol.asyncIterator in Q}function OQ(Q){if(!Q.trim())return{};try{return JSON.parse(Q)}catch{}let $=[],Z=!1,G=!1;for(let W of Q){if(Z){if(G)G=!1;else if(W==="\\")G=!0;else if(W==='"')Z=!1;continue}if(W==='"')Z=!0;else if(W==="{")$.push("}");else if(W==="[")$.push("]");else if(W==="}"||W==="]")$.pop()}let J=Q;if(Z)J+='"';J=J.replace(/[,:]\s*$/,"");let Y=$.reverse().join("");try{return JSON.parse(J+Y)}catch{try{return JSON.parse(J.replace(/,?\s*"[^"]*"\s*$/,"")+Y)}catch{return{}}}}function tQ(Q,$){let Z=[...Q],G=new Map(Z.map((J,Y)=>[J.id,Y]));for(let J of $){let Y=G.get(J.id);if(Y===void 0)G.set(J.id,Z.length),Z.push(J);else Z[Y]=J}return Z}function s(Q){let $=new Set;for(let G of Q)for(let J of G.content)if(J.type==="tool-result")$.add(J.toolCallId);let Z=new Set;for(let G of Q)for(let J of G.content)if(J.type==="tool-call"&&!$.has(J.toolCallId))Z.add(J.toolCallId);return Z}function aQ(Q){for(let $=Q.length-1;$>=0;$--){let Z=Q[$].content;for(let G=Z.length-1;G>=0;G--){let J=Z[G];if(J.type==="output"&&J.partial!==!0)return J.value}}return}function rQ(Q,$){return $===void 0?`"${Q}"`:`"${Q}" labelled "${$}"`}function Y2(Q){return Q.content.map(($)=>$.type==="text"?$.text:`<${$.type}>`).join("")}function p2(Q){if(Q.prompt!==void 0)return`user:${Q.prompt}`;let $=Q.messages?.[0];return $?`${$.role}:${Y2($)}`:null}function eQ(Q){let $=new Set;for(let Z of Q)for(let G of Z.content){if(G.type!=="tool-call")continue;for(let J of G.attachments??[])if("shown"in J&&J.shown)$.add(J.shown.messageId)}return $}var Q2=1;function i2(Q,$,Z){let G=Z.mimeType||$.type||"";if(G&&Q.attachment.mimeType!==G)return`was ${JSON.stringify(Q.attachment.mimeType)} on the turn that escalated and is ${JSON.stringify(G)} on the replay`;let J=Boolean(Z.showModel);if(J!==Boolean(Q.shown))return J?"was stored without showModel on the turn that escalated and asks for showModel on the replay":"was stored with showModel on the turn that escalated and asks for a plain put on the replay";return null}function l2(Q,$,Z){if(Q.agent!==$.name||Q.label!==Z.label)return`was ${rQ(Q.agent,Q.label)} on the turn that escalated and is ${rQ($.name,Z.label)} on the replay`;let G=p2(Z),J=Q.messages[0],Y=J?`${J.role}:${Y2(J)}`:null;if(G!==null&&Y!==null&&G!==Y)return`was started with ${JSON.stringify(Y)} on the turn that escalated and with ${JSON.stringify(G)} on the replay`;return null}function $2(Q,$){let Z=Q??[];if(Z.length<$.length)return null;for(let G=0;G<$.length;G++)if(Z[G]!==$[G])return null;return Z.slice($.length)}class jQ{read;create;fill;index=0;replayable;constructor(Q,$,Z){this.read=Q;this.create=$;this.fill=Z;this.replayable=Q()?.length??0}next(){let Q=this.index++;return{at:Q,recorded:Q<this.replayable?this.read()?.[Q]:void 0,write:($)=>{let Z=this.read()??this.create();if(this.fill)for(let G=Z.length;G<Q;G++)Z[G]=this.fill();Z[Q]=$}}}}class W2{runId;config;params;controller=new AbortController;buffer=[];waiters=new Set;seq=0;ended=!1;history=[];produced=[];current=null;amended=new Map;unreported=new Set;usage=o();finishReason="stop";output;stopReason;settled;depth;maxDepth;chain;signingRunId;pathPrefix;onPending;nestedSettling=new Set;shownQueue=new Map;constructor(Q,$){this.config=Q,this.params=$,this.runId=$.runId??`run_${crypto.randomUUID()}`,this.history=[...$.messages];let Z=$.nesting;if(this.depth=Z?.depth??0,this.maxDepth=Z?.maxDepth??Q.maxDepth,this.chain=Z?.chain??[Q.name],this.signingRunId=Z?.signingRunId??this.runId,this.pathPrefix=Z?.signingPath??[],this.onPending=Z?.onPending??"escalate",$.signal)if($.signal.aborted)this.controller.abort();else $.signal.addEventListener("abort",()=>this.stop(),{once:!0});this.settled=this.execute(),$.req?.ctx?.()?.waitUntil(this.settled)}emit(Q){if(this.ended)return;this.buffer.push({seq:++this.seq,event:Q}),this.wake()}wake(){let Q=[...this.waiters];this.waiters.clear();for(let $ of Q)$()}nextFrame(){return new Promise((Q)=>this.waiters.add(Q))}async*frames(Q=0){let $=Q>0?Q-1:0;for(;;){while($<this.buffer.length)yield this.buffer[$++];if(this.ended)return;await this.nextFrame()}}async*[Symbol.asyncIterator](){for await(let Q of this.frames())yield Q.event}toResponse(Q){let $=this.frames(Q?.from),Z=new TextEncoder,G=!1,J,Y=new ReadableStream({start:async(W)=>{J=UQ(W);try{for await(let V of $){if(G)break;W.enqueue(Z.encode(`id: ${V.seq}
|
|
11
11
|
data: ${JSON.stringify(V.event)}
|
|
12
12
|
|
|
13
|
-
`)),J.touch()}}catch{}J.stop();try{W.close()}catch{}},cancel:()=>{G=!0,J.stop()}});return new Response(Y,{headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}result(){return this.settled}stop(Q){if(this.ended||this.controller.signal.aborted)return;this.stopReason=Q?.reason,this.controller.abort()}async execute(){this.emit({type:"run-start",runId:this.runId,threadId:this.params.threadId});try{let Q=await this.ingestTurn();if(Q.length>0)this.finishReason="awaiting-input",this.emit({type:"awaiting-input",runId:this.runId,pending:Q});else await this.loop()}catch(Q){if(Q instanceof
|
|
13
|
+
`)),J.touch()}}catch{}J.stop();try{W.close()}catch{}},cancel:()=>{G=!0,J.stop()}});return new Response(Y,{headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}result(){return this.settled}stop(Q){if(this.ended||this.controller.signal.aborted)return;this.stopReason=Q?.reason,this.controller.abort()}async execute(){this.emit({type:"run-start",runId:this.runId,threadId:this.params.threadId});try{let Q=await this.ingestTurn();if(Q.length>0)this.finishReason="awaiting-input",this.emit({type:"awaiting-input",runId:this.runId,pending:Q});else await this.loop()}catch(Q){if(Q instanceof q||this.controller.signal.aborted)await this.finalizeAborted();else{let $=this.config.provider.normalizeError(Q);this.emit({type:"error",error:$}),await this.finalizeMessage("error"),this.finishReason="error"}}return this.emit({type:"usage",usage:this.usage}),this.emit({type:"run-end",runId:this.runId,finishReason:this.finishReason}),this.ended=!0,this.wake(),{runId:this.runId,messages:this.produced,finishReason:this.finishReason,usage:this.usage,output:this.output}}async loop(){let Q=Math.max(1,this.config.maxSteps);for(let $=1;$<=Q;$++){let Z=this.startMessage(),G=await this.runStep(Z);if(G.error){this.emit({type:"error",error:G.error}),await this.finalizeMessage("error"),this.finishReason="error";return}let J=Z.content.filter((W)=>W.type==="tool-call");if(J.length===0){this.finishReason=G.reason,await this.finalizeMessage(G.reason);return}let Y=await this.runTools(Z,J,$);if(Y.length>0){this.finishReason="awaiting-input",await this.finalizeMessage("awaiting-input"),this.emit({type:"awaiting-input",runId:this.runId,pending:Y});return}if($===Q){this.finishReason="max-steps",await this.finalizeMessage("max-steps");return}await this.finalizeMessage(G.reason)}}startMessage(){let Q={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()};return this.current=Q,this.history.push(Q),this.produced.push(Q),this.emit({type:"message-start",messageId:Q.id,role:"assistant"}),Q}async finalizeMessage(Q){let $=this.current;if(!$)return;this.current=null,$.finishReason=Q;for(let Z of $.content)if(Z.type==="text"||Z.type==="reasoning"){if(typeof Z.text==="string")Z.text=d2(Z.text)}this.emit({type:"message-end",messageId:$.id,finishReason:Q}),await this.report($),await this.reportDeferred()}async report(Q){if(!this.params.onMessage)return;try{await this.params.onMessage(Q)}catch{}}async runStep(Q){let $=this.controller.signal,Z=this.config.provider,G={reason:"stop"},J=new Map,Y="",V=Z.stream({messages:this.historyForProvider(Q),systemPrompt:await this.systemPrompt(),tools:this.config.providerTools.length>0?this.config.providerTools:void 0,output:this.config.output?{name:"output",schema:this.config.output.toJSONSchema()}:void 0,reasoning:this.config.reasoning,signal:$})[Symbol.asyncIterator]();for(;;){let X=await n(Promise.resolve(V.next()),$);if(X.done)break;let B=X.value;switch(B.type){case"text-delta":{n2(Q,"text",B.delta),this.emit({type:"text-delta",messageId:Q.id,delta:B.delta});break}case"reasoning-delta":{o2(Q,B.id,B.delta),this.emit({type:"reasoning-delta",messageId:Q.id,delta:B.delta,id:B.id});break}case"output-delta":{Y+=B.delta,this.emit({type:"output-delta",messageId:Q.id,delta:B.delta,snapshot:OQ(Y)});break}case"tool-search":{this.emit({type:"tool-search",loaded:B.loaded});break}case"tool-call-delta":{let K=J.get(B.toolCallId)??{name:B.name,args:""};K.args+=B.argsDelta,K.name=B.name||K.name,J.set(B.toolCallId,K),this.emit({type:"tool-call",messageId:Q.id,part:{type:"tool-call",toolCallId:B.toolCallId,name:K.name,input:OQ(K.args),partial:!0}});break}case"tool-call":{J.delete(B.toolCallId);let K={type:"tool-call",toolCallId:B.toolCallId,name:B.name,input:G2(B.args)};Q.content.push(K),this.emit({type:"tool-call",messageId:Q.id,part:K});break}case"finish":{if(this.usage=DQ(this.usage,B.usage),!G.error)G={reason:B.reason};break}case"error":{G={reason:"error",error:B.error};break}}}for(let[X,B]of J){let K={type:"tool-call",toolCallId:X,name:B.name,input:G2(B.args)};Q.content.push(K),this.emit({type:"tool-call",messageId:Q.id,part:K})}if(this.config.output&&Y&&!G.error){let X=this.config.output.safeParse(OQ(Y));if(X.ok===!0)this.output=X.value,Q.content.push({type:"output",value:X.value});else this.emit({type:"error",error:{code:"unknown",message:`The model's structured answer did not match the output schema: ${X.errors.join(", ")}`,retryable:!0}})}return G}async systemPrompt(){let Q=[this.config.instructions,this.params.instructions].filter(($)=>Boolean($&&$.trim()));return Q.length>0?Q.join(`
|
|
14
14
|
|
|
15
|
-
`):void 0}async runTools(Q,$,Z){let G=[],J=[];for(let Y of $){let W=this.config.registry.get(String(Y.name));if(!W){this.addResult(Q,{type:"tool-result",toolCallId:Y.toolCallId,name:Y.name,status:"error",error:{code:"tool_error",message:`There is no tool named "${String(Y.name)}".`,toolCallId:Y.toolCallId,retryable:!0}});continue}let V=W.tool.inputSchema.safeParse(Y.input);if(V.ok===!1){this.addResult(Q,{type:"tool-result",toolCallId:Y.toolCallId,name:Y.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${String(Y.name)}": ${V.errors.join(", ")}`,toolCallId:Y.toolCallId,retryable:!0}});continue}Y.input=V.value;let X=Z2(W.tool);if(X){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(Y));continue}G.push({toolCallId:Y.toolCallId,name:Y.name,input:V.value,kind:X,signature:yQ(this.claimsFor(Y.toolCallId,String(Y.name),X,V.value)),...this.pathPrefix.length>0?{path:[...this.pathPrefix]}:{}});continue}J.push(this.executeTool(W,Q.id,Y,V.value,Z).then(async(B)=>{this.addResult(Q,B),await this.settleShown(Y.toolCallId)}).catch((B)=>{if(B instanceof P){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(Y));return}G.push(...B.pending);return}}))}return await n(Promise.all(J).then(()=>{return}),this.controller.signal),G}claimsFor(Q,$,Z,G){return{runId:this.signingRunId,toolCallId:Q,name:$,kind:Z,input:G,path:this.pathPrefix.length>0?[...this.pathPrefix]:void 0}}deniedByPolicy(Q){return{type:"tool-result",toolCallId:Q.toolCallId,name:Q.name,status:"denied",cause:"refused",reason:`"${String(Q.name)}" needs the user, and this run was started with onPending: "deny". Answer from what you already have.`}}async executeTool(Q,$,Z,G,J,Y){let W={req:this.params.req,runId:this.runId,threadId:this.params.threadId,toolCallId:Z.toolCallId,signal:this.controller.signal,step:J,depth:this.depth,resumed:Y!==void 0,attachments:this.toolAttachments(Z),turn:this.toolTurn($),runAgent:this.nestedRunner($,Z,Y)};try{let V=Q.tool.execute(G,W),X;if(c2(V)){let B=await V.next();while(!B.done)this.emit({type:"tool-progress",toolCallId:Z.toolCallId,data:B.value}),B=await V.next();X=B.value}else X=await V;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"ok",output:X}}catch(V){if(V instanceof M||this.controller.signal.aborted)throw new M;if(V instanceof P)throw V;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:{code:"tool_error",message:V instanceof Error?V.message:String(V),toolCallId:Z.toolCallId,retryable:!0}}}}nestedRunner(Q,$,Z){let G=new jQ(()=>$.nested,()=>$.nested=[]);return async(J,Y={})=>{let{at:W,recorded:V,write:X}=G.next();if(V){let B=i2(V,J,Y);if(B)throw Error(`Nested run ${W} of "${String($.name)}" ${B}. `+"runAgent is memoized by call index, so a body whose runAgent calls depend on a condition that changed between turns cannot be resumed \u2014 the answer would be paired with a different sub-run. "+"Make the sequence of runAgent calls, and what each one is asked, the same every time this tool runs, or branch on ctx.resumed.");if(V.finishReason!=="awaiting-input")return{runId:V.runId,agent:V.agent,messages:V.messages,finishReason:V.finishReason??"stop",usage:V.usage??o(),output:aQ(V.messages),nested:V}}return this.runNested(Q,$,J,Y,X,V,Z?.answers??[])}}async runNested(Q,$,Z,G,J,Y,W){let V=[...this.chain,Z.name];if(this.chain.includes(Z.name))throw Error(`"${Z.name}" is already running further up this chain: ${V.join(" -> ")}. An agent cannot run itself, directly or through another agent.`);let X=this.depth+1;if(X>this.maxDepth)throw Error(`Nested agent runs are ${this.maxDepth} deep at most and this one would be ${X}: ${V.join(" -> ")}. Raise maxDepth on the agent at the root of the run if the tree is meant to be this deep.`);let B=G.label,K=[...this.pathPrefix,$.toolCallId],H=this.onPending==="deny"?"deny":G.onPending??"escalate",z=Y!==void 0,O=z?s(Y.messages):new Set,D=z?W.filter((F)=>{let k=$2(F.path,K);if(k===null)return!1;return O.has(k.length>0?k[0]:F.toolCallId)}):[],U=Z.stream({messages:z?Y.messages:G.messages??[],turn:z?{toolResults:D}:G.prompt?{text:G.prompt}:void 0,req:this.params.req,attachments:this.params.attachments,signal:this.controller.signal,threadId:this.params.threadId,instructions:G.instructions,runId:z?Y.runId:void 0,nesting:{depth:X,maxDepth:this.maxDepth,chain:V,signingRunId:this.signingRunId,signingPath:K,onPending:H}}),j=[],L=(async()=>{for await(let F of U){if(F.type==="awaiting-input")j=F.pending;this.emit({type:"nested-event",toolCallId:$.toolCallId,runId:U.runId,agent:Z.name,label:B,event:F})}})(),w=(async()=>{let F=await U.result();await L;let k=z?tQ(Y.messages,F.messages):tQ(G.messages??[],F.messages),IQ={runId:U.runId,agent:Z.name,label:B,messages:k,finishReason:F.finishReason,usage:z?DQ(Y.usage??o(),F.usage):F.usage,...F.finishReason==="awaiting-input"?{signature:cQ({runId:this.signingRunId,path:K,nestedRunId:U.runId,open:[...s(k)],input:$.input})}:{}};return J(IQ),this.usage=DQ(this.usage,F.usage),{result:F,record:IQ}})(),b=w.then(()=>{return},()=>{return});this.nestedSettling.add(b);let u,N;try{({result:u,record:N}=await w)}finally{this.nestedSettling.delete(b)}if(this.controller.signal.aborted)throw new M;if(u.finishReason==="awaiting-input"){if(j.length===0)throw Error(`"${Z.name}" ended awaiting input but asked nothing, so there is no question to escalate.`);throw this.emit({type:"tool-call",messageId:Q,part:$,resent:!0}),new P({pending:j,path:K,nested:N})}return{runId:N.runId,agent:Z.name,messages:N.messages,finishReason:u.finishReason,usage:N.usage??o(),output:u.output??aQ(N.messages),nested:N}}addResult(Q,$){Q.content.push($),this.emit({type:"tool-result",messageId:Q.id,part:$})}toolAttachments(Q){let $=this.params.attachments??null,Z=new jQ(()=>Q.attachments,()=>Q.attachments=[],()=>({failed:!0})),G=()=>{if(!$)throw new x("This request has no attachment scope, so a tool cannot store or read files on it. `attachmentScope()` returned null \u2014 put the chat route behind authentication, send a `threadId`, or override `attachmentScope()` on the controller.");return $};return{get:(J)=>G().get(J),read:(J)=>G().read(J),file:(J)=>G().file(J),put:async(J,Y={})=>{let{at:W,recorded:V,write:X}=Z.next();if(V&&"attachment"in V){let U=p2(V,J,Y);if(U)throw Error(`Attachment ${W} of "${String(Q.name)}" ${U}. `+"ctx.attachments.put is memoized by call index within a tool call, so a body whose put calls depend on a condition that changed between turns cannot be replayed \u2014 the model would be shown a file under an id that names different bytes. "+"Make the sequence of put calls the same every time this tool runs, or branch on ctx.resumed.");if(V.shown)this.queueShown(Q.toolCallId,V);return V.attachment}let B=G(),K=Y.mimeType||J.type||"",H=Y.name??(J instanceof File?J.name:"attachment"),z;if(Y.showModel){let U=this.config.provider;if(!U.capabilities.fileInput)throw Error(`"${String(Q.name)}" asked to show a file to ${U.model}, which does not accept file input. Drop \`showModel\` for this provider, or run this agent on a model that takes files \u2014 \`capabilities.fileInput\` is what says which do.`);z=await U.upload(new File([J],H,{type:K||void 0}))}let O=await B.put(J,{name:H,mimeType:K,fileId:z}),D={attachment:O,...z?{shown:{fileId:z,messageId:`msg_${crypto.randomUUID()}`,createdAt:new Date().toISOString()}}:{}};if(X(D),D.shown)this.queueShown(Q.toolCallId,D);return O}}}toolTurn(Q){let $=this.history.findIndex((Y)=>Y.id===Q),Z=eQ(this.history),G;for(let Y=$-1;Y>=0;Y--){let W=this.history[Y];if(W.role!=="user"||Z.has(W.id))continue;G=W;break}let J=[];for(let Y of G?.content??[]){if(Y.type!=="file")continue;let W=Y.attachmentId;if(typeof W!=="string"||!W.startsWith(C))continue;if(!J.includes(W))J.push(W)}return Object.freeze({attachments:Object.freeze(J)})}queueShown(Q,$){let Z=$.shown;if(!Z)return;let G=this.shownQueue.get(Q)??[];if(G.some((J)=>J.id===Z.messageId))return;G.push({id:Z.messageId,role:"user",content:[{type:"file",fileId:Z.fileId,name:$.attachment.name,mimeType:$.attachment.mimeType,attachmentId:$.attachment.id}],createdAt:Z.createdAt,finishReason:"stop"}),this.shownQueue.set(Q,G)}async settleShown(Q){let $=this.shownQueue.get(Q);if(!$||$.length===0)return;if(this.shownQueue.delete(Q),this.ended||this.controller.signal.aborted)return;for(let Z of $){if(this.history.some((G)=>G.id===Z.id))continue;this.history.push(Z),this.produced.push(Z),this.emit({type:"message",message:Z}),this.unreported.add(Z)}}historyForProvider(Q){let $=this.history.filter((Y)=>Y!==Q),Z=eQ($),G=[];for(let Y of $){if(!Z.has(Y.id))continue;for(let W of Y.content)if(W.type==="file")G.push(W)}if(G.length<=Q2)return $;let J=new Set(G.slice(0,G.length-Q2));return $.map((Y)=>{if(!Y.content.some((W)=>W.type==="file"&&J.has(W)))return Y;return{...Y,content:Y.content.map((W)=>W.type==="file"&&J.has(W)?{type:"text",text:`[A ${W.mimeType||"file"} produced by a tool (attachment ${W.attachmentId}) was attached here and has been dropped from this request: only the most recent tool-produced file is kept attached, to keep the context bounded. Call the tool again if you need to look at it.]`}:W)}})}async ingestTurn(){let Q=this.params.turn,$=this.openCalls(),Z=[];if($.length>0){let G=new Set,J=new Set,Y=new Map;for(let W of Q?.toolResults??[]){let V=`${(W.path??[]).join("/")}#${W.toolCallId}`;if(J.has(V))continue;J.add(V);let X=(z)=>this.emit({type:"error",error:{code:"invalid_tool_result",message:z,toolCallId:W.toolCallId,retryable:!1}}),B=$2(W.path,this.pathPrefix);if(B===null){X(`The answer for "${W.toolCallId}" is addressed to a tool call this run is not inside.`);continue}if(B.length>0){let z=B[0],O=$.find((j)=>j.call.toolCallId===z);if(!O){X(`No pending tool call with id "${z}" to deliver a nested answer to.`);continue}let D=this.parkedBelow(O.call,B,W.toolCallId);if(D.ok===!1){let j=`The answer for "${W.toolCallId}" is addressed under "${z}", which`;X(D.reason==="unparked"?`${j} has no sub-agent run waiting on that question.`:D.reason==="expired"?`${j} parked a sub-agent run that has since expired. Ask again.`:`${j} carries a record of a parked sub-agent run the server did not sign.`);continue}let U=Y.get(z);if(!U){if(!dQ(D.signature)){X(`The answer for "${W.toolCallId}" is addressed under "${z}", which has already been re-entered on that record. Ask again.`);continue}U=[],Y.set(z,U),G.add(z)}U.push(W);continue}let K=$.find((z)=>z.call.toolCallId===W.toolCallId);if(!K){X(`No pending tool call with id "${W.toolCallId}".`);continue}let H=await this.resolveAnswer(K,W,Z);if(H===null)continue;if(G.add(W.toolCallId),H!=="open")this.attachToHistory(K,H),await this.settleShown(W.toolCallId)}for(let[W,V]of Y){let X=$.find((K)=>K.call.toolCallId===W),B=await this.reenter(X,V,Z);if(B)this.attachToHistory(X,B),await this.settleShown(W)}for(let W of $){if(G.has(W.call.toolCallId))continue;this.attachToHistory(W,{type:"tool-result",toolCallId:W.call.toolCallId,name:W.call.name,status:"denied",cause:"refused"})}await this.reportDeferred()}if(Q&&(Q.text||Q.files&&Q.files.length>0)){let G={id:`msg_${crypto.randomUUID()}`,role:"user",content:[...Q.text?[{type:"text",text:Q.text}]:[],...(Q.files??[]).map((J)=>({type:"file",...J.fileId?{fileId:J.fileId}:{},name:J.name,mimeType:J.mimeType,...J.attachmentId?{attachmentId:J.attachmentId}:{}}))],createdAt:new Date().toISOString(),finishReason:"stop"};this.history.push(G),this.produced.push(G),await this.report(G)}return Z}parkedBelow(Q,$,Z){let G=$.length>1?$[1]:Z,J=[...this.pathPrefix,Q.toolCallId],Y=(Q.nested??[]).find((V)=>V.finishReason==="awaiting-input"&&s(V.messages).has(G));if(!Y)return{ok:!1,reason:"unparked"};if(typeof Y.signature!=="string")return{ok:!1,reason:"unsigned"};let W=mQ(Y.signature,{path:J,nestedRunId:Y.runId,open:[...s(Y.messages)],input:Q.input});if(W.ok===!1)return{ok:!1,reason:W.reason==="expired"?"expired":"unsigned"};return{ok:!0,signature:Y.signature}}async reenter(Q,$,Z){let G=String(Q.call.name),J=this.config.registry.get(G);if(!J||!J.tool.execute)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_result",message:`The tool "${G}" no longer exists, so the sub-agent's question cannot be delivered.`,toolCallId:Q.call.toolCallId,retryable:!1}};let Y=J.tool.inputSchema.safeParse(Q.call.input);if(Y.ok===!1)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${G}": ${Y.errors.join(", ")}`,toolCallId:Q.call.toolCallId,retryable:!0}};let W=this.amendCall(Q);W.input=Y.value;try{return await n(this.executeTool(J,Q.message.id,W,Y.value,0,{answers:$}),this.controller.signal)}catch(V){if(V instanceof P)return Z.push(...V.pending),null;throw V}}amendCall(Q){let $=this.amend(Q.message),Z=$.content.indexOf(Q.call),G={...Q.call,nested:(Q.call.nested??[]).map((J)=>({...J})),...Q.call.attachments?{attachments:Q.call.attachments.map((J)=>({...J}))}:{}};if(Z>=0)$.content[Z]=G;return this.unreported.add($),G}openCalls(){let Q=new Set;for(let Z of this.history)for(let G of Z.content)if(G.type==="tool-result")Q.add(G.toolCallId);let $=[];for(let Z of this.history)for(let G of Z.content)if(G.type==="tool-call"&&!Q.has(G.toolCallId))$.push({message:Z,call:G});return $}async resolveAnswer(Q,$,Z){let G=Q.call,J=String(G.name),Y=this.config.registry.get(J),W=(K)=>{return this.emit({type:"error",error:{code:"invalid_tool_result",message:K,toolCallId:G.toolCallId,retryable:!1}}),null};if(!Y)return W(`The tool "${J}" no longer exists, so its answer cannot be checked.`);let V=Z2(Y.tool);if(!V)return W(`"${J}" is a server tool with no pending question.`);if(typeof $.signature!=="string"||$.signature.length===0)return W(`The answer for "${J}" carried no signature.`);let X=p($.signature);if(!X)return W(`The signature for "${J}" is malformed.`);let B=gQ($.signature,{...this.claimsFor(G.toolCallId,J,V,G.input),runId:X.runId});if(B.ok===!1)return W(B.reason==="expired"?`The approval for "${J}" has expired. Ask again.`:`The answer for "${J}" does not match the call the server made.`);if(!iQ($.signature))return W(`The answer for "${J}" has already been used. Ask again.`);if("approve"in $){if(V!=="approval")return W(`"${J}" is answered by the client, not approved.`);if($.approve===!0){let K=this.amendCall(Q);try{return await n(this.executeTool(Y,Q.message.id,K,K.input,0),this.controller.signal)}catch(H){if(H instanceof P)return Z.push(...H.pending),"open";throw H}}return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"denied",cause:"refused",reason:$.reason}}if("output"in $){if(V==="approval")return W(`"${J}" is approved, not answered: the server produces its result.`);let K=Y.tool.outputSchema,H=K?K.safeParse($.output):{ok:!0,value:$.output};if(H.ok===!1)return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"error",error:{code:"invalid_tool_result",message:`The answer for "${J}" did not match its output schema: ${H.errors.join(", ")}`,toolCallId:G.toolCallId,retryable:!0}};return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"ok",output:H.value}}return W(`The answer for "${J}" carried neither an approval nor an output.`)}attachToHistory(Q,$){let Z=this.amend(Q.message);Z.content.push($),this.unreported.add(Z),this.emit({type:"tool-result",messageId:Z.id,part:$})}amend(Q){let $=this.amended.get(Q.id);if($)return $;let Z={...Q,content:[...Q.content]},G=this.history.indexOf(Q);if(G>=0)this.history[G]=Z;return this.produced.push(Z),this.amended.set(Q.id,Z),Z}async reportDeferred(){let Q=[...this.unreported];this.unreported.clear();for(let $ of Q)await this.report($)}async finalizeAborted(){if(this.nestedSettling.size>0)await Promise.all([...this.nestedSettling]);for(let $ of this.openCalls()){if($.message===this.current)continue;this.attachToHistory($,{type:"tool-result",toolCallId:$.call.toolCallId,name:$.call.name,status:"denied",cause:"stopped",reason:this.stopReason})}await this.reportDeferred();let Q=this.current;if(Q){let $=new Set(Q.content.filter((Z)=>Z.type==="tool-result").map((Z)=>Z.toolCallId));for(let Z of[...Q.content]){if(Z.type!=="tool-call"||$.has(Z.toolCallId))continue;delete Z.partial,this.addResult(Q,{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"denied",cause:"stopped",reason:this.stopReason})}}this.finishReason="aborted",await this.finalizeMessage("aborted")}}function Z2(Q){if(Q.answeredBy==="client")return Q.inputSchema===FQ?"question":"client";return Q.requiresApproval?"approval":null}function G2(Q){if(!Q||!Q.trim())return{};try{return JSON.parse(Q)}catch{return Q}}function d2(Q){if(Q.length>0)Q[0];return Q}function l2(Q,$,Z){let G=Q.content[Q.content.length-1];if(G&&G.type===$){G.text=(G.text??"")+Z;return}Q.content.push($==="text"?{type:"text",text:Z}:{type:"reasoning",text:Z})}function n2(Q,$,Z){let G=Q.content[Q.content.length-1];if(G&&G.type==="reasoning"&&G.id===$){G.text=(G.text??"")+Z;return}Q.content.push($?{type:"reasoning",id:$,text:Z}:{type:"reasoning",text:Z})}function o2(Q,$){return Q.descriptors($).map((Z)=>q.create({name:Z.name,description:Z.description,inputSchema:Z.inputSchema,requiresApproval:Z.requiresApproval,execute:(G,J)=>Q.execute({kind:"local",req:J.req},Z.name,G,J)}))}class a extends Error{status;body;requestId;constructor(Q,$,Z){super(`Provider request failed with status ${Q}: ${s2($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=Z}}class r extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function s2(Q){let $=V2(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function V2(Q){if(!Q||typeof Q!=="object")return null;let $=Q,G=$.error&&typeof $.error==="object"?$.error:Q;if(typeof G.message!=="string"&&typeof G.code!=="string"&&typeof G.type!=="string")return null;let J=G.innererror?.code??G.code;return{message:G.message,type:G.type,code:J,param:G.param}}function S(Q){if(Q instanceof r)return{code:"provider_error",message:Q.message,retryable:!0};if(e2(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof a)return t2(Q.status,V2(Q.body),Q.message);if(Q instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${Q.message}`,retryable:!0};if(Q instanceof Error)return{code:"provider_error",message:Q.message,retryable:!1};return{code:"unknown",message:String(Q),retryable:!1}}function t2(Q,$,Z){let G=$?.message??Z,J=($?.code??"").toLowerCase(),Y=($?.type??"").toLowerCase(),W=`${J} ${Y} ${G}`.toLowerCase();if(Q===429){let V=J==="insufficient_quota"||W.includes("quota");return{code:"rate_limited",message:G,retryable:!V}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:G,retryable:!0};if(a2(W))return{code:"context_length_exceeded",message:G,retryable:!1};if(r2(W))return{code:"content_filtered",message:G,retryable:!1};if($?.param?.startsWith("tools")||W.includes("invalid schema for function"))return{code:"invalid_tool_input",message:G,retryable:!1};return{code:"provider_error",message:G,retryable:!1}}function a2(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function r2(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function e2(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}var Q5=500,B2=20000;function $5(Q,$){if(!Q)return;let Z=Q.trim();if(/^\d+(\.\d+)?$/.test(Z))return Math.max(0,Number(Z)*1000);let G=Date.parse(Z);if(Number.isNaN(G))return;return Math.max(0,G-$)}function X2(Q,$){let Z=Math.min(B2,Q5*2**Q);return Math.round(Z*(0.5+$()*0.5))}function Z5(Q){return Q===429||Q===408||Q===409||Q>=500}function G5(Q,$){return Z5(Q)&&S($).retryable}function K2(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function J5(Q,$){return new Promise((Z,G)=>{let J=setTimeout(Z,Q);$?.addEventListener("abort",()=>{clearTimeout(J),G(K2($))},{once:!0})})}async function NQ(Q,$,Z){let G=Z.fetchImpl??((K,H)=>fetch(K,H)),J=Z.sleep??J5,Y=Z.random??Math.random,W=Z.now??Date.now,V=Math.max(0,Z.maxRetries),X=async(K)=>{let H=Z.signal;if(!H)return await J(K);H.throwIfAborted();let z;try{await Promise.race([J(K,H),new Promise((O,D)=>{z=()=>D(K2(H)),H.addEventListener("abort",z,{once:!0})})])}finally{if(z)H.removeEventListener("abort",z)}},B;for(let K=0;K<=V;K++){Z.signal?.throwIfAborted();let H=new AbortController,z=()=>H.abort(Z.signal?.reason);Z.signal?.addEventListener("abort",z,{once:!0});let O=!1,D=Z.timeoutMs>0?setTimeout(()=>{O=!0,H.abort()},Z.timeoutMs):void 0,U;try{U=await G(Q,{...$,signal:H.signal})}catch(b){if(D!==void 0)clearTimeout(D);if(Z.signal?.removeEventListener("abort",z),Z.signal?.aborted)throw b;if(B=O?new r(Z.timeoutMs):b,K===V)throw B;await X(X2(K,Y));continue}if(D!==void 0)clearTimeout(D);if(U.ok)return U;Z.signal?.removeEventListener("abort",z);let j=await Y5(U),L=new a(U.status,j,U.headers.get("x-request-id")??void 0);if(K===V||!G5(U.status,L))throw L;let w=$5(U.headers.get("retry-after"),W());await X(w===void 0?X2(K,Y):Math.min(w,B2)),B=L}throw B??Error("Provider request failed with no response.")}async function Y5(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}async function*W5(Q){let $="",Z="",G=[],J,Y=()=>{if(G.length===0&&!Z)return null;let X={event:Z,data:G.join(`
|
|
15
|
+
`):void 0}async runTools(Q,$,Z){let G=[],J=[];for(let Y of $){let W=this.config.registry.get(String(Y.name));if(!W){this.addResult(Q,{type:"tool-result",toolCallId:Y.toolCallId,name:Y.name,status:"error",error:{code:"tool_error",message:`There is no tool named "${String(Y.name)}".`,toolCallId:Y.toolCallId,retryable:!0}});continue}let V=W.tool.inputSchema.safeParse(Y.input);if(V.ok===!1){this.addResult(Q,{type:"tool-result",toolCallId:Y.toolCallId,name:Y.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${String(Y.name)}": ${V.errors.join(", ")}`,toolCallId:Y.toolCallId,retryable:!0}});continue}Y.input=V.value;let X=Z2(W.tool);if(X){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(Y));continue}G.push({toolCallId:Y.toolCallId,name:Y.name,input:V.value,kind:X,signature:yQ(this.claimsFor(Y.toolCallId,String(Y.name),X,V.value)),...this.pathPrefix.length>0?{path:[...this.pathPrefix]}:{}});continue}J.push(this.executeTool(W,Q.id,Y,V.value,Z).then(async(B)=>{this.addResult(Q,B),await this.settleShown(Y.toolCallId)}).catch((B)=>{if(B instanceof M){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(Y));return}G.push(...B.pending);return}}))}return await n(Promise.all(J).then(()=>{return}),this.controller.signal),G}claimsFor(Q,$,Z,G){return{runId:this.signingRunId,toolCallId:Q,name:$,kind:Z,input:G,path:this.pathPrefix.length>0?[...this.pathPrefix]:void 0}}deniedByPolicy(Q){return{type:"tool-result",toolCallId:Q.toolCallId,name:Q.name,status:"denied",cause:"refused",reason:`"${String(Q.name)}" needs the user, and this run was started with onPending: "deny". Answer from what you already have.`}}async executeTool(Q,$,Z,G,J,Y){let W={req:this.params.req,runId:this.runId,threadId:this.params.threadId,toolCallId:Z.toolCallId,signal:this.controller.signal,step:J,depth:this.depth,resumed:Y!==void 0,attachments:this.toolAttachments(Z),turn:this.toolTurn($),runAgent:this.nestedRunner($,Z,Y)};try{let V=Q.tool.execute(G,W),X;if(m2(V)){let B=await V.next();while(!B.done)this.emit({type:"tool-progress",toolCallId:Z.toolCallId,data:B.value}),B=await V.next();X=B.value}else X=await V;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"ok",output:X}}catch(V){if(V instanceof q||this.controller.signal.aborted)throw new q;if(V instanceof M)throw V;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:{code:"tool_error",message:V instanceof Error?V.message:String(V),toolCallId:Z.toolCallId,retryable:!0}}}}nestedRunner(Q,$,Z){let G=new jQ(()=>$.nested,()=>$.nested=[]);return async(J,Y={})=>{let{at:W,recorded:V,write:X}=G.next();if(V){let B=l2(V,J,Y);if(B)throw Error(`Nested run ${W} of "${String($.name)}" ${B}. `+"runAgent is memoized by call index, so a body whose runAgent calls depend on a condition that changed between turns cannot be resumed \u2014 the answer would be paired with a different sub-run. "+"Make the sequence of runAgent calls, and what each one is asked, the same every time this tool runs, or branch on ctx.resumed.");if(V.finishReason!=="awaiting-input")return{runId:V.runId,agent:V.agent,messages:V.messages,finishReason:V.finishReason??"stop",usage:V.usage??o(),output:aQ(V.messages),nested:V}}return this.runNested(Q,$,J,Y,X,V,Z?.answers??[])}}async runNested(Q,$,Z,G,J,Y,W){let V=[...this.chain,Z.name];if(this.chain.includes(Z.name))throw Error(`"${Z.name}" is already running further up this chain: ${V.join(" -> ")}. An agent cannot run itself, directly or through another agent.`);let X=this.depth+1;if(X>this.maxDepth)throw Error(`Nested agent runs are ${this.maxDepth} deep at most and this one would be ${X}: ${V.join(" -> ")}. Raise maxDepth on the agent at the root of the run if the tree is meant to be this deep.`);let B=G.label,K=[...this.pathPrefix,$.toolCallId],H=this.onPending==="deny"?"deny":G.onPending??"escalate",z=Y!==void 0,O=z?s(Y.messages):new Set,D=z?W.filter((L)=>{let k=$2(L.path,K);if(k===null)return!1;return O.has(k.length>0?k[0]:L.toolCallId)}):[],U=Z.stream({messages:z?Y.messages:G.messages??[],turn:z?{toolResults:D}:G.prompt?{text:G.prompt}:void 0,req:this.params.req,attachments:this.params.attachments,signal:this.controller.signal,threadId:this.params.threadId,instructions:G.instructions,runId:z?Y.runId:void 0,nesting:{depth:X,maxDepth:this.maxDepth,chain:V,signingRunId:this.signingRunId,signingPath:K,onPending:H}}),j=[],F=(async()=>{for await(let L of U){if(L.type==="awaiting-input")j=L.pending;this.emit({type:"nested-event",toolCallId:$.toolCallId,runId:U.runId,agent:Z.name,label:B,event:L})}})(),w=(async()=>{let L=await U.result();await F;let k=z?tQ(Y.messages,L.messages):tQ(G.messages??[],L.messages),IQ={runId:U.runId,agent:Z.name,label:B,messages:k,finishReason:L.finishReason,usage:z?DQ(Y.usage??o(),L.usage):L.usage,...L.finishReason==="awaiting-input"?{signature:cQ({runId:this.signingRunId,path:K,nestedRunId:U.runId,open:[...s(k)],input:$.input})}:{}};return J(IQ),this.usage=DQ(this.usage,L.usage),{result:L,record:IQ}})(),b=w.then(()=>{return},()=>{return});this.nestedSettling.add(b);let u,_;try{({result:u,record:_}=await w)}finally{this.nestedSettling.delete(b)}if(this.controller.signal.aborted)throw new q;if(u.finishReason==="awaiting-input"){if(j.length===0)throw Error(`"${Z.name}" ended awaiting input but asked nothing, so there is no question to escalate.`);throw this.emit({type:"tool-call",messageId:Q,part:$,resent:!0}),new M({pending:j,path:K,nested:_})}return{runId:_.runId,agent:Z.name,messages:_.messages,finishReason:u.finishReason,usage:_.usage??o(),output:u.output??aQ(_.messages),nested:_}}addResult(Q,$){Q.content.push($),this.emit({type:"tool-result",messageId:Q.id,part:$})}toolAttachments(Q){let $=this.params.attachments??null,Z=new jQ(()=>Q.attachments,()=>Q.attachments=[],()=>({failed:!0})),G=()=>{if(!$)throw new x("This request has no attachment scope, so a tool cannot store or read files on it. `attachmentScope()` returned null \u2014 put the chat route behind authentication, send a `threadId`, or override `attachmentScope()` on the controller.");return $};return{get:(J)=>G().get(J),read:(J)=>G().read(J),file:(J)=>G().file(J),put:async(J,Y={})=>{let{at:W,recorded:V,write:X}=Z.next();if(V&&"attachment"in V){let U=i2(V,J,Y);if(U)throw Error(`Attachment ${W} of "${String(Q.name)}" ${U}. `+"ctx.attachments.put is memoized by call index within a tool call, so a body whose put calls depend on a condition that changed between turns cannot be replayed \u2014 the model would be shown a file under an id that names different bytes. "+"Make the sequence of put calls the same every time this tool runs, or branch on ctx.resumed.");if(V.shown)this.queueShown(Q.toolCallId,V);return V.attachment}let B=G(),K=Y.mimeType||J.type||"",H=Y.name??(J instanceof File?J.name:"attachment"),z;if(Y.showModel){let U=this.config.provider;if(!U.capabilities.fileInput)throw Error(`"${String(Q.name)}" asked to show a file to ${U.model}, which does not accept file input. Drop \`showModel\` for this provider, or run this agent on a model that takes files \u2014 \`capabilities.fileInput\` is what says which do.`);z=await U.upload(new File([J],H,{type:K||void 0}))}let O=await B.put(J,{name:H,mimeType:K,fileId:z}),D={attachment:O,...z?{shown:{fileId:z,messageId:`msg_${crypto.randomUUID()}`,createdAt:new Date().toISOString()}}:{}};if(X(D),D.shown)this.queueShown(Q.toolCallId,D);return O}}}toolTurn(Q){let $=this.history.findIndex((Y)=>Y.id===Q),Z=eQ(this.history),G;for(let Y=$-1;Y>=0;Y--){let W=this.history[Y];if(W.role!=="user"||Z.has(W.id))continue;G=W;break}let J=[];for(let Y of G?.content??[]){if(Y.type!=="file")continue;let W=Y.attachmentId;if(typeof W!=="string"||!W.startsWith(C))continue;if(!J.includes(W))J.push(W)}return Object.freeze({attachments:Object.freeze(J)})}queueShown(Q,$){let Z=$.shown;if(!Z)return;let G=this.shownQueue.get(Q)??[];if(G.some((J)=>J.id===Z.messageId))return;G.push({id:Z.messageId,role:"user",content:[{type:"file",fileId:Z.fileId,name:$.attachment.name,mimeType:$.attachment.mimeType,attachmentId:$.attachment.id}],createdAt:Z.createdAt,finishReason:"stop"}),this.shownQueue.set(Q,G)}async settleShown(Q){let $=this.shownQueue.get(Q);if(!$||$.length===0)return;if(this.shownQueue.delete(Q),this.ended||this.controller.signal.aborted)return;for(let Z of $){if(this.history.some((G)=>G.id===Z.id))continue;this.history.push(Z),this.produced.push(Z),this.emit({type:"message",message:Z}),this.unreported.add(Z)}}historyForProvider(Q){let $=this.history.filter((Y)=>Y!==Q),Z=eQ($),G=[];for(let Y of $){if(!Z.has(Y.id))continue;for(let W of Y.content)if(W.type==="file")G.push(W)}if(G.length<=Q2)return $;let J=new Set(G.slice(0,G.length-Q2));return $.map((Y)=>{if(!Y.content.some((W)=>W.type==="file"&&J.has(W)))return Y;return{...Y,content:Y.content.map((W)=>W.type==="file"&&J.has(W)?{type:"text",text:`[A ${W.mimeType||"file"} produced by a tool (attachment ${W.attachmentId}) was attached here and has been dropped from this request: only the most recent tool-produced file is kept attached, to keep the context bounded. Call the tool again if you need to look at it.]`}:W)}})}async ingestTurn(){let Q=this.params.turn,$=this.openCalls(),Z=[];if($.length>0){let G=new Set,J=new Set,Y=new Map;for(let W of Q?.toolResults??[]){let V=`${(W.path??[]).join("/")}#${W.toolCallId}`;if(J.has(V))continue;J.add(V);let X=(z)=>this.emit({type:"error",error:{code:"invalid_tool_result",message:z,toolCallId:W.toolCallId,retryable:!1}}),B=$2(W.path,this.pathPrefix);if(B===null){X(`The answer for "${W.toolCallId}" is addressed to a tool call this run is not inside.`);continue}if(B.length>0){let z=B[0],O=$.find((j)=>j.call.toolCallId===z);if(!O){X(`No pending tool call with id "${z}" to deliver a nested answer to.`);continue}let D=this.parkedBelow(O.call,B,W.toolCallId);if(D.ok===!1){let j=`The answer for "${W.toolCallId}" is addressed under "${z}", which`;X(D.reason==="unparked"?`${j} has no sub-agent run waiting on that question.`:D.reason==="expired"?`${j} parked a sub-agent run that has since expired. Ask again.`:`${j} carries a record of a parked sub-agent run the server did not sign.`);continue}let U=Y.get(z);if(!U){if(!lQ(D.signature)){X(`The answer for "${W.toolCallId}" is addressed under "${z}", which has already been re-entered on that record. Ask again.`);continue}U=[],Y.set(z,U),G.add(z)}U.push(W);continue}let K=$.find((z)=>z.call.toolCallId===W.toolCallId);if(!K){X(`No pending tool call with id "${W.toolCallId}".`);continue}let H=await this.resolveAnswer(K,W,Z);if(H===null)continue;if(G.add(W.toolCallId),H!=="open")this.attachToHistory(K,H),await this.settleShown(W.toolCallId)}for(let[W,V]of Y){let X=$.find((K)=>K.call.toolCallId===W),B=await this.reenter(X,V,Z);if(B)this.attachToHistory(X,B),await this.settleShown(W)}for(let W of $){if(G.has(W.call.toolCallId))continue;this.attachToHistory(W,{type:"tool-result",toolCallId:W.call.toolCallId,name:W.call.name,status:"denied",cause:"refused"})}await this.reportDeferred()}if(Q&&(Q.text||Q.files&&Q.files.length>0)){let G={id:`msg_${crypto.randomUUID()}`,role:"user",content:[...Q.text?[{type:"text",text:Q.text}]:[],...(Q.files??[]).map((J)=>({type:"file",...J.fileId?{fileId:J.fileId}:{},name:J.name,mimeType:J.mimeType,...J.attachmentId?{attachmentId:J.attachmentId}:{}}))],createdAt:new Date().toISOString(),finishReason:"stop"};this.history.push(G),this.produced.push(G),await this.report(G)}return Z}parkedBelow(Q,$,Z){let G=$.length>1?$[1]:Z,J=[...this.pathPrefix,Q.toolCallId],Y=(Q.nested??[]).find((V)=>V.finishReason==="awaiting-input"&&s(V.messages).has(G));if(!Y)return{ok:!1,reason:"unparked"};if(typeof Y.signature!=="string")return{ok:!1,reason:"unsigned"};let W=mQ(Y.signature,{path:J,nestedRunId:Y.runId,open:[...s(Y.messages)],input:Q.input});if(W.ok===!1)return{ok:!1,reason:W.reason==="expired"?"expired":"unsigned"};return{ok:!0,signature:Y.signature}}async reenter(Q,$,Z){let G=String(Q.call.name),J=this.config.registry.get(G);if(!J||!J.tool.execute)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_result",message:`The tool "${G}" no longer exists, so the sub-agent's question cannot be delivered.`,toolCallId:Q.call.toolCallId,retryable:!1}};let Y=J.tool.inputSchema.safeParse(Q.call.input);if(Y.ok===!1)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${G}": ${Y.errors.join(", ")}`,toolCallId:Q.call.toolCallId,retryable:!0}};let W=this.amendCall(Q);W.input=Y.value;try{return await n(this.executeTool(J,Q.message.id,W,Y.value,0,{answers:$}),this.controller.signal)}catch(V){if(V instanceof M)return Z.push(...V.pending),null;throw V}}amendCall(Q){let $=this.amend(Q.message),Z=$.content.indexOf(Q.call),G={...Q.call,nested:(Q.call.nested??[]).map((J)=>({...J})),...Q.call.attachments?{attachments:Q.call.attachments.map((J)=>({...J}))}:{}};if(Z>=0)$.content[Z]=G;return this.unreported.add($),G}openCalls(){let Q=new Set;for(let Z of this.history)for(let G of Z.content)if(G.type==="tool-result")Q.add(G.toolCallId);let $=[];for(let Z of this.history)for(let G of Z.content)if(G.type==="tool-call"&&!Q.has(G.toolCallId))$.push({message:Z,call:G});return $}async resolveAnswer(Q,$,Z){let G=Q.call,J=String(G.name),Y=this.config.registry.get(J),W=(K)=>{return this.emit({type:"error",error:{code:"invalid_tool_result",message:K,toolCallId:G.toolCallId,retryable:!1}}),null};if(!Y)return W(`The tool "${J}" no longer exists, so its answer cannot be checked.`);let V=Z2(Y.tool);if(!V)return W(`"${J}" is a server tool with no pending question.`);if(typeof $.signature!=="string"||$.signature.length===0)return W(`The answer for "${J}" carried no signature.`);let X=p($.signature);if(!X)return W(`The signature for "${J}" is malformed.`);let B=gQ($.signature,{...this.claimsFor(G.toolCallId,J,V,G.input),runId:X.runId});if(B.ok===!1)return W(B.reason==="expired"?`The approval for "${J}" has expired. Ask again.`:`The answer for "${J}" does not match the call the server made.`);if(!iQ($.signature))return W(`The answer for "${J}" has already been used. Ask again.`);if("approve"in $){if(V!=="approval")return W(`"${J}" is answered by the client, not approved.`);if($.approve===!0){let K=this.amendCall(Q);try{return await n(this.executeTool(Y,Q.message.id,K,K.input,0),this.controller.signal)}catch(H){if(H instanceof M)return Z.push(...H.pending),"open";throw H}}return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"denied",cause:"refused",reason:$.reason}}if("output"in $){if(V==="approval")return W(`"${J}" is approved, not answered: the server produces its result.`);let K=Y.tool.outputSchema,H=K?K.safeParse($.output):{ok:!0,value:$.output};if(H.ok===!1)return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"error",error:{code:"invalid_tool_result",message:`The answer for "${J}" did not match its output schema: ${H.errors.join(", ")}`,toolCallId:G.toolCallId,retryable:!0}};return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"ok",output:H.value}}return W(`The answer for "${J}" carried neither an approval nor an output.`)}attachToHistory(Q,$){let Z=this.amend(Q.message);Z.content.push($),this.unreported.add(Z),this.emit({type:"tool-result",messageId:Z.id,part:$})}amend(Q){let $=this.amended.get(Q.id);if($)return $;let Z={...Q,content:[...Q.content]},G=this.history.indexOf(Q);if(G>=0)this.history[G]=Z;return this.produced.push(Z),this.amended.set(Q.id,Z),Z}async reportDeferred(){let Q=[...this.unreported];this.unreported.clear();for(let $ of Q)await this.report($)}async finalizeAborted(){if(this.nestedSettling.size>0)await Promise.all([...this.nestedSettling]);for(let $ of this.openCalls()){if($.message===this.current)continue;this.attachToHistory($,{type:"tool-result",toolCallId:$.call.toolCallId,name:$.call.name,status:"denied",cause:"stopped",reason:this.stopReason})}await this.reportDeferred();let Q=this.current;if(Q){let $=new Set(Q.content.filter((Z)=>Z.type==="tool-result").map((Z)=>Z.toolCallId));for(let Z of[...Q.content]){if(Z.type!=="tool-call"||$.has(Z.toolCallId))continue;delete Z.partial,this.addResult(Q,{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"denied",cause:"stopped",reason:this.stopReason})}}this.finishReason="aborted",await this.finalizeMessage("aborted")}}function Z2(Q){if(Q.answeredBy==="client")return Q.inputSchema===LQ?"question":"client";return Q.requiresApproval?"approval":null}function G2(Q){if(!Q||!Q.trim())return{};try{return JSON.parse(Q)}catch{return Q}}function d2(Q){if(Q.length>0)Q[0];return Q}function n2(Q,$,Z){let G=Q.content[Q.content.length-1];if(G&&G.type===$){G.text=(G.text??"")+Z;return}Q.content.push($==="text"?{type:"text",text:Z}:{type:"reasoning",text:Z})}function o2(Q,$,Z){let G=Q.content[Q.content.length-1];if(G&&G.type==="reasoning"&&G.id===$){G.text=(G.text??"")+Z;return}Q.content.push($?{type:"reasoning",id:$,text:Z}:{type:"reasoning",text:Z})}function s2(Q,$){return Q.descriptors($).map((Z)=>S.create({name:Z.name,description:Z.description,inputSchema:Z.inputSchema,requiresApproval:Z.requiresApproval,execute:(G,J)=>Q.execute({kind:"local",req:J.req},Z.name,G,J)}))}class a extends Error{status;body;requestId;constructor(Q,$,Z){super(`Provider request failed with status ${Q}: ${t2($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=Z}}class r extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function t2(Q){let $=V2(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function V2(Q){if(!Q||typeof Q!=="object")return null;let $=Q,G=$.error&&typeof $.error==="object"?$.error:Q;if(typeof G.message!=="string"&&typeof G.code!=="string"&&typeof G.type!=="string")return null;let J=G.innererror?.code??G.code;return{message:G.message,type:G.type,code:J,param:G.param}}function R(Q){if(Q instanceof r)return{code:"provider_error",message:Q.message,retryable:!0};if(Q5(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof a)return a2(Q.status,V2(Q.body),Q.message);if(Q instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${Q.message}`,retryable:!0};if(Q instanceof Error)return{code:"provider_error",message:Q.message,retryable:!1};return{code:"unknown",message:String(Q),retryable:!1}}function a2(Q,$,Z){let G=$?.message??Z,J=($?.code??"").toLowerCase(),Y=($?.type??"").toLowerCase(),W=`${J} ${Y} ${G}`.toLowerCase();if(Q===429){let V=J==="insufficient_quota"||W.includes("quota");return{code:"rate_limited",message:G,retryable:!V}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:G,retryable:!0};if(r2(W))return{code:"context_length_exceeded",message:G,retryable:!1};if(e2(W))return{code:"content_filtered",message:G,retryable:!1};if($?.param?.startsWith("tools")||W.includes("invalid schema for function"))return{code:"invalid_tool_input",message:G,retryable:!1};return{code:"provider_error",message:G,retryable:!1}}function r2(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function e2(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function Q5(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}var $5=500,B2=20000;function Z5(Q,$){if(!Q)return;let Z=Q.trim();if(/^\d+(\.\d+)?$/.test(Z))return Math.max(0,Number(Z)*1000);let G=Date.parse(Z);if(Number.isNaN(G))return;return Math.max(0,G-$)}function X2(Q,$){let Z=Math.min(B2,$5*2**Q);return Math.round(Z*(0.5+$()*0.5))}function G5(Q){return Q===429||Q===408||Q===409||Q>=500}function J5(Q,$){return G5(Q)&&R($).retryable}function K2(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function Y5(Q,$){return new Promise((Z,G)=>{let J=setTimeout(Z,Q);$?.addEventListener("abort",()=>{clearTimeout(J),G(K2($))},{once:!0})})}async function NQ(Q,$,Z){let G=Z.fetchImpl??((K,H)=>fetch(K,H)),J=Z.sleep??Y5,Y=Z.random??Math.random,W=Z.now??Date.now,V=Math.max(0,Z.maxRetries),X=async(K)=>{let H=Z.signal;if(!H)return await J(K);H.throwIfAborted();let z;try{await Promise.race([J(K,H),new Promise((O,D)=>{z=()=>D(K2(H)),H.addEventListener("abort",z,{once:!0})})])}finally{if(z)H.removeEventListener("abort",z)}},B;for(let K=0;K<=V;K++){Z.signal?.throwIfAborted();let H=new AbortController,z=()=>H.abort(Z.signal?.reason);Z.signal?.addEventListener("abort",z,{once:!0});let O=!1,D=Z.timeoutMs>0?setTimeout(()=>{O=!0,H.abort()},Z.timeoutMs):void 0,U;try{U=await G(Q,{...$,signal:H.signal})}catch(b){if(D!==void 0)clearTimeout(D);if(Z.signal?.removeEventListener("abort",z),Z.signal?.aborted)throw b;if(B=O?new r(Z.timeoutMs):b,K===V)throw B;await X(X2(K,Y));continue}if(D!==void 0)clearTimeout(D);if(U.ok)return U;Z.signal?.removeEventListener("abort",z);let j=await W5(U),F=new a(U.status,j,U.headers.get("x-request-id")??void 0);if(K===V||!J5(U.status,F))throw F;let w=Z5(U.headers.get("retry-after"),W());await X(w===void 0?X2(K,Y):Math.min(w,B2)),B=F}throw B??Error("Provider request failed with no response.")}async function W5(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}async function*V5(Q){let $="",Z="",G=[],J,Y=()=>{if(G.length===0&&!Z)return null;let X={event:Z,data:G.join(`
|
|
16
16
|
`),id:J};return Z="",G=[],J=void 0,X.data?X:null},W=(X)=>{let B=X.endsWith("\r")?X.slice(0,-1):X;if(B==="")return Y();if(B.startsWith(":"))return null;let K=B.indexOf(":"),H=K===-1?B:B.slice(0,K),z=K===-1?"":B.slice(K+1);if(z.startsWith(" "))z=z.slice(1);if(H==="event")Z=z;else if(H==="data")G.push(z);else if(H==="id")J=z;return null};for await(let X of Q){$+=X;let B=$.indexOf(`
|
|
17
17
|
`);while(B!==-1){let K=$.slice(0,B);$=$.slice(B+1);let H=W(K);if(H)yield H;B=$.indexOf(`
|
|
18
|
-
`)}}if($.length>0){let X=W($);if(X)yield X}let V=Y();if(V)yield V}async function*H2(Q,$={}){let Z=new Map,G=new Set,J=!1;for await(let Y of W5(Q)){if(Y.data==="[DONE]")break;let W;try{W=JSON.parse(Y.data)}catch{continue}switch(typeof W.type==="string"?W.type:Y.event){case"response.output_text.delta":{let X=String(W.delta??"");if(!X)break;yield $.structuredOutput?{type:"output-delta",delta:X}:{type:"text-delta",delta:X};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let X=String(W.delta??"");if(!X)break;yield{type:"reasoning-delta",delta:X,id:W.item_id};break}case"response.output_item.added":{let X=W.item;if(!X)break;if(X.type==="function_call"){let B=String(X.id??W.item_id??X.call_id??"");Z.set(B,{callId:String(X.call_id??B),name:String(X.name??""),namespace:typeof X.namespace==="string"&&X.namespace?X.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let X=Z.get(String(W.item_id??""));if(!X)break;let B=String(W.delta??"");if(!B)break;yield{type:"tool-call-delta",toolCallId:X.callId,name:X.name,argsDelta:B,...X.namespace?{namespace:X.namespace}:{}};break}case"response.function_call_arguments.done":{let X=String(W.item_id??""),B=Z.get(X);if(!B)break;B.done=!0,yield{type:"tool-call",toolCallId:B.callId,name:B.name,args:String(W.arguments??""),...B.namespace?{namespace:B.namespace}:{}};break}case"response.output_item.done":{let X=W.item;if(!X)break;if(X.type==="function_call"){let B=String(X.id??W.item_id??X.call_id??""),K=Z.get(B);if(K?.done)break;let H=(typeof X.namespace==="string"?X.namespace:"")||K?.namespace;if(yield{type:"tool-call",toolCallId:String(X.call_id??B),name:String(X.name??K?.name??""),args:String(X.arguments??""),...H?{namespace:H}:{}},K)K.done=!0;break}if(X.type==="tool_search_call"||X.type==="tool_search_output"){let B=V5(X);if(B.loaded.length===0&&B.namespaces.length===0)break;let K=String(X.tool_search_call_id??X.id??"");if(G.has(K))break;G.add(K),yield{type:"tool-search",...B}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(W.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{J=!0,yield{type:"finish",reason:"stop",usage:_Q(W.response?.usage)};break}case"response.incomplete":{J=!0;let X=_Q(W.response?.usage),B=W.response?.incomplete_details?.reason;if(B==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:X5(W.response?.content_filters),retryable:!1}},yield{type:"finish",reason:"error",usage:X};break}yield{type:"finish",reason:B==="max_output_tokens"?"length":"stop",usage:X};break}case"response.failed":case"error":{J=!0;let X=W.response?.error??W.error??W;yield{type:"error",error:B5(X)},yield{type:"finish",reason:"error",usage:_Q(W.response?.usage)};break}}if(J)return}if(!J)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield{type:"finish",reason:"error",usage:A()}}function V5(Q){let $=[],Z=[];return z2(Q.results??Q.tools??Q.loaded??Q.output,$,Z,0),{loaded:PQ($),namespaces:PQ(Z)}}function z2(Q,$,Z,G){if(!Array.isArray(Q)||G>4)return;for(let J of Q){if(typeof J==="string"){$.push(J);continue}if(!J||typeof J!=="object")continue;let Y=J,W=typeof Y.name==="string"?Y.name:typeof Y.tool_name==="string"?Y.tool_name:"",V=Y.tools??Y.functions;if(Array.isArray(V)){if(W)Z.push(W);z2(V,$,Z,G+1);continue}if(W)$.push(W)}}function PQ(Q){return Q.filter(($,Z)=>Q.indexOf($)===Z)}function X5(Q){if(!Array.isArray(Q))return"The provider's content filter blocked this request.";let Z=[];for(let G of Q){if(!G||typeof G!=="object")continue;let J=G,Y=J.content_filter_results;if(!Y||typeof Y!=="object")continue;for(let[W,V]of Object.entries(Y))if(V&&typeof V==="object"&&V.filtered===!0)Z.push(`${W} (${String(J.source_type??"unknown")})`)}return Z.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${PQ(Z).join(", ")}.`}function B5(Q){let $=typeof Q?.message==="string"?Q.message:"The provider stream failed.",Z=String(Q?.code??"").toLowerCase();if(Z==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(Z==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(Z.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function A(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function _Q(Q){if(!Q)return A();let $=Number(Q.input_tokens??0),Z=Number(Q.output_tokens??0),G={inputTokens:$,outputTokens:Z,totalTokens:Number(Q.total_tokens??$+Z)},J=Q.output_tokens_details?.reasoning_tokens;if(typeof J==="number")G.reasoningTokens=J;let Y=Q.input_tokens_details?.cached_tokens;if(typeof Y==="number")G.cachedInputTokens=Y;return G}async function*U2(Q){if(!Q)return;let $=Q.getReader(),Z=new TextDecoder;try{while(!0){let{done:J,value:Y}=await $.read();if(J)break;if(Y)yield Z.decode(Y,{stream:!0})}let G=Z.decode();if(G)yield G}finally{$.releaseLock()}}async function*MQ(Q,$,Z){let G;try{G=await NQ(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify($)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(J){let Y=S(J);if(Y.code!=="aborted")yield{type:"error",error:Y};yield{type:"finish",reason:Y.code==="aborted"?"aborted":"error",usage:A()};return}try{yield*H2(U2(G.body),{structuredOutput:Z.structuredOutput})}catch(J){let Y=S(J);if(Y.code==="aborted"){yield{type:"finish",reason:"aborted",usage:A()};return}yield{type:"error",error:Y},yield{type:"finish",reason:"error",usage:A()}}}async function qQ(Q,$){let Z=new FormData;Z.set("purpose","user_data"),Z.set("file",$);let J=await(await NQ(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:Z},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl})).json();if(!J?.id)throw Error("The provider accepted the upload but returned no file id.");return J.id}function SQ(Q){let $=K5(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Z=H5($);if(Z?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Z.major>1,toolSearch:D2(Z)};if(Z?.kind==="gpt")return{reasoning:Z.major>=5,structuredOutput:Z.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:Z.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:D2(Z)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function D2(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function K5(Q){return Q.trim().toLowerCase()}function H5(Q){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(Q);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let Z=/^o(\d+)(?:[-.]|$)/.exec(Q);if(Z?.[1])return{kind:"o",major:Number(Z[1]),minor:0};return null}function RQ(Q,$){let{capabilities:Z}=$,G={model:$.model,input:z5(Q.messages,Z),stream:!0};if(Q.systemPrompt)G.instructions=Q.systemPrompt;let J=_5(Q.tools,Z);if(J.length>0){if(G.tools=J,!Z.parallelToolCalls)G.parallel_tool_calls=!1}if(Q.output)G.text={format:{type:"json_schema",name:Q.output.name,schema:Q.output.schema,strict:!0}};if(Q.reasoning&&Z.reasoning)G.reasoning={effort:Q.reasoning,summary:"auto"};if(typeof Q.temperature==="number")G.temperature=Q.temperature;if(typeof Q.maxOutputTokens==="number")G.max_output_tokens=Q.maxOutputTokens;return G}function z5(Q,$){let Z=[];for(let G of Q){let J=G.role,Y=[],W=()=>{if(Y.length===0)return;Z.push({type:"message",role:J,content:Y}),Y=[]};for(let V of G.content??[])switch(V.type){case"text":{if(!V.text)break;Y.push(e(J,V.text));break}case"output":{if(V.partial)break;Y.push(e(J,JSON.stringify(V.value)));break}case"file":{if(J==="assistant")break;let X=O5(V);if(!$.fileInput){if(X)Y.push(e(J,O2(V,!1)));break}if(V.fileId?.startsWith(C))throw Error(`FilePart.fileId holds a gemi attachment id (${V.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!V.fileId&&!X)throw Error("FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_\u2026`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.");if(X)Y.push(e(J,O2(V,!!V.fileId)));if(V.fileId)Y.push(j5(V));break}case"reasoning":{W();let X=C5(V);if(X)Z.push(X);break}case"tool-call":{if(V.partial)break;W(),Z.push({type:"function_call",call_id:V.toolCallId,name:String(V.name),arguments:JSON.stringify(V.input??{})});break}case"tool-result":{W(),Z.push({type:"function_call_output",call_id:V.toolCallId,output:N5(V)});break}}W()}return D5(Z)}var U5="No result was recorded for this tool call. Assume it did not complete.";function D5(Q){let $=new Set,Z=new Set,G=[];for(let Y of Q){if(Y.type==="function_call"){let W=String(Y.call_id);if($.has(W))continue;$.add(W)}else if(Y.type==="function_call_output"){let W=String(Y.call_id);if(!$.has(W)||Z.has(W))continue;Z.add(W)}G.push(Y)}if(Z.size===$.size)return G;let J=[];for(let Y of G){if(J.push(Y),Y.type!=="function_call")continue;let W=String(Y.call_id);if(Z.has(W))continue;Z.add(W),J.push({type:"function_call_output",call_id:W,output:U5})}return J}function e(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function O5(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(C)?$:void 0}function O2(Q,$){let Z=[`id=${JSON.stringify(Q.attachmentId)}`];if(Q.name)Z.push(`name=${JSON.stringify(Q.name)}`);if(Q.mimeType)Z.push(`mimeType=${JSON.stringify(Q.mimeType)}`);let G=`attachment ${Z.join(" ")}`;return $?`[${G}]`:`[${G} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function j5(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":F5(Q.name))?"input_image":"input_file",file_id:Q.fileId}}function F5(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&L5.has($[1])}var L5=new Set(["jpeg","jpg","png","gif","webp"]);function C5(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function N5(Q){if(Q.status==="ok")return typeof Q.output==="string"?Q.output:JSON.stringify(Q.output??null);if(Q.status==="denied"){let $=Q.reason?` Reason given: ${Q.reason}`:"";if(Q.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${Q.error?.code??"unknown"}): ${Q.error?.message??"no message"}`}function j2(Q){return Array.isArray(Q.tools)}function _5(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let J=[];for(let Y of Q)if(j2(Y))for(let W of Y.tools)J.push(QQ(W,!1));else J.push(QQ(Y,!1));return J}let Z=[],G=!1;for(let J of Q)if(j2(J)){let Y=J.tools.map((W)=>{if(W.deferred)G=!0;return QQ(W,!0)});Z.push({type:"namespace",name:J.name,description:J.description,tools:Y})}else{if(J.deferred)G=!0;Z.push(QQ(J,!0))}if(G)Z.push({type:"tool_search"});return Z}function QQ(Q,$){let Z={type:"function",name:Q.name,description:Q.description,parameters:Q.parameters,strict:Q.strict};if($&&Q.deferred)Z.defer_loading=!0;return Z}var L2=120000,C2=2;function R(Q){return typeof process>"u"?void 0:process.env?.[Q]}class $Q{static models(){return[]}normalizeError(Q){return S(Q)}}var N2=["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.4-nano","gpt-5.2","gpt-5.1","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini","o4-mini","o3","o3-mini"];class TQ extends $Q{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=SQ(Q),this.config=$}static model(Q,$){return new TQ(Q,$)}static models(){return N2}stream(Q){let $=RQ(Q,{model:this.model,capabilities:this.capabilities});return MQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return qQ(this.endpoint(),Q)}baseURL(){return(this.config.baseURL??R("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,"")}endpoint(){let Q=this.baseURL(),$=this.config;return{responsesUrl:`${Q}/responses`,filesUrl:`${Q}/files`,headers:async()=>{let Z=$.apiKey??R("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...$.headers}},timeoutMs:$.timeoutMs??L2,maxRetries:$.maxRetries??C2}}}var P5="preview";function F2(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function M5(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}class kQ extends $Q{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=SQ(Q),this.config=$}static model(Q,$){return new kQ(Q,$)}static models(){return N2}stream(Q){let $=RQ(Q,{model:this.deployment(),capabilities:this.capabilities});return MQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return qQ(this.endpoint(),Q)}deployment(){return this.config.deployment??this.model}base(){let Q=this.config,$=Q.baseURL??Q.endpoint??R("AZURE_OPENAI_ENDPOINT");if($)return F2($);let Z=Q.resourceName??R("AZURE_OPENAI_RESOURCE_NAME")??R("AZURE_RESOURCE_NAME");return Z?F2(`https://${Z.trim()}.cognitiveservices.azure.com`):""}endpoint(){let Q=this.config,$=this.base(),Z=Q.apiVersion??R("AZURE_OPENAI_API_VERSION")??P5,G=M5(Z),J=`?api-version=${encodeURIComponent(Z)}`;return{responsesUrl:`${$}${G}/responses${J}`,filesUrl:`${$}${G}/files${J}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let Y=Q.apiKey??R("AZURE_OPENAI_API_KEY");return{...Y?{"api-key":Y}:{},...Q.headers}},timeoutMs:Q.timeoutMs??L2,maxRetries:Q.maxRetries??C2}}}class I extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(Q,$,Z){super(`Frame ${$} of run ${Q} has been evicted; the oldest frame still buffered is ${Z}. Reload the thread instead of resuming.`);this.runId=Q;this.requested=$;this.oldest=Z}}class y extends Error{runId;code="live_run_not_found";constructor(Q){super(`No live run ${Q} in this process.`);this.runId=Q}}class ZQ{ttlMs;maxFrames;runs=new Map;byThread=new Map;byClientRun=new Map;constructor(Q={}){this.ttlMs=Q.ttlMs??60000,this.maxFrames=Q.maxFrames??4096}register(Q,$={}){let Z={run:Q,threadId:$.threadId,clientRunId:$.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evictAt:null,wake:new Set,version:0};if(this.runs.set(Q.runId,Z),$.threadId)this.byThread.set($.threadId,Q.runId);if($.clientRunId)this.byClientRun.set($.clientRunId,Q.runId);return this.pump(Z,$)}findByClientRunId(Q){let $=this.byClientRun.get(Q);return $&&this.runs.has($)?$:null}async find(Q){let $=this.byThread.get(Q.threadId);if(!$)return null;let Z=this.runs.get($);if(!Z)return null;return{runId:$,seq:Z.lastSeq}}get(Q){return this.runs.get(Q)?.run??null}replay(Q,$){let Z=this.runs.get(Q);if(!Z)throw new y(Q);if($!==void 0&&$<Z.lostBefore)throw new I(Q,$,Z.lostBefore);let G=Z.frames[0]?.seq;return this.drain(Z,Q,$??G??Z.lastSeq+1)}clear(){for(let Q of this.runs.values()){if(Q.evictAt)clearTimeout(Q.evictAt);Q.ended=!0,this.notify(Q)}this.runs.clear(),this.byThread.clear(),this.byClientRun.clear()}get size(){return this.runs.size}async pump(Q,$){let Z=Promise.resolve();try{for await(let G of Q.run.frames()){if(Q.frames.push(G),Q.lastSeq=G.seq,Q.frames.length>this.maxFrames){let Y=Q.frames.shift();if(Y)Q.lostBefore=Y.seq+1}this.notify(Q);let J=$.onEvent;if(J)Z=Z.then(()=>J(G.event)).catch((Y)=>_2($,Y))}}catch(G){_2($,G)}finally{Q.ended=!0,this.notify(Q),this.scheduleEviction(Q),await Z}}async*drain(Q,$,Z){let G=Z;while(!0){let J=Q.version;for(;;){if(G<Q.lostBefore)throw new I($,G,Q.lostBefore);let Y=Q.frames,W=Y[0]?.seq;if(W===void 0)break;let V=Math.max(0,G-W);if(V>=Y.length)break;let X=Y[V];yield X,G=X.seq+1}if(Q.ended&&G>Q.lastSeq)return;await this.wait(Q,J)}}wait(Q,$){if(Q.version!==$)return Promise.resolve();return new Promise((Z)=>Q.wake.add(Z))}notify(Q){Q.version++;let $=Array.from(Q.wake);Q.wake.clear();for(let Z of $)Z()}scheduleEviction(Q){if(Q.evictAt)return;let $=setTimeout(()=>{let Z=Q.run.runId;if(this.runs.delete(Z),Q.threadId&&this.byThread.get(Q.threadId)===Z)this.byThread.delete(Q.threadId);if(Q.clientRunId&&this.byClientRun.get(Q.clientRunId)===Z)this.byClientRun.delete(Q.clientRunId);this.notify(Q)},this.ttlMs);$.unref?.(),Q.evictAt=$}}var EQ=new ZQ;function _2(Q,$){try{Q.onInternalError?.($)}catch{}}class GQ{ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor(Q={}){this.ttlMs=Q.ttlMs??86400000,this.clientOwnedIds=Q.clientOwnedIds??!1}async createThread(Q){let $=crypto.randomUUID();return this.threads.set($,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:$}}async loadThread(Q){this.sweep();let $=this.threads.get(Q);if(!$)return this.clientOwnedIds?[]:null;return $.touchedAt=Date.now(),$.messages.slice()}async appendMessages(Q,$){this.sweep();let Z=this.threads.get(Q);if(!Z){if(!this.clientOwnedIds)throw Error(`Thread ${Q} does not exist here, or has expired.`);Z={messages:[],touchedAt:Date.now()},this.threads.set(Q,Z)}for(let G of $){let J=Z.messages.findIndex((Y)=>Y.id===G.id);if(J===-1)Z.messages.push(G);else Z.messages[J]=G}Z.touchedAt=Date.now()}delete(Q){this.threads.delete(Q)}get size(){return this.threads.size}sweep(Q=Date.now()){if(Q-this.lastSweep<60000)return;this.lastSweep=Q;for(let[$,Z]of this.threads)if(Q-Z.touchedAt>this.ttlMs)this.threads.delete($)}}var xQ=new GQ;var q5=q2,JQ=new Map,P2=new WeakMap,YQ=new Map;class R2 extends q5{static kind="agent-controller";store=xQ;liveRuns=EQ;attachments=l;attachmentStorage=S2;hookHoldMs=30000;instructions(Q){}async stream(Q=new g){let $=await AQ(Q);if($.error)return WQ($);let Z=$.body,G=typeof Z.threadId==="string"?Z.threadId:void 0,J=R5(Z);if(J.error)return WQ({body:{},error:J.error});let Y=J.turn,W=typeof Z.clientRunId==="string"?Z.clientRunId:void 0,V=W?{cancelled:!1}:null;if(V)YQ.set(W,V);let X=async()=>{let B;if(G){let L=await this.store.loadThread(G);if(!L)return T(404,{code:"thread_not_found",message:`Thread ${G} does not exist here, or has expired.`});B=L}else B=Array.isArray(Z.messages)?Z.messages:[];let K=await this.instructions(Q)||void 0,H=await this.attachmentsFor(Q,G);if(V?.cancelled)return T(409,{code:"stopped",message:"The turn was stopped before it started."});let z=this.agent.stream({messages:B,turn:Y,req:Q,threadId:G,instructions:K,attachments:H}),O={req:Q,runId:z.runId,threadId:G},D=this.liveRuns.register(z,{threadId:G,clientRunId:W,onEvent:(L)=>this.dispatchEvent(L,O),onInternalError:(L)=>this.reportHookFailure(L)}),{stored:U,hooks:j}=this.persistRun(z,O,D);return P2.set(z,U),Q.ctx?.()?.waitUntil(j),z.toResponse()};try{return G?await this.withThread(G,X):await X()}finally{if(V&&YQ.get(W)===V)YQ.delete(W)}}async withThread(Q,$){let Z=JQ.get(Q)??Promise.resolve(),G,J=new Promise((W)=>{G=W}),Y=Z.then(()=>J);JQ.set(Q,Y),await Z;try{let W=await this.liveRuns.find({threadId:Q}),V=W?this.liveRuns.get(W.runId):null;if(V)V.stop({reason:"superseded by a later turn on this thread"}),await P2.get(V);return await $()}finally{if(G(),JQ.get(Q)===Y)JQ.delete(Q)}}async attach(Q=new g){let $=await AQ(Q);if($.error)return WQ($);let Z=$.body,G=typeof Z.threadId==="string"?Z.threadId:E5(Q,"threadId");if(!G)return T(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});let J=await this.liveRuns.find({threadId:G});if(!J)return T(404,{code:"no_live_run",message:`No run in progress for thread ${G} in this process.`});let Y=typeof Z.runId==="string"?Z.runId:void 0,W=Y&&Y!==J.runId?void 0:k5(Q,Z);try{return oQ(this.liveRuns.replay(J.runId,W))}catch(V){if(V instanceof I)return T(410,{code:V.code,message:V.message,oldestSeq:V.oldest});if(V instanceof y)return T(404,{code:V.code,message:V.message});throw V}}async stop(Q=new g){let $=await AQ(Q);if($.error)return WQ($);let Z=$.body,G=typeof Z.runId==="string"?Z.runId:void 0;if(!G&&typeof Z.clientRunId==="string"){if(G=this.liveRuns.findByClientRunId(Z.clientRunId)??void 0,!G){let Y=YQ.get(Z.clientRunId);if(Y)return Y.cancelled=!0,{stopped:!0}}}if(!G&&typeof Z.threadId==="string")G=(await this.liveRuns.find({threadId:Z.threadId}))?.runId;let J=G?this.liveRuns.get(G):null;if(!J)return{stopped:!1};return J.stop({reason:typeof Z.reason==="string"?Z.reason:void 0}),{stopped:!0}}attachmentScope(Q,$){let Z=Q.ctx()?.user,G=Z?.id??Z?.publicId;if(G!==void 0&&G!==null&&String(G)!=="")return{key:`user:${String(G)}`};if($)return{key:`thread:${$}`};return null}attachmentDestination(Q,$){return"both"}async attachmentsFor(Q,$){let Z=await this.attachmentScope(Q,$);if(!Z)return null;return new f(this.attachments,this.attachmentStorage,Z)}async upload(Q=new g){let $=await Q.rawRequest.formData(),Z=$.get("file");if(!(Z instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let G=Z instanceof File&&Z.name?Z.name:"upload",J=Z.type||"application/octet-stream",Y=$.get("threadId"),W=typeof Y==="string"&&Y.length>0&&await this.store.loadThread(Y)!==null?Y:void 0,V=await this.attachmentDestination(Z,Q),X=x5(V,$.get("destination")),B=await this.attachmentScope(Q,W),K=X!=="provider"&&!B;if(K){if(X==="storage")throw Error('This upload was routed to storage, but `attachmentScope()` returned null for the request, so there is no subject to file the attachment under. Guard the route (`this.agent(Chat).middleware({ upload: "auth" })`), send a `threadId` with the upload, or override `attachmentScope()`.');A5()}if(X==="provider"||!B){let j={fileId:await this.agent.provider.upload(Z),name:G,mimeType:J,size:Z.size,destination:"provider"};if(K)j.downgraded="no_scope";return j}let H=KQ(),z=await this.attachmentStorage.put({name:HQ(H,G),body:Z,contentType:J}),O=X==="both"?await this.agent.provider.upload(Z):void 0,D={id:H,scopeKey:B.key,fileId:O,objectName:z,name:G,mimeType:J,size:Z.size,createdAt:new Date().toISOString(),destination:X};return await this.attachments.put(B,D),{fileId:O,attachmentId:H,name:G,mimeType:J,size:Z.size,destination:X}}onMessage(Q,$){}onToolCall(Q,$){}onAwaitingInput(Q,$){}onError(Q,$){}onStreamComplete(Q,$){}reportHookFailure(Q){console.error("[gemi/ai] agent controller hook failed",Q)}async dispatchEvent(Q,$){switch(Q.type){case"tool-call":if(!Q.part.partial&&!Q.resent)await this.onToolCall({toolCallId:Q.part.toolCallId,name:String(Q.part.name),input:Q.part.input},$);return;case"awaiting-input":await this.onAwaitingInput(Q.pending,$);return;case"error":await this.onError(Q.error,$);return;default:return}}persistRun(Q,$,Z){let G=Promise.resolve(),J=(async()=>{let W;try{W=await Q.result()}catch(X){G=this.safely(()=>this.onError({code:"unknown",message:X instanceof Error?X.message:String(X),retryable:!1},$));return}let V=W.messages;if($.threadId&&V.length>0)try{await this.store.appendMessages($.threadId,V)}catch(X){this.reportHookFailure(X)}G=this.notifyRun(W,V,$)})(),Y=J.then(()=>w5(Promise.all([G,Z]).then(()=>{}),this.hookHoldMs));return{stored:J,hooks:Y}}async notifyRun(Q,$,Z){for(let G of $)await this.safely(()=>this.onMessage(G,Z));await this.safely(()=>this.onStreamComplete(Q,Z))}async safely(Q){try{await Q()}catch($){this.reportHookFailure($)}}}async function AQ(Q){let $=Q?.rawRequest;if(!$||$.method==="GET"||$.method==="HEAD"||!$.body)return{body:{}};if(!S5($.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let Z;try{Z=await $.text()}catch{return{body:{},error:"The request body could not be read."}}if(!Z.trim())return{body:{}};let G;try{G=JSON.parse(Z)}catch{return{body:{},error:"The request body is not valid JSON."}}if(G===null||typeof G!=="object"||Array.isArray(G))return{body:{},error:"The request body must be a JSON object."};return{body:G}}function S5(Q){if(typeof Q!=="string")return!1;let[$]=Q.split(";",1);return $.trim().toLowerCase()==="application/json"}function WQ(Q){return T(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function R5(Q){let $=Q.turn&&typeof Q.turn==="object"?Q.turn:Q,Z={};if(typeof $.text==="string")Z.text=$.text;if(Array.isArray($.files)){let G=T5($.files);if(typeof G==="string")return{error:G};Z.files=G}if(Array.isArray($.toolResults))Z.toolResults=$.toolResults;return Object.keys(Z).length>0?{turn:Z}:{}}function T5(Q){let $=[];for(let[Z,G]of Q.entries()){let J=`turn.files[${Z}]`;if(!G||typeof G!=="object"||Array.isArray(G))return`${J} must be an object.`;let Y={};for(let K of["fileId","attachmentId","name","mimeType"]){let H=G[K];if(H===void 0||H===null||H==="")continue;if(typeof H!=="string")return`${J}.${K} must be a string.`;Y[K]=H}let{fileId:W,attachmentId:V,name:X,mimeType:B}=Y;if(W?.startsWith(C))return`${J}.fileId holds a gemi attachment id (${W}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(V!==void 0&&!V.startsWith(C))return`${J}.attachmentId is not a gemi attachment id: it must start with "${C}".`;if(!W&&!V)return`${J} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...W?{fileId:W}:{},...V?{attachmentId:V}:{},...X!==void 0?{name:X}:{},...B!==void 0?{mimeType:B}:{}})}return $}function k5(Q,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let G=Math.floor($.cursor);if(G>=0)return G+1;return}let Z=Q?.rawRequest?.headers?.get("Last-Event-ID");if(Z){let G=Number.parseInt(Z,10);if(Number.isFinite(G))return Math.max(0,G+1)}return}function E5(Q,$){let Z=Q?.search?.get($);return typeof Z==="string"?Z:void 0}function T(Q,$){return new Response(JSON.stringify({error:$}),{status:Q,headers:{"Content-Type":"application/json"}})}function x5(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 M2=!1;function A5(){if(M2)return;M2=!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 I5=2147483647;function w5(Q,$){let Z=Q.then(()=>{},()=>{});if(!($<=I5))return Z;let G,J=new Promise((Y)=>{G=setTimeout(Y,$)});return Promise.race([Z,J]).finally(()=>clearTimeout(G))}export{o2 as toAgentTools,b5 as s,EQ as liveRuns,l as defaultAttachmentStore,xQ as defaultAgentStore,t as ToolNamespace,LQ as Skill,f as ScopedAttachments,h as SKILLS_NAMESPACE,P as PendingEscalation,TQ as OpenAIProvider,ZQ as MemoryLiveRuns,d as MemoryAttachmentStore,GQ as MemoryAgentStore,y as LiveRunNotFoundError,x as InvalidAttachmentScopeError,I as FrameCursorEvictedError,kQ as AzureOpenAIProvider,v as AttachmentNotFoundError,q as AgentTool,$Q as AgentProvider,R2 as AgentController,CQ as Agent};
|
|
18
|
+
`)}}if($.length>0){let X=W($);if(X)yield X}let V=Y();if(V)yield V}async function*H2(Q,$={}){let Z=new Map,G=new Set,J=!1;for await(let Y of V5(Q)){if(Y.data==="[DONE]")break;let W;try{W=JSON.parse(Y.data)}catch{continue}switch(typeof W.type==="string"?W.type:Y.event){case"response.output_text.delta":{let X=String(W.delta??"");if(!X)break;yield $.structuredOutput?{type:"output-delta",delta:X}:{type:"text-delta",delta:X};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let X=String(W.delta??"");if(!X)break;yield{type:"reasoning-delta",delta:X,id:W.item_id};break}case"response.output_item.added":{let X=W.item;if(!X)break;if(X.type==="function_call"){let B=String(X.id??W.item_id??X.call_id??"");Z.set(B,{callId:String(X.call_id??B),name:String(X.name??""),namespace:typeof X.namespace==="string"&&X.namespace?X.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let X=Z.get(String(W.item_id??""));if(!X)break;let B=String(W.delta??"");if(!B)break;yield{type:"tool-call-delta",toolCallId:X.callId,name:X.name,argsDelta:B,...X.namespace?{namespace:X.namespace}:{}};break}case"response.function_call_arguments.done":{let X=String(W.item_id??""),B=Z.get(X);if(!B)break;B.done=!0,yield{type:"tool-call",toolCallId:B.callId,name:B.name,args:String(W.arguments??""),...B.namespace?{namespace:B.namespace}:{}};break}case"response.output_item.done":{let X=W.item;if(!X)break;if(X.type==="function_call"){let B=String(X.id??W.item_id??X.call_id??""),K=Z.get(B);if(K?.done)break;let H=(typeof X.namespace==="string"?X.namespace:"")||K?.namespace;if(yield{type:"tool-call",toolCallId:String(X.call_id??B),name:String(X.name??K?.name??""),args:String(X.arguments??""),...H?{namespace:H}:{}},K)K.done=!0;break}if(X.type==="tool_search_call"||X.type==="tool_search_output"){let B=X5(X);if(B.loaded.length===0&&B.namespaces.length===0)break;let K=String(X.tool_search_call_id??X.id??"");if(G.has(K))break;G.add(K),yield{type:"tool-search",...B}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(W.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{J=!0,yield{type:"finish",reason:"stop",usage:_Q(W.response?.usage)};break}case"response.incomplete":{J=!0;let X=_Q(W.response?.usage),B=W.response?.incomplete_details?.reason;if(B==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:B5(W.response?.content_filters),retryable:!1}},yield{type:"finish",reason:"error",usage:X};break}yield{type:"finish",reason:B==="max_output_tokens"?"length":"stop",usage:X};break}case"response.failed":case"error":{J=!0;let X=W.response?.error??W.error??W;yield{type:"error",error:K5(X)},yield{type:"finish",reason:"error",usage:_Q(W.response?.usage)};break}}if(J)return}if(!J)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield{type:"finish",reason:"error",usage:A()}}function X5(Q){let $=[],Z=[];return z2(Q.results??Q.tools??Q.loaded??Q.output,$,Z,0),{loaded:PQ($),namespaces:PQ(Z)}}function z2(Q,$,Z,G){if(!Array.isArray(Q)||G>4)return;for(let J of Q){if(typeof J==="string"){$.push(J);continue}if(!J||typeof J!=="object")continue;let Y=J,W=typeof Y.name==="string"?Y.name:typeof Y.tool_name==="string"?Y.tool_name:"",V=Y.tools??Y.functions;if(Array.isArray(V)){if(W)Z.push(W);z2(V,$,Z,G+1);continue}if(W)$.push(W)}}function PQ(Q){return Q.filter(($,Z)=>Q.indexOf($)===Z)}function B5(Q){if(!Array.isArray(Q))return"The provider's content filter blocked this request.";let Z=[];for(let G of Q){if(!G||typeof G!=="object")continue;let J=G,Y=J.content_filter_results;if(!Y||typeof Y!=="object")continue;for(let[W,V]of Object.entries(Y))if(V&&typeof V==="object"&&V.filtered===!0)Z.push(`${W} (${String(J.source_type??"unknown")})`)}return Z.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${PQ(Z).join(", ")}.`}function K5(Q){let $=typeof Q?.message==="string"?Q.message:"The provider stream failed.",Z=String(Q?.code??"").toLowerCase();if(Z==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(Z==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(Z.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function A(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function _Q(Q){if(!Q)return A();let $=Number(Q.input_tokens??0),Z=Number(Q.output_tokens??0),G={inputTokens:$,outputTokens:Z,totalTokens:Number(Q.total_tokens??$+Z)},J=Q.output_tokens_details?.reasoning_tokens;if(typeof J==="number")G.reasoningTokens=J;let Y=Q.input_tokens_details?.cached_tokens;if(typeof Y==="number")G.cachedInputTokens=Y;return G}async function*U2(Q){if(!Q)return;let $=Q.getReader(),Z=new TextDecoder;try{while(!0){let{done:J,value:Y}=await $.read();if(J)break;if(Y)yield Z.decode(Y,{stream:!0})}let G=Z.decode();if(G)yield G}finally{$.releaseLock()}}async function*MQ(Q,$,Z){let G;try{G=await NQ(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify($)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(J){let Y=R(J);if(Y.code!=="aborted")yield{type:"error",error:Y};yield{type:"finish",reason:Y.code==="aborted"?"aborted":"error",usage:A()};return}try{yield*H2(U2(G.body),{structuredOutput:Z.structuredOutput})}catch(J){let Y=R(J);if(Y.code==="aborted"){yield{type:"finish",reason:"aborted",usage:A()};return}yield{type:"error",error:Y},yield{type:"finish",reason:"error",usage:A()}}}async function qQ(Q,$){let Z=new FormData;Z.set("purpose","user_data"),Z.set("file",$);let J=await(await NQ(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:Z},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl})).json();if(!J?.id)throw Error("The provider accepted the upload but returned no file id.");return J.id}function SQ(Q){let $=H5(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Z=z5($);if(Z?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Z.major>1,toolSearch:D2(Z)};if(Z?.kind==="gpt")return{reasoning:Z.major>=5,structuredOutput:Z.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:Z.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:D2(Z)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function D2(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function H5(Q){return Q.trim().toLowerCase()}function z5(Q){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(Q);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let Z=/^o(\d+)(?:[-.]|$)/.exec(Q);if(Z?.[1])return{kind:"o",major:Number(Z[1]),minor:0};return null}function RQ(Q,$){let{capabilities:Z}=$,G={model:$.model,input:U5(Q.messages,Z),stream:!0};if(Q.systemPrompt)G.instructions=Q.systemPrompt;let J=P5(Q.tools,Z);if(J.length>0){if(G.tools=J,!Z.parallelToolCalls)G.parallel_tool_calls=!1}if(Q.output)G.text={format:{type:"json_schema",name:Q.output.name,schema:Q.output.schema,strict:!0}};if(Q.reasoning&&Z.reasoning)G.reasoning={effort:Q.reasoning,summary:"auto"};if(typeof Q.temperature==="number")G.temperature=Q.temperature;if(typeof Q.maxOutputTokens==="number")G.max_output_tokens=Q.maxOutputTokens;return G}function U5(Q,$){let Z=[];for(let G of Q){let J=G.role,Y=[],W=()=>{if(Y.length===0)return;Z.push({type:"message",role:J,content:Y}),Y=[]};for(let V of G.content??[])switch(V.type){case"text":{if(!V.text)break;Y.push(e(J,V.text));break}case"output":{if(V.partial)break;Y.push(e(J,JSON.stringify(V.value)));break}case"file":{if(J==="assistant")break;let X=j5(V);if(!$.fileInput){if(X)Y.push(e(J,O2(V,!1)));break}if(V.fileId?.startsWith(C))throw Error(`FilePart.fileId holds a gemi attachment id (${V.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!V.fileId&&!X)throw Error("FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_\u2026`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.");if(X)Y.push(e(J,O2(V,!!V.fileId)));if(V.fileId)Y.push(L5(V));break}case"reasoning":{W();let X=N5(V);if(X)Z.push(X);break}case"tool-call":{if(V.partial)break;W(),Z.push({type:"function_call",call_id:V.toolCallId,name:String(V.name),arguments:JSON.stringify(V.input??{})});break}case"tool-result":{W(),Z.push({type:"function_call_output",call_id:V.toolCallId,output:_5(V)});break}}W()}return O5(Z)}var D5="No result was recorded for this tool call. Assume it did not complete.";function O5(Q){let $=new Set,Z=new Set,G=[];for(let Y of Q){if(Y.type==="function_call"){let W=String(Y.call_id);if($.has(W))continue;$.add(W)}else if(Y.type==="function_call_output"){let W=String(Y.call_id);if(!$.has(W)||Z.has(W))continue;Z.add(W)}G.push(Y)}if(Z.size===$.size)return G;let J=[];for(let Y of G){if(J.push(Y),Y.type!=="function_call")continue;let W=String(Y.call_id);if(Z.has(W))continue;Z.add(W),J.push({type:"function_call_output",call_id:W,output:D5})}return J}function e(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function j5(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(C)?$:void 0}function O2(Q,$){let Z=[`id=${JSON.stringify(Q.attachmentId)}`];if(Q.name)Z.push(`name=${JSON.stringify(Q.name)}`);if(Q.mimeType)Z.push(`mimeType=${JSON.stringify(Q.mimeType)}`);let G=`attachment ${Z.join(" ")}`;return $?`[${G}]`:`[${G} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function L5(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":F5(Q.name))?"input_image":"input_file",file_id:Q.fileId}}function F5(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&C5.has($[1])}var C5=new Set(["jpeg","jpg","png","gif","webp"]);function N5(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function _5(Q){if(Q.status==="ok")return typeof Q.output==="string"?Q.output:JSON.stringify(Q.output??null);if(Q.status==="denied"){let $=Q.reason?` Reason given: ${Q.reason}`:"";if(Q.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${Q.error?.code??"unknown"}): ${Q.error?.message??"no message"}`}function j2(Q){return Array.isArray(Q.tools)}function P5(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let J=[];for(let Y of Q)if(j2(Y))for(let W of Y.tools)J.push(QQ(W,!1));else J.push(QQ(Y,!1));return J}let Z=[],G=!1;for(let J of Q)if(j2(J)){let Y=J.tools.map((W)=>{if(W.deferred)G=!0;return QQ(W,!0)});Z.push({type:"namespace",name:J.name,description:J.description,tools:Y})}else{if(J.deferred)G=!0;Z.push(QQ(J,!0))}if(G)Z.push({type:"tool_search"});return Z}function QQ(Q,$){let Z={type:"function",name:Q.name,description:Q.description,parameters:Q.parameters,strict:Q.strict};if($&&Q.deferred)Z.defer_loading=!0;return Z}var F2=120000,C2=2;function T(Q){return typeof process>"u"?void 0:process.env?.[Q]}class $Q{static models(){return[]}normalizeError(Q){return R(Q)}}var N2=["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.4-nano","gpt-5.2","gpt-5.1","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini","o4-mini","o3","o3-mini"];class TQ extends $Q{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=SQ(Q),this.config=$}static model(Q,$){return new TQ(Q,$)}static models(){return N2}stream(Q){let $=RQ(Q,{model:this.model,capabilities:this.capabilities});return MQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return qQ(this.endpoint(),Q)}baseURL(){return(this.config.baseURL??T("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,"")}endpoint(){let Q=this.baseURL(),$=this.config;return{responsesUrl:`${Q}/responses`,filesUrl:`${Q}/files`,headers:async()=>{let Z=$.apiKey??T("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...$.headers}},timeoutMs:$.timeoutMs??F2,maxRetries:$.maxRetries??C2}}}var M5="preview";function L2(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function q5(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}class kQ extends $Q{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=SQ(Q),this.config=$}static model(Q,$){return new kQ(Q,$)}static models(){return N2}stream(Q){let $=RQ(Q,{model:this.deployment(),capabilities:this.capabilities});return MQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return qQ(this.endpoint(),Q)}deployment(){return this.config.deployment??this.model}base(){let Q=this.config,$=Q.baseURL??Q.endpoint??T("AZURE_OPENAI_ENDPOINT");if($)return L2($);let Z=Q.resourceName??T("AZURE_OPENAI_RESOURCE_NAME")??T("AZURE_RESOURCE_NAME");return Z?L2(`https://${Z.trim()}.cognitiveservices.azure.com`):""}endpoint(){let Q=this.config,$=this.base(),Z=Q.apiVersion??T("AZURE_OPENAI_API_VERSION")??M5,G=q5(Z),J=`?api-version=${encodeURIComponent(Z)}`;return{responsesUrl:`${$}${G}/responses${J}`,filesUrl:`${$}${G}/files${J}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let Y=Q.apiKey??T("AZURE_OPENAI_API_KEY");return{...Y?{"api-key":Y}:{},...Q.headers}},timeoutMs:Q.timeoutMs??F2,maxRetries:Q.maxRetries??C2}}}class I extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(Q,$,Z){super(`Frame ${$} of run ${Q} has been evicted; the oldest frame still buffered is ${Z}. Reload the thread instead of resuming.`);this.runId=Q;this.requested=$;this.oldest=Z}}class y extends Error{runId;code="live_run_not_found";constructor(Q){super(`No live run ${Q} in this process.`);this.runId=Q}}class ZQ{ttlMs;maxFrames;runs=new Map;byThread=new Map;byClientRun=new Map;constructor(Q={}){this.ttlMs=Q.ttlMs??60000,this.maxFrames=Q.maxFrames??4096}register(Q,$={}){let Z={run:Q,threadId:$.threadId,clientRunId:$.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evictAt:null,wake:new Set,version:0};if(this.runs.set(Q.runId,Z),$.threadId)this.byThread.set($.threadId,Q.runId);if($.clientRunId)this.byClientRun.set($.clientRunId,Q.runId);return this.pump(Z,$)}findByClientRunId(Q){let $=this.byClientRun.get(Q);return $&&this.runs.has($)?$:null}async find(Q){let $=this.byThread.get(Q.threadId);if(!$)return null;let Z=this.runs.get($);if(!Z)return null;return{runId:$,seq:Z.lastSeq}}get(Q){return this.runs.get(Q)?.run??null}replay(Q,$){let Z=this.runs.get(Q);if(!Z)throw new y(Q);if($!==void 0&&$<Z.lostBefore)throw new I(Q,$,Z.lostBefore);let G=Z.frames[0]?.seq;return this.drain(Z,Q,$??G??Z.lastSeq+1)}clear(){for(let Q of this.runs.values()){if(Q.evictAt)clearTimeout(Q.evictAt);Q.ended=!0,this.notify(Q)}this.runs.clear(),this.byThread.clear(),this.byClientRun.clear()}get size(){return this.runs.size}async pump(Q,$){let Z=Promise.resolve();try{for await(let G of Q.run.frames()){if(Q.frames.push(G),Q.lastSeq=G.seq,Q.frames.length>this.maxFrames){let Y=Q.frames.shift();if(Y)Q.lostBefore=Y.seq+1}this.notify(Q);let J=$.onEvent;if(J)Z=Z.then(()=>J(G.event)).catch((Y)=>_2($,Y))}}catch(G){_2($,G)}finally{Q.ended=!0,this.notify(Q),this.scheduleEviction(Q),await Z}}async*drain(Q,$,Z){let G=Z;while(!0){let J=Q.version;for(;;){if(G<Q.lostBefore)throw new I($,G,Q.lostBefore);let Y=Q.frames,W=Y[0]?.seq;if(W===void 0)break;let V=Math.max(0,G-W);if(V>=Y.length)break;let X=Y[V];yield X,G=X.seq+1}if(Q.ended&&G>Q.lastSeq)return;await this.wait(Q,J)}}wait(Q,$){if(Q.version!==$)return Promise.resolve();return new Promise((Z)=>Q.wake.add(Z))}notify(Q){Q.version++;let $=Array.from(Q.wake);Q.wake.clear();for(let Z of $)Z()}scheduleEviction(Q){if(Q.evictAt)return;let $=setTimeout(()=>{let Z=Q.run.runId;if(this.runs.delete(Z),Q.threadId&&this.byThread.get(Q.threadId)===Z)this.byThread.delete(Q.threadId);if(Q.clientRunId&&this.byClientRun.get(Q.clientRunId)===Z)this.byClientRun.delete(Q.clientRunId);this.notify(Q)},this.ttlMs);$.unref?.(),Q.evictAt=$}}var EQ=new ZQ;function _2(Q,$){try{Q.onInternalError?.($)}catch{}}class GQ{ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor(Q={}){this.ttlMs=Q.ttlMs??86400000,this.clientOwnedIds=Q.clientOwnedIds??!1}async createThread(Q){let $=crypto.randomUUID();return this.threads.set($,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:$}}async loadThread(Q){this.sweep();let $=this.threads.get(Q);if(!$)return this.clientOwnedIds?[]:null;return $.touchedAt=Date.now(),$.messages.slice()}async appendMessages(Q,$){this.sweep();let Z=this.threads.get(Q);if(!Z){if(!this.clientOwnedIds)throw Error(`Thread ${Q} does not exist here, or has expired.`);Z={messages:[],touchedAt:Date.now()},this.threads.set(Q,Z)}for(let G of $){let J=Z.messages.findIndex((Y)=>Y.id===G.id);if(J===-1)Z.messages.push(G);else Z.messages[J]=G}Z.touchedAt=Date.now()}delete(Q){this.threads.delete(Q)}get size(){return this.threads.size}sweep(Q=Date.now()){if(Q-this.lastSweep<60000)return;this.lastSweep=Q;for(let[$,Z]of this.threads)if(Q-Z.touchedAt>this.ttlMs)this.threads.delete($)}}var xQ=new GQ;var S5=S2,JQ=new Map,P2=new WeakMap,YQ=new Map;class T2 extends S5{static kind="agent-controller";store=xQ;liveRuns=EQ;attachments=d;attachmentStorage=R2;hookHoldMs=30000;instructions(Q){}requireThread=!1;authorizeRequest(Q,$){}async stream(Q=new g){let $=await AQ(Q);if($.error)return WQ($);let Z=$.body,G=typeof Z.threadId==="string"?Z.threadId:void 0,J=T5(Z);if(J.error)return WQ({body:{},error:J.error});let Y=J.turn,W=typeof Z.clientRunId==="string"?Z.clientRunId:void 0;if(this.requireThread&&!G)return N(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});let V=W?{cancelled:!1}:null;if(V)YQ.set(W,V);let X=async()=>{let B;if(G){let F=await this.store.loadThread(G);if(!F)return N(404,{code:"thread_not_found",message:`Thread ${G} does not exist here, or has expired.`});B=F}else B=Array.isArray(Z.messages)?Z.messages:[];let K=await this.instructions(Q)||void 0,H=await this.attachmentsFor(Q,G);if(V?.cancelled)return M2();let z=this.agent.stream({messages:B,turn:Y,req:Q,threadId:G,instructions:K,attachments:H}),O={req:Q,runId:z.runId,threadId:G},D=this.liveRuns.register(z,{threadId:G,clientRunId:W,onEvent:(F)=>this.dispatchEvent(F,O),onInternalError:(F)=>this.reportHookFailure(F)}),{stored:U,hooks:j}=this.persistRun(z,O,D);return P2.set(z,U),Q.ctx?.()?.waitUntil(j),z.toResponse()};try{if(await this.authorizeRequest(Q,{route:"stream",threadId:G}),V?.cancelled)return M2();return G?await this.withThread(G,X):await X()}finally{if(V&&YQ.get(W)===V)YQ.delete(W)}}async withThread(Q,$){let Z=JQ.get(Q)??Promise.resolve(),G,J=new Promise((W)=>{G=W}),Y=Z.then(()=>J);JQ.set(Q,Y),await Z;try{let W=await this.liveRuns.find({threadId:Q}),V=W?this.liveRuns.get(W.runId):null;if(V)V.stop({reason:"superseded by a later turn on this thread"}),await P2.get(V);return await $()}finally{if(G(),JQ.get(Q)===Y)JQ.delete(Q)}}async attach(Q=new g){let $=await AQ(Q);if($.error)return WQ($);let Z=$.body,G=typeof Z.threadId==="string"?Z.threadId:x5(Q,"threadId");if(!G)return N(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(Q,{route:"attach",threadId:G});let J=await this.liveRuns.find({threadId:G});if(!J)return N(404,{code:"no_live_run",message:`No run in progress for thread ${G} in this process.`});let Y=typeof Z.runId==="string"?Z.runId:void 0,W=Y&&Y!==J.runId?void 0:E5(Q,Z);try{return oQ(this.liveRuns.replay(J.runId,W))}catch(V){if(V instanceof I)return N(410,{code:V.code,message:V.message,oldestSeq:V.oldest});if(V instanceof y)return N(404,{code:V.code,message:V.message});throw V}}async stop(Q=new g){let $=await AQ(Q);if($.error)return WQ($);let Z=$.body;await this.authorizeRequest(Q,{route:"stop",threadId:typeof Z.threadId==="string"?Z.threadId:void 0});let G=typeof Z.runId==="string"?Z.runId:void 0;if(!G&&typeof Z.clientRunId==="string"){if(G=this.liveRuns.findByClientRunId(Z.clientRunId)??void 0,!G){let Y=YQ.get(Z.clientRunId);if(Y)return Y.cancelled=!0,{stopped:!0}}}if(!G&&typeof Z.threadId==="string")G=(await this.liveRuns.find({threadId:Z.threadId}))?.runId;let J=G?this.liveRuns.get(G):null;if(!J)return{stopped:!1};return J.stop({reason:typeof Z.reason==="string"?Z.reason:void 0}),{stopped:!0}}attachmentScope(Q,$){let Z=Q.ctx()?.user,G=Z?.id??Z?.publicId;if(G!==void 0&&G!==null&&String(G)!=="")return{key:`user:${String(G)}`};if($)return{key:`thread:${$}`};return null}attachmentDestination(Q,$){return"both"}async attachmentsFor(Q,$){let Z=await this.attachmentScope(Q,$);if(!Z)return null;return new f(this.attachments,this.attachmentStorage,Z)}async upload(Q=new g){let $=await Q.rawRequest.formData(),Z=$.get("file");if(!(Z instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let G=Z instanceof File&&Z.name?Z.name:"upload",J=Z.type||"application/octet-stream",Y=$.get("threadId");await this.authorizeRequest(Q,{route:"upload",threadId:typeof Y==="string"&&Y.length>0?Y:void 0});let W=typeof Y==="string"&&Y.length>0&&await this.store.loadThread(Y)!==null?Y:void 0,V=await this.attachmentDestination(Z,Q),X=A5(V,$.get("destination")),B=await this.attachmentScope(Q,W),K=X!=="provider"&&!B;if(K){if(X==="storage")throw Error('This upload was routed to storage, but `attachmentScope()` returned null for the request, so there is no subject to file the attachment under. Guard the route (`this.agent(Chat).middleware({ upload: "auth" })`), send a `threadId` with the upload, or override `attachmentScope()`.');I5()}if(X==="provider"||!B){let j={fileId:await this.agent.provider.upload(Z),name:G,mimeType:J,size:Z.size,destination:"provider"};if(K)j.downgraded="no_scope";return j}let H=KQ(),z=await this.attachmentStorage.put({name:HQ(H,G),body:Z,contentType:J}),O=X==="both"?await this.agent.provider.upload(Z):void 0,D={id:H,scopeKey:B.key,fileId:O,objectName:z,name:G,mimeType:J,size:Z.size,createdAt:new Date().toISOString(),destination:X};return await this.attachments.put(B,D),{fileId:O,attachmentId:H,name:G,mimeType:J,size:Z.size,destination:X}}onMessage(Q,$){}onToolCall(Q,$){}onAwaitingInput(Q,$){}onError(Q,$){}onStreamComplete(Q,$){}reportHookFailure(Q){console.error("[gemi/ai] agent controller hook failed",Q)}async dispatchEvent(Q,$){switch(Q.type){case"tool-call":if(!Q.part.partial&&!Q.resent)await this.onToolCall({toolCallId:Q.part.toolCallId,name:String(Q.part.name),input:Q.part.input},$);return;case"awaiting-input":await this.onAwaitingInput(Q.pending,$);return;case"error":await this.onError(Q.error,$);return;default:return}}persistRun(Q,$,Z){let G=Promise.resolve(),J=(async()=>{let W;try{W=await Q.result()}catch(X){G=this.safely(()=>this.onError({code:"unknown",message:X instanceof Error?X.message:String(X),retryable:!1},$));return}let V=W.messages;if($.threadId&&V.length>0)try{await this.store.appendMessages($.threadId,V)}catch(X){this.reportHookFailure(X)}G=this.notifyRun(W,V,$)})(),Y=J.then(()=>b5(Promise.all([G,Z]).then(()=>{}),this.hookHoldMs));return{stored:J,hooks:Y}}async notifyRun(Q,$,Z){for(let G of $)await this.safely(()=>this.onMessage(G,Z));await this.safely(()=>this.onStreamComplete(Q,Z))}async safely(Q){try{await Q()}catch($){this.reportHookFailure($)}}}async function AQ(Q){let $=Q?.rawRequest;if(!$||$.method==="GET"||$.method==="HEAD"||!$.body)return{body:{}};if(!R5($.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let Z;try{Z=await $.text()}catch{return{body:{},error:"The request body could not be read."}}if(!Z.trim())return{body:{}};let G;try{G=JSON.parse(Z)}catch{return{body:{},error:"The request body is not valid JSON."}}if(G===null||typeof G!=="object"||Array.isArray(G))return{body:{},error:"The request body must be a JSON object."};return{body:G}}function R5(Q){if(typeof Q!=="string")return!1;let[$]=Q.split(";",1);return $.trim().toLowerCase()==="application/json"}function WQ(Q){return N(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function T5(Q){let $=Q.turn&&typeof Q.turn==="object"?Q.turn:Q,Z={};if(typeof $.text==="string")Z.text=$.text;if(Array.isArray($.files)){let G=k5($.files);if(typeof G==="string")return{error:G};Z.files=G}if(Array.isArray($.toolResults))Z.toolResults=$.toolResults;return Object.keys(Z).length>0?{turn:Z}:{}}function k5(Q){let $=[];for(let[Z,G]of Q.entries()){let J=`turn.files[${Z}]`;if(!G||typeof G!=="object"||Array.isArray(G))return`${J} must be an object.`;let Y={};for(let K of["fileId","attachmentId","name","mimeType"]){let H=G[K];if(H===void 0||H===null||H==="")continue;if(typeof H!=="string")return`${J}.${K} must be a string.`;Y[K]=H}let{fileId:W,attachmentId:V,name:X,mimeType:B}=Y;if(W?.startsWith(C))return`${J}.fileId holds a gemi attachment id (${W}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(V!==void 0&&!V.startsWith(C))return`${J}.attachmentId is not a gemi attachment id: it must start with "${C}".`;if(!W&&!V)return`${J} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...W?{fileId:W}:{},...V?{attachmentId:V}:{},...X!==void 0?{name:X}:{},...B!==void 0?{mimeType:B}:{}})}return $}function E5(Q,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let G=Math.floor($.cursor);if(G>=0)return G+1;return}let Z=Q?.rawRequest?.headers?.get("Last-Event-ID");if(Z){let G=Number.parseInt(Z,10);if(Number.isFinite(G))return Math.max(0,G+1)}return}function x5(Q,$){let Z=Q?.search?.get($);return typeof Z==="string"?Z:void 0}function M2(){return N(409,{code:"stopped",message:"The turn was stopped before it started."})}function N(Q,$){return new Response(JSON.stringify({error:$}),{status:Q,headers:{"Content-Type":"application/json"}})}function A5(Q,$){if(typeof $!=="string"||$.length===0)return Q;if($!=="both"&&$!=="provider"&&$!=="storage")throw Error(`Unknown attachment destination "${$}". Expected "both", "provider" or "storage".`);if($===Q||Q==="both"&&$==="storage")return $;if(Q==="both"&&$==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${$}" destination, but the server's policy for it is "${Q}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var q2=!1;function I5(){if(q2)return;q2=!0,console.warn("[gemi/ai] An upload had no attachment scope, so its bytes were sent to the model provider only and no attachment id was minted \u2014 a tool cannot forward this file. Guard the route with auth, send a `threadId` with the upload, or override `attachmentScope()`.")}var w5=2147483647;function b5(Q,$){let Z=Q.then(()=>{},()=>{});if(!($<=w5))return Z;let G,J=new Promise((Y)=>{G=setTimeout(Y,$)});return Promise.race([Z,J]).finally(()=>clearTimeout(G))}export{s2 as toAgentTools,v5 as s,EQ as liveRuns,d as defaultAttachmentStore,xQ as defaultAgentStore,t as ToolNamespace,FQ as Skill,f as ScopedAttachments,h as SKILLS_NAMESPACE,M as PendingEscalation,TQ as OpenAIProvider,ZQ as MemoryLiveRuns,l as MemoryAttachmentStore,GQ as MemoryAgentStore,y as LiveRunNotFoundError,x as InvalidAttachmentScopeError,I as FrameCursorEvictedError,kQ as AzureOpenAIProvider,v as AttachmentNotFoundError,S as AgentTool,$Q as AgentProvider,T2 as AgentController,CQ as Agent};
|
|
19
19
|
|
|
20
|
-
//# debugId=
|
|
20
|
+
//# debugId=057203A7B61B126764756E2164756E21
|