gemi 0.108.0 → 0.110.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/index.js +2 -2
- package/dist/ai/index.js.map +1 -1
- package/dist/app/index.js +2 -2
- package/dist/app/index.js.map +1 -1
- package/dist/bin/gemi.js +535 -55
- package/dist/bin/gemi.js.map +11 -6
- package/dist/bun/plugin.js +2 -2
- package/dist/bun/plugin.js.map +1 -1
- package/dist/bun/preload.js +2 -2
- package/dist/bun/preload.js.map +1 -1
- package/dist/{chunk-xpyhmg45.js → chunk-09ypnhjv.js} +3 -3
- package/dist/{chunk-3s3awh38.js.map → chunk-09ypnhjv.js.map} +1 -1
- package/dist/{chunk-rjernda5.js → chunk-0d9qsmx2.js} +3 -3
- package/dist/{chunk-rjernda5.js.map → chunk-0d9qsmx2.js.map} +1 -1
- package/dist/{chunk-xg9vye7c.js → chunk-0sjh5v1n.js} +1 -1
- package/dist/{chunk-2mhx4e4g.js → chunk-11fsn5mr.js} +3 -3
- package/dist/{chunk-2mhx4e4g.js.map → chunk-11fsn5mr.js.map} +1 -1
- package/dist/{chunk-wzqkdmjd.js → chunk-1c1d0e60.js} +3 -3
- package/dist/{chunk-wzqkdmjd.js.map → chunk-1c1d0e60.js.map} +1 -1
- package/dist/{chunk-wedwkqe7.js → chunk-1kr25rcg.js} +3 -3
- package/dist/{chunk-wedwkqe7.js.map → chunk-1kr25rcg.js.map} +1 -1
- package/dist/{chunk-6wrhc9bq.js → chunk-1pem26zc.js} +3 -3
- package/dist/{chunk-6wrhc9bq.js.map → chunk-1pem26zc.js.map} +1 -1
- package/dist/{chunk-ydkjf626.js → chunk-1va15sfq.js} +2 -2
- package/dist/{chunk-ydkjf626.js.map → chunk-1va15sfq.js.map} +2 -2
- package/dist/{chunk-3s3awh38.js → chunk-1yx2e0bh.js} +2 -2
- package/dist/{chunk-xpyhmg45.js.map → chunk-1yx2e0bh.js.map} +1 -1
- package/dist/{chunk-9r3znmqq.js → chunk-303mprnv.js} +2 -2
- package/dist/{chunk-9r3znmqq.js.map → chunk-303mprnv.js.map} +1 -1
- package/dist/{chunk-sbyqs03h.js → chunk-30xjcyzh.js} +2 -2
- package/dist/{chunk-sbyqs03h.js.map → chunk-30xjcyzh.js.map} +1 -1
- package/dist/{chunk-k17prwhx.js → chunk-358sdcx9.js} +3 -3
- package/dist/{chunk-k17prwhx.js.map → chunk-358sdcx9.js.map} +1 -1
- package/dist/{chunk-2gmgd05c.js → chunk-3cg7y62b.js} +2 -2
- package/dist/{chunk-2gmgd05c.js.map → chunk-3cg7y62b.js.map} +1 -1
- package/dist/{chunk-t26n9vzw.js → chunk-3y8q8x11.js} +2 -2
- package/dist/{chunk-t26n9vzw.js.map → chunk-3y8q8x11.js.map} +1 -1
- package/dist/chunk-4mfrgd5m.js +34 -0
- package/dist/chunk-4mfrgd5m.js.map +10 -0
- package/dist/chunk-5cygrbxv.js +4 -0
- package/dist/{chunk-vj2t77x1.js.map → chunk-5cygrbxv.js.map} +2 -2
- package/dist/{chunk-tvy2fqza.js → chunk-5stgtwqw.js} +2 -2
- package/dist/{chunk-tvy2fqza.js.map → chunk-5stgtwqw.js.map} +1 -1
- package/dist/chunk-61f4m5px.js +6 -0
- package/dist/chunk-61f4m5px.js.map +12 -0
- package/dist/chunk-6chz1ktz.js +9 -0
- package/dist/chunk-6chz1ktz.js.map +13 -0
- package/dist/{chunk-1rs13253.js → chunk-6vr7f5fq.js} +4 -4
- package/dist/{chunk-1rs13253.js.map → chunk-6vr7f5fq.js.map} +1 -1
- package/dist/{chunk-2q7m8a16.js → chunk-7tx5y712.js} +2 -2
- package/dist/{chunk-2q7m8a16.js.map → chunk-7tx5y712.js.map} +1 -1
- package/dist/{chunk-eytdyahy.js → chunk-8afxrmdc.js} +3 -3
- package/dist/{chunk-eytdyahy.js.map → chunk-8afxrmdc.js.map} +1 -1
- package/dist/{chunk-anp4kv3w.js → chunk-8b2tw2yp.js} +1 -1
- package/dist/{chunk-kqff894s.js → chunk-9rchedr4.js} +2 -2
- package/dist/{chunk-kqff894s.js.map → chunk-9rchedr4.js.map} +1 -1
- package/dist/{chunk-6rz8kyqb.js → chunk-9s851qz8.js} +2 -2
- package/dist/{chunk-6rz8kyqb.js.map → chunk-9s851qz8.js.map} +1 -1
- package/dist/{chunk-8pynv9rw.js → chunk-a6453d9s.js} +3 -3
- package/dist/{chunk-8pynv9rw.js.map → chunk-a6453d9s.js.map} +1 -1
- package/dist/{chunk-5wt25tyd.js → chunk-bn5yn731.js} +2 -2
- package/dist/{chunk-5wt25tyd.js.map → chunk-bn5yn731.js.map} +1 -1
- package/dist/{chunk-zrdbytx4.js → chunk-c098fzvk.js} +2 -2
- package/dist/{chunk-zrdbytx4.js.map → chunk-c098fzvk.js.map} +1 -1
- package/dist/{chunk-mhq2bd9c.js → chunk-cttmy1jp.js} +4 -4
- package/dist/{chunk-mhq2bd9c.js.map → chunk-cttmy1jp.js.map} +2 -2
- package/dist/{chunk-331s9wqr.js → chunk-cy5qp6mz.js} +3 -3
- package/dist/{chunk-331s9wqr.js.map → chunk-cy5qp6mz.js.map} +1 -1
- package/dist/{chunk-kh273hj0.js → chunk-ddr4qvvt.js} +3 -3
- package/dist/{chunk-kh273hj0.js.map → chunk-ddr4qvvt.js.map} +1 -1
- package/dist/chunk-e1n8zs3h.js +58 -0
- package/dist/chunk-e1n8zs3h.js.map +14 -0
- package/dist/{chunk-2xqrh6d0.js → chunk-et4pv1b1.js} +1 -1
- package/dist/{chunk-a1g0bahx.js → chunk-frerzsxq.js} +2 -2
- package/dist/{chunk-a1g0bahx.js.map → chunk-frerzsxq.js.map} +1 -1
- package/dist/{chunk-pj2e1p07.js → chunk-gb37722w.js} +3 -3
- package/dist/{chunk-pj2e1p07.js.map → chunk-gb37722w.js.map} +1 -1
- package/dist/chunk-h3864a8z.js +17 -0
- package/dist/{chunk-ncfxmtd5.js.map → chunk-h3864a8z.js.map} +14 -11
- package/dist/{chunk-661wezaf.js → chunk-h4sw6nt3.js} +3 -3
- package/dist/{chunk-661wezaf.js.map → chunk-h4sw6nt3.js.map} +1 -1
- package/dist/{chunk-m31pfz1s.js → chunk-he7z7y9j.js} +2 -2
- package/dist/{chunk-m31pfz1s.js.map → chunk-he7z7y9j.js.map} +1 -1
- package/dist/{chunk-kstvyvr0.js → chunk-hf7a51s3.js} +2 -2
- package/dist/{chunk-kstvyvr0.js.map → chunk-hf7a51s3.js.map} +1 -1
- package/dist/chunk-hn67spz6.js +5 -0
- package/dist/{chunk-mrvcaakf.js.map → chunk-hn67spz6.js.map} +1 -1
- package/dist/{chunk-fq3sb3xt.js → chunk-jbrwt3cs.js} +4 -4
- package/dist/{chunk-fq3sb3xt.js.map → chunk-jbrwt3cs.js.map} +1 -1
- package/dist/{chunk-jnw73s8c.js → chunk-k1vw22t2.js} +2 -2
- package/dist/{chunk-jnw73s8c.js.map → chunk-k1vw22t2.js.map} +1 -1
- package/dist/chunk-k1xt2tw7.js +4 -0
- package/dist/{chunk-hdhahvd4.js.map → chunk-k1xt2tw7.js.map} +2 -2
- package/dist/chunk-k9wgtrc5.js +24 -0
- package/dist/{chunk-h2hdpm70.js.map → chunk-k9wgtrc5.js.map} +4 -4
- package/dist/{chunk-00y49jcf.js → chunk-kf71mjxa.js} +3 -3
- package/dist/{chunk-00y49jcf.js.map → chunk-kf71mjxa.js.map} +1 -1
- package/dist/{chunk-kqz8jp6v.js → chunk-m6ystvtk.js} +2 -2
- package/dist/{chunk-kqz8jp6v.js.map → chunk-m6ystvtk.js.map} +1 -1
- package/dist/{chunk-ftgd68se.js → chunk-mb7q7s0a.js} +3 -3
- package/dist/{chunk-ftgd68se.js.map → chunk-mb7q7s0a.js.map} +1 -1
- package/dist/{chunk-rh9j8cwv.js → chunk-mn5xw79b.js} +3 -3
- package/dist/{chunk-rh9j8cwv.js.map → chunk-mn5xw79b.js.map} +1 -1
- package/dist/{chunk-wsftnxzs.js → chunk-mwqg079k.js} +2 -2
- package/dist/{chunk-wsftnxzs.js.map → chunk-mwqg079k.js.map} +1 -1
- package/dist/{chunk-yebaheh7.js → chunk-nncz308h.js} +3 -3
- package/dist/{chunk-yebaheh7.js.map → chunk-nncz308h.js.map} +1 -1
- package/dist/{chunk-82hpq0bq.js → chunk-nsvktvp4.js} +2 -2
- package/dist/{chunk-82hpq0bq.js.map → chunk-nsvktvp4.js.map} +1 -1
- package/dist/{chunk-h7pafjej.js → chunk-nvv9wej6.js} +3 -3
- package/dist/{chunk-h7pafjej.js.map → chunk-nvv9wej6.js.map} +1 -1
- package/dist/chunk-p1aqq0ga.js +16 -0
- package/dist/{chunk-q7y9v2v5.js.map → chunk-p1aqq0ga.js.map} +5 -8
- package/dist/chunk-p7r2w4qw.js +5 -0
- package/dist/{chunk-h3t4n0bn.js.map → chunk-p7r2w4qw.js.map} +2 -2
- package/dist/{chunk-fwympxqk.js → chunk-pwmgqq7z.js} +2 -2
- package/dist/{chunk-fwympxqk.js.map → chunk-pwmgqq7z.js.map} +1 -1
- package/dist/chunk-pyj7cd9t.js +4 -0
- package/dist/{chunk-q2fyp44f.js.map → chunk-pyj7cd9t.js.map} +2 -2
- package/dist/{chunk-9mqqr05d.js → chunk-q9s7kwgt.js} +3 -3
- package/dist/{chunk-9mqqr05d.js.map → chunk-q9s7kwgt.js.map} +1 -1
- package/dist/{chunk-9hbwvcxn.js → chunk-qd2v93y4.js} +2 -2
- package/dist/{chunk-9hbwvcxn.js.map → chunk-qd2v93y4.js.map} +1 -1
- package/dist/{chunk-tyhrrnp5.js → chunk-rfcygmf5.js} +3 -3
- package/dist/{chunk-tyhrrnp5.js.map → chunk-rfcygmf5.js.map} +1 -1
- package/dist/{chunk-4rr9wmh8.js → chunk-s6jjy4y9.js} +2 -2
- package/dist/{chunk-4rr9wmh8.js.map → chunk-s6jjy4y9.js.map} +1 -1
- package/dist/{chunk-njkk498k.js → chunk-sq2wkynk.js} +2 -2
- package/dist/{chunk-njkk498k.js.map → chunk-sq2wkynk.js.map} +1 -1
- package/dist/{chunk-kda25fn4.js → chunk-td8tha3j.js} +3 -3
- package/dist/{chunk-kda25fn4.js.map → chunk-td8tha3j.js.map} +1 -1
- package/dist/{chunk-cfsscms3.js → chunk-tk5q8hkv.js} +4 -4
- package/dist/{chunk-cfsscms3.js.map → chunk-tk5q8hkv.js.map} +2 -2
- package/dist/{chunk-1npdp1w2.js → chunk-tq85n8zh.js} +2 -2
- package/dist/{chunk-1npdp1w2.js.map → chunk-tq85n8zh.js.map} +1 -1
- package/dist/{chunk-gqpge54c.js → chunk-twnn7r66.js} +2 -2
- package/dist/{chunk-gqpge54c.js.map → chunk-twnn7r66.js.map} +1 -1
- package/dist/chunk-w7jsh3xd.js +5 -0
- package/dist/{chunk-9jz4rggd.js.map → chunk-w7jsh3xd.js.map} +2 -2
- package/dist/{chunk-we2sj339.js → chunk-wsttx9rg.js} +2 -2
- package/dist/{chunk-we2sj339.js.map → chunk-wsttx9rg.js.map} +1 -1
- package/dist/{chunk-47rgq59q.js → chunk-wvsv1jgg.js} +2 -2
- package/dist/{chunk-47rgq59q.js.map → chunk-wvsv1jgg.js.map} +1 -1
- package/dist/chunk-x78jrs4y.js +4 -0
- package/dist/{chunk-ffagkj3x.js.map → chunk-x78jrs4y.js.map} +2 -2
- package/dist/chunk-xk930yaw.js +5 -0
- package/dist/{chunk-rn2kgbg4.js.map → chunk-xk930yaw.js.map} +2 -2
- package/dist/chunk-xkc7ftnq.js +9 -0
- package/dist/chunk-xkc7ftnq.js.map +10 -0
- package/dist/{chunk-564zfdd1.js → chunk-yer1r3t3.js} +2 -2
- package/dist/{chunk-564zfdd1.js.map → chunk-yer1r3t3.js.map} +1 -1
- package/dist/{chunk-v52dyw0q.js → chunk-yqavgpwd.js} +3 -3
- package/dist/{chunk-v52dyw0q.js.map → chunk-yqavgpwd.js.map} +1 -1
- package/dist/{chunk-hyfzw1fk.js → chunk-z10cas5r.js} +2 -2
- package/dist/{chunk-hyfzw1fk.js.map → chunk-z10cas5r.js.map} +1 -1
- package/dist/{chunk-h4x7cba0.js → chunk-zhs1r1z0.js} +3 -3
- package/dist/{chunk-h4x7cba0.js.map → chunk-zhs1r1z0.js.map} +1 -1
- package/dist/chunks/{ThemeProvider-Cqfwr6dk.js → ThemeProvider-BgLyzzOL.js} +8 -2
- package/dist/chunks/ThemeProvider-BgLyzzOL.js.map +1 -0
- package/dist/client/ClientRouterContext.d.ts.map +1 -1
- package/dist/client/ServerDataProvider.d.ts +2 -0
- package/dist/client/ServerDataProvider.d.ts.map +1 -1
- package/dist/client/createRoot.d.ts.map +1 -1
- package/dist/client/index.d.ts +2 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +127 -4
- package/dist/client/index.js.map +1 -1
- package/dist/client/islands.d.ts +127 -0
- package/dist/client/islands.d.ts.map +1 -0
- package/dist/config/index.d.ts +8 -1
- package/dist/config/index.d.ts.map +1 -1
- package/dist/config/index.js +1 -1
- package/dist/config/index.js.map +2 -2
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/Lang.d.ts +7 -1
- package/dist/facades/Lang.d.ts.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/CorsMiddleware.d.ts +13 -0
- package/dist/http/CorsMiddleware.d.ts.map +1 -1
- package/dist/http/Middleware.d.ts +11 -0
- package/dist/http/Middleware.d.ts.map +1 -1
- package/dist/http/ViewRouter.d.ts +67 -0
- package/dist/http/ViewRouter.d.ts.map +1 -1
- package/dist/http/index.d.ts +1 -1
- package/dist/http/index.d.ts.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/internal/islandRuntime.d.ts +45 -0
- package/dist/internal/islandRuntime.d.ts.map +1 -0
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/context.d.ts +24 -0
- package/dist/orm/context.d.ts.map +1 -1
- package/dist/orm/index.d.ts +1 -1
- package/dist/orm/index.d.ts.map +1 -1
- package/dist/orm/index.js +3 -3
- package/dist/orm/index.js.map +2 -2
- package/dist/server/devFetch.d.ts.map +1 -1
- package/dist/server/httpDev.d.ts.map +1 -1
- package/dist/server/httpProd.d.ts.map +1 -1
- package/dist/server/idleTimeout.d.ts +24 -0
- package/dist/server/idleTimeout.d.ts.map +1 -0
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/server/modulePreloads.d.ts +18 -0
- package/dist/server/modulePreloads.d.ts.map +1 -1
- package/dist/server/styles.d.ts +3 -1
- package/dist/server/styles.d.ts.map +1 -1
- package/dist/services/index.d.ts +1 -0
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +3 -3
- package/dist/services/index.js.map +2 -2
- package/dist/services/middleware/MiddlewareRegistry.d.ts +13 -2
- package/dist/services/middleware/MiddlewareRegistry.d.ts.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/services/router/DomainRouter.d.ts +10 -0
- package/dist/services/router/DomainRouter.d.ts.map +1 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts +30 -2
- package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
- package/dist/services/router/createFlatViewRoutes.d.ts +13 -1
- package/dist/services/router/createFlatViewRoutes.d.ts.map +1 -1
- package/dist/services/router/staticCache.d.ts +23 -0
- package/dist/services/router/staticCache.d.ts.map +1 -0
- package/dist/services/router/staticDocument.d.ts +66 -0
- package/dist/services/router/staticDocument.d.ts.map +1 -0
- package/dist/stats/bundleStats.d.ts +104 -0
- package/dist/stats/bundleStats.d.ts.map +1 -0
- package/dist/stats/route-table.d.ts +2 -0
- package/dist/stats/route-table.d.ts.map +1 -0
- package/dist/stats/route-table.js +4 -0
- package/dist/stats/route-table.js.map +11 -0
- package/dist/stats/routeTable.d.ts +25 -0
- package/dist/stats/routeTable.d.ts.map +1 -0
- package/dist/stats/run.d.ts +43 -0
- package/dist/stats/run.d.ts.map +1 -0
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/vite/index.mjs +173 -2
- package/dist/vitest/index.d.ts +18 -0
- package/dist/vitest/index.d.ts.map +1 -1
- package/dist/vitest/index.js +2 -2
- package/dist/vitest/index.js.map +3 -3
- package/package.json +2 -1
- package/dist/chunk-9jz4rggd.js +0 -5
- package/dist/chunk-b9av1sgb.js +0 -58
- package/dist/chunk-b9av1sgb.js.map +0 -14
- package/dist/chunk-cewyag0d.js +0 -6
- package/dist/chunk-cewyag0d.js.map +0 -11
- package/dist/chunk-ffagkj3x.js +0 -4
- package/dist/chunk-h2hdpm70.js +0 -24
- package/dist/chunk-h3t4n0bn.js +0 -5
- package/dist/chunk-hdhahvd4.js +0 -4
- package/dist/chunk-k9qmr2wa.js +0 -9
- package/dist/chunk-k9qmr2wa.js.map +0 -10
- package/dist/chunk-mrvcaakf.js +0 -5
- package/dist/chunk-ncfxmtd5.js +0 -17
- package/dist/chunk-q2fyp44f.js +0 -4
- package/dist/chunk-q7y9v2v5.js +0 -18
- package/dist/chunk-rn2kgbg4.js +0 -5
- package/dist/chunk-vj2t77x1.js +0 -4
- package/dist/chunks/ThemeProvider-Cqfwr6dk.js.map +0 -1
- /package/dist/{chunk-xg9vye7c.js.map → chunk-0sjh5v1n.js.map} +0 -0
- /package/dist/{chunk-anp4kv3w.js.map → chunk-8b2tw2yp.js.map} +0 -0
- /package/dist/{chunk-2xqrh6d0.js.map → chunk-et4pv1b1.js.map} +0 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Bb as T,Cb as a9,Db as I$,Eb as v$,Fb as b3}from"../chunk-t26n9vzw.js";import{Mf as x3,Of as ZQ,Pf as l,df as A3,gf as E3,vf as l1,wf as i1,xf as QQ,yf as zQ}from"../chunk-rh9j8cwv.js";import{Qf as k3,Sf as mQ,Tf as pQ}from"../chunk-fwympxqk.js";import{Xf as AQ}from"../chunk-njkk498k.js";import{bh as PQ}from"../chunk-9mqqr05d.js";import"../chunk-2gmgd05c.js";import"../chunk-kqz8jp6v.js";import"../chunk-3s3awh38.js";class h extends Error{status;body;requestId;constructor(Q,$,Z){super(`Provider request failed with status ${Q}: ${u3($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=Z}}class UQ extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function u3(Q){let $=e9(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function e9(Q){if(!Q||typeof Q!=="object")return null;let $=Q,J=$.error&&typeof $.error==="object"?$.error:Q;if(typeof J.message!=="string"&&typeof J.code!=="string"&&typeof J.type!=="string")return null;let W=J.innererror?.code??J.code;return{message:J.message,type:J.type,code:W,param:J.param}}function x(Q){if(!Q||typeof Q!=="object")return{};let{status:$,requestId:Z}=Q;return{...typeof $==="number"&&$>=100&&$<=599?{status:$}:{},...typeof Z==="string"&&Z?{requestId:Z}:{}}}function A(Q){if(Q instanceof UQ)return{code:"provider_error",message:Q.message,retryable:!0};if(d3(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof h)return c3(Q.status,e9(Q.body),Q.message);if(Q instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${Q.message}`,retryable:!0};if(Q instanceof Error)return{code:"provider_error",message:Q.message,retryable:!1};return{code:"unknown",message:String(Q),retryable:!1}}function c3(Q,$,Z){let J=$?.message??Z,W=($?.code??"").toLowerCase(),G=($?.type??"").toLowerCase(),X=`${W} ${G} ${J}`.toLowerCase();if(Q===429){let Y=W==="insufficient_quota"||X.includes("quota");return{code:"rate_limited",message:J,retryable:!Y}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:J,retryable:!0};if(m3(X))return{code:"context_length_exceeded",message:J,retryable:!1};if(p3(X))return{code:"content_filtered",message:J,retryable:!1};if($?.param?.startsWith("tools")||X.includes("invalid schema for function"))return{code:"invalid_tool_input",message:J,retryable:!1};return{code:"provider_error",message:J,retryable:!1}}function m3(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function p3(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function d3(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}class k extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function y(Q,$){if($.aborted)return Promise.reject(new k);return new Promise((Z,J)=>{let W=()=>J(new k);$.addEventListener("abort",W,{once:!0}),Q.then(Z,J).finally(()=>$.removeEventListener("abort",W))})}function M(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function R(Q,$){if(!$)return Q;let Z={inputTokens:Q.inputTokens+($.inputTokens??0),outputTokens:Q.outputTokens+($.outputTokens??0),totalTokens:Q.totalTokens+($.totalTokens??0)};if($.reasoningTokens!==void 0||Q.reasoningTokens!==void 0)Z.reasoningTokens=(Q.reasoningTokens??0)+($.reasoningTokens??0);if($.cachedInputTokens!==void 0||Q.cachedInputTokens!==void 0)Z.cachedInputTokens=(Q.cachedInputTokens??0)+($.cachedInputTokens??0);if($.imageInputTokens!==void 0||Q.imageInputTokens!==void 0)Z.imageInputTokens=(Q.imageInputTokens??0)+($.imageInputTokens??0);if($.imageOutputTokens!==void 0||Q.imageOutputTokens!==void 0)Z.imageOutputTokens=(Q.imageOutputTokens??0)+($.imageOutputTokens??0);return Z}function DQ(Q){if(!Q.trim())return{};try{return JSON.parse(Q)}catch{}let $=[],Z=!1,J=!1;for(let X of Q){if(Z){if(J)J=!1;else if(X==="\\")J=!0;else if(X==='"')Z=!1;continue}if(X==='"')Z=!0;else if(X==="{")$.push("}");else if(X==="[")$.push("]");else if(X==="}"||X==="]")$.pop()}let W=Q;if(Z)W+='"';W=W.replace(/[,:]\s*$/,"");let G=$.reverse().join("");try{return JSON.parse(W+G)}catch{try{return JSON.parse(W.replace(/,?\s*"[^"]*"\s*$/,"")+G)}catch{return{}}}}function FQ(Q){return{name:"output",schema:Q.toJSONSchema(),strict:QQ(Q)}}function jQ(Q,$){let Z=Q.safeParse(DQ($));if(Z.ok===!0)return{ok:!0,value:Z.value};return{ok:!1,error:{code:"invalid_output",message:`The model's structured answer did not match the output schema: ${Z.errors.join(", ")}`,retryable:!0}}}function LQ(Q){if(Q.length>0)Q[0];return Q}function $Q(Q,$,Z){let J=Q.content[Q.content.length-1];if(J&&J.type===$){J.text=(J.text??"")+Z;return}Q.content.push($==="text"?{type:"text",text:Z}:{type:"reasoning",text:Z})}function CQ(Q,$,Z){let J=Q.content[Q.content.length-1];if(J&&J.type==="reasoning"&&J.id===$){J.text=(J.text??"")+Z;return}Q.content.push($?{type:"reasoning",id:$,text:Z}:{type:"reasoning",text:Z})}function l3(Q){return dQ(Q)}async function dQ(Q,$={}){let Z=`gen_${crypto.randomUUID()}`,J=await o3(Q);if($.settled?.(J),!J.ok){if(Q.logErrors!==!1&&J.error.code!=="aborted")i3(Z,J.error,$.origin);if(Q.throwOnError)throw new JQ({runId:Z,messages:J.messages,finishReason:J.finishReason,usage:J.usage,error:J.error})}return J}function i3(Q,$,Z){let J=`[gemi/ai] generate() failed (${$.code}${$.status!==void 0?` ${$.status}`:""}): ${$.message}`,W={...Z,generateId:Q,error:$},G=!1;try{ZQ.error(J,W),G=!0}catch{}if(!G||Bun.env.NODE_ENV==="development")console.error(J,W)}async function o3(Q){let $=Q.messages??[];if($.length===0&&!Q.prompt)throw Error("generate() was given neither a `prompt` nor `messages`, so there is nothing to send the model.");let Z=[...$];if(Q.prompt)Z.push({id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:Q.prompt}],createdAt:new Date().toISOString()});let J={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()},W=Q.signal??new AbortController().signal,G=M(),X="stop",Y,H={},V="";try{let U=Q.provider.stream({messages:[...Z],systemPrompt:Q.instructions?.trim()?Q.instructions:void 0,output:FQ(Q.output),reasoning:Q.reasoning,maxOutputTokens:Q.maxOutputTokens,temperature:Q.temperature,signal:Q.signal})[Symbol.asyncIterator]();try{for(;;){let F=await y(Promise.resolve(U.next()),W);if(F.done)break;let D=F.value;switch(D.type){case"output-delta":V+=D.delta;break;case"text-delta":$Q(J,"text",D.delta);break;case"reasoning-delta":CQ(J,D.id,D.delta);break;case"finish":if(G=R(G,D.usage),!Y)X=D.reason;break;case"error":X="error",Y=D.error,H=x(D);break}}}finally{if(W.aborted)Promise.resolve(U.return?.()).catch(()=>{})}}catch(B){if(B instanceof k||W.aborted)X="aborted",Y=n3(W);else X="error",Y=Q.provider.normalizeError(B),H=x(B)}let K=!1,z;if(!Y)if(X==="length")Y={code:"invalid_output",message:"The model ran out of output tokens before finishing its structured answer, so it was cut off. Raise maxOutputTokens, or ask for a shorter answer.",retryable:!0};else if(!V.trim())Y={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let B=jQ(Q.output,V);if(B.ok===!0)K=!0,z=B.value;else Y=B.error}if(K)J.content.push({type:"output",value:z});else if(V)$Q(J,"text",V);for(let B of J.content)if((B.type==="text"||B.type==="reasoning")&&typeof B.text==="string")B.text=LQ(B.text);if(J.finishReason=X,J.usage=G,Z.push(J),K)return{ok:!0,output:z,messages:Z,usage:G,finishReason:X};return{ok:!1,error:{...Y,...H},messages:Z,usage:G,finishReason:X}}function n3(Q){return Q.reason?.name==="TimeoutError"?{code:"timeout",message:"The generation timed out.",retryable:!0}:{code:"aborted",message:"The generation was stopped.",retryable:!1}}import{createHmac as s3,hkdfSync as t3,randomBytes as Q$,timingSafeEqual as a3}from"crypto";class WQ{spent=new Map;sweepAt=1024;async consume(Q,$){return this.consumeSync(Q,$)}consumeSync(Q,$,Z=Date.now()){if(this.spent.size>=this.sweepAt)this.sweep(Z);let J=this.spent.get(Q);if(J!==void 0&&J>Z)return!1;return this.spent.set(Q,$),!0}get size(){return this.spent.size}sweep(Q){for(let[$,Z]of this.spent)if(Z<=Q)this.spent.delete($);this.sweepAt=Math.max(1024,this.spent.size*2)}}class lQ{injectedClient;prefix;constructor(Q={}){this.injectedClient=Q.client,this.prefix=Q.prefix??"gemi:ai:nonce"}async consume(Q,$){let Z=Math.max(1,Math.ceil($-Date.now()));return await this.client.send("SET",[`${this.prefix}:${Q}`,"1","PX",String(Z),"NX"])==="OK"}get client(){if(this.injectedClient)return this.injectedClient;let Q=PQ(),$=Q.bound(l)?Q.make(l).client:void 0;if(!$)throw Error("RedisNonceStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisNonceStore({ client }).");return $}}var i=new WQ;var iQ="agt2",OQ="agt1",$$=[iQ,OQ],oQ=86400000,r3=Date.now()+oQ;function Z$(Q){return Q<=r3}var J$="gemi.ai.pending-call.v1",W$="gemi.ai.nested-run.v1",e3="gemi.ai.execution-receipt.v1",QZ="gemi.ai.signing",qQ=new Map;function GQ(Q,$){let Z=nQ($),J=`${Q}\x00${Z}`,W=qQ.get(J);if(!W){if(W=Buffer.from(t3("sha256",Z,QZ,Q,32)),qQ.size>64)qQ.clear();qQ.set(J,W)}return W}function nQ(Q){let $=Q??process.env.SECRET;if(!$)throw Error("Signing a pending tool call needs an app secret. Set SECRET in the environment.");return $}function I(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(I).join(",")}]`;let $=Q;return`{${Object.keys($).filter((J)=>$[J]!==void 0).sort().map((J)=>`${JSON.stringify(J)}:${I($[J])}`).join(",")}}`}function $Z(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function g(Q,$){return s3("sha256",Q).update($Z($)).digest()}function G$(Q,$){let Z=Buffer.from(Q.split(".")[4],"base64url");return Z.length===$.length&&a3(Z,$)}function sQ(Q){return I(Q??null)}function X$(Q,$,Z){return[iQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),I(Q.input),I(Q.path??[]),sQ(Q.subject)]}function ZZ(Q,$,Z){let J=[OQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),I(Q.input)];if(Q.path&&Q.path.length>0)J.push(I(Q.path));return J}var V$=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),JZ=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function Y$(Q,$={}){let Z=GQ(J$,$.secret),W=($.now??Date.now())+($.ttlMs??oQ),G=Q$(12).toString("base64url"),X=g(Z,X$(Q,G,W)).toString("base64url");return[iQ,V$(Q.runId),G,W.toString(36),X].join(".")}function tQ(Q){return _Q(Q,$$)}function _Q(Q,$){let Z=Q.split(".");if(Z.length!==5||!$.includes(Z[0]))return null;let J=Number.parseInt(Z[3],36);if(!Number.isFinite(J))return null;try{return{runId:JZ(Z[1]),nonce:Z[2],expiresAt:J,version:Z[0]}}catch{return null}}function H$(Q,$,Z={}){let J=_Q(Q,$$);if(!J)return{ok:!1,reason:"malformed"};if(J.version===OQ&&!Z$(J.expiresAt))return{ok:!1,reason:"forged"};let W=J.version===OQ?g(nQ(Z.secret),ZZ($,J.nonce,J.expiresAt)):g(GQ(J$,Z.secret),X$($,J.nonce,J.expiresAt));if(!G$(Q,W))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>J.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:J.runId,nonce:J.nonce,expiresAt:J.expiresAt}}var aQ="agn2",NQ="agn1",K$=[aQ,NQ];function B$(Q,$,Z){return[...z$(Q,$,Z,aQ),sQ(Q.subject)]}function z$(Q,$,Z,J=NQ){return[J,Q.runId,I(Q.path),Q.nestedRunId,$,String(Z),I([...Q.open].sort()),I(Q.input)]}function U$(Q,$={}){let Z=GQ(W$,$.secret),W=($.now??Date.now())+($.ttlMs??oQ),G=Q$(12).toString("base64url"),X=g(Z,B$(Q,G,W)).toString("base64url");return[aQ,V$(Q.runId),G,W.toString(36),X].join(".")}function D$(Q,$,Z={}){let J=_Q(Q,K$);if(!J)return{ok:!1,reason:"malformed"};if(J.version===NQ&&!Z$(J.expiresAt))return{ok:!1,reason:"forged"};let W={...$,runId:J.runId},G=J.version===NQ?g(nQ(Z.secret),z$(W,J.nonce,J.expiresAt)):g(GQ(W$,Z.secret),B$(W,J.nonce,J.expiresAt));if(!G$(Q,G))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>J.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:J.runId,nonce:J.nonce,expiresAt:J.expiresAt}}function F$(Q,$,Z={}){let J=GQ(e3,Z.secret);return g(J,[Q,$.runId,$.toolCallId,$.name,$.kind,I($.input),I($.path??[]),sQ($.subject)]).toString("base64url")}function j$(Q,$){return C$($,tQ(Q))}function L$(Q,$){return C$($,_Q(Q,K$))}async function C$(Q,$){if(!$)return!1;return Q.consume($.nonce,$.expiresAt)}class XQ extends T{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class o extends T{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function rQ(Q){if(!Q||typeof Q.key!=="string"||Q.key.length===0)throw new o("An attachment scope needs a non-empty key. Return `null` from `attachmentScope()` for a request that has no subject \u2014 an empty key is a bucket every caller shares.");return Q}var f="gemi_att_";function eQ(){return`${f}${crypto.randomUUID()}`}class VQ{store;storage;scope;constructor(Q,$,Z){this.store=Q;this.storage=$;this.scope=Z;rQ(Z)}async get(Q){let $=await this.store.find(this.scope,Q);if(!$||$.scopeKey!==this.scope.key)throw new XQ(Q);return $}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,$){if(!$.objectName)throw new XQ(Q);return await this.storage.read({name:$.objectName})}async file(Q){let $=await this.get(Q),J=(await this.readRecord(Q,$)).body,W=J instanceof Blob?J:J?await new Response(J).blob():new Blob([]);return new File([W],$.name,{type:$.mimeType})}async put(Q,$={}){let Z=eQ(),J=$.mimeType??Q.type??"",W=$.name??(Q instanceof File?Q.name:Z),G=await this.storage.put({name:Q9(Z,W),body:Q,contentType:J||void 0}),X={id:Z,scopeKey:this.scope.key,objectName:G,name:W,mimeType:J||"application/octet-stream",size:Q.size,createdAt:new Date().toISOString(),destination:$.fileId?"both":"storage",...$.fileId?{fileId:$.fileId}:{}};return await this.store.put(this.scope,X),X}}function Q9(Q,$){let Z=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Q}${Z?`.${Z[1].toLowerCase()}`:""}`}class MQ{rows=new Map;async put(Q,$){rQ(Q),this.rows.set($.id,{...$,scopeKey:Q.key})}async find(Q,$){rQ(Q);let Z=this.rows.get($);if(!Z||Z.scopeKey!==Q.key)return null;return Z}get size(){return this.rows.size}}var SQ=new MQ;var $9=new TextEncoder;function P$(Q){return`id: ${Q.seq}
|
|
2
|
+
import{Jb as T,Kb as a9,Lb as I$,Mb as v$,Nb as b3}from"../chunk-3y8q8x11.js";import{Ef as l1,Ff as i1,Gf as QQ,Hf as zQ,Vf as x3,Xf as ZQ,Yf as l,mf as A3,pf as E3}from"../chunk-mn5xw79b.js";import{$f as mQ,Zf as k3,ag as pQ}from"../chunk-pwmgqq7z.js";import{eg as AQ}from"../chunk-sq2wkynk.js";import{lh as PQ}from"../chunk-q9s7kwgt.js";import"../chunk-3cg7y62b.js";import"../chunk-m6ystvtk.js";import"../chunk-1yx2e0bh.js";class h extends Error{status;body;requestId;constructor(Q,$,Z){super(`Provider request failed with status ${Q}: ${u3($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=Z}}class UQ extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function u3(Q){let $=e9(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function e9(Q){if(!Q||typeof Q!=="object")return null;let $=Q,J=$.error&&typeof $.error==="object"?$.error:Q;if(typeof J.message!=="string"&&typeof J.code!=="string"&&typeof J.type!=="string")return null;let W=J.innererror?.code??J.code;return{message:J.message,type:J.type,code:W,param:J.param}}function x(Q){if(!Q||typeof Q!=="object")return{};let{status:$,requestId:Z}=Q;return{...typeof $==="number"&&$>=100&&$<=599?{status:$}:{},...typeof Z==="string"&&Z?{requestId:Z}:{}}}function A(Q){if(Q instanceof UQ)return{code:"provider_error",message:Q.message,retryable:!0};if(d3(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof h)return c3(Q.status,e9(Q.body),Q.message);if(Q instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${Q.message}`,retryable:!0};if(Q instanceof Error)return{code:"provider_error",message:Q.message,retryable:!1};return{code:"unknown",message:String(Q),retryable:!1}}function c3(Q,$,Z){let J=$?.message??Z,W=($?.code??"").toLowerCase(),G=($?.type??"").toLowerCase(),X=`${W} ${G} ${J}`.toLowerCase();if(Q===429){let Y=W==="insufficient_quota"||X.includes("quota");return{code:"rate_limited",message:J,retryable:!Y}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:J,retryable:!0};if(m3(X))return{code:"context_length_exceeded",message:J,retryable:!1};if(p3(X))return{code:"content_filtered",message:J,retryable:!1};if($?.param?.startsWith("tools")||X.includes("invalid schema for function"))return{code:"invalid_tool_input",message:J,retryable:!1};return{code:"provider_error",message:J,retryable:!1}}function m3(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function p3(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function d3(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}class k extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function y(Q,$){if($.aborted)return Promise.reject(new k);return new Promise((Z,J)=>{let W=()=>J(new k);$.addEventListener("abort",W,{once:!0}),Q.then(Z,J).finally(()=>$.removeEventListener("abort",W))})}function M(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function R(Q,$){if(!$)return Q;let Z={inputTokens:Q.inputTokens+($.inputTokens??0),outputTokens:Q.outputTokens+($.outputTokens??0),totalTokens:Q.totalTokens+($.totalTokens??0)};if($.reasoningTokens!==void 0||Q.reasoningTokens!==void 0)Z.reasoningTokens=(Q.reasoningTokens??0)+($.reasoningTokens??0);if($.cachedInputTokens!==void 0||Q.cachedInputTokens!==void 0)Z.cachedInputTokens=(Q.cachedInputTokens??0)+($.cachedInputTokens??0);if($.imageInputTokens!==void 0||Q.imageInputTokens!==void 0)Z.imageInputTokens=(Q.imageInputTokens??0)+($.imageInputTokens??0);if($.imageOutputTokens!==void 0||Q.imageOutputTokens!==void 0)Z.imageOutputTokens=(Q.imageOutputTokens??0)+($.imageOutputTokens??0);return Z}function DQ(Q){if(!Q.trim())return{};try{return JSON.parse(Q)}catch{}let $=[],Z=!1,J=!1;for(let X of Q){if(Z){if(J)J=!1;else if(X==="\\")J=!0;else if(X==='"')Z=!1;continue}if(X==='"')Z=!0;else if(X==="{")$.push("}");else if(X==="[")$.push("]");else if(X==="}"||X==="]")$.pop()}let W=Q;if(Z)W+='"';W=W.replace(/[,:]\s*$/,"");let G=$.reverse().join("");try{return JSON.parse(W+G)}catch{try{return JSON.parse(W.replace(/,?\s*"[^"]*"\s*$/,"")+G)}catch{return{}}}}function FQ(Q){return{name:"output",schema:Q.toJSONSchema(),strict:QQ(Q)}}function jQ(Q,$){let Z=Q.safeParse(DQ($));if(Z.ok===!0)return{ok:!0,value:Z.value};return{ok:!1,error:{code:"invalid_output",message:`The model's structured answer did not match the output schema: ${Z.errors.join(", ")}`,retryable:!0}}}function LQ(Q){if(Q.length>0)Q[0];return Q}function $Q(Q,$,Z){let J=Q.content[Q.content.length-1];if(J&&J.type===$){J.text=(J.text??"")+Z;return}Q.content.push($==="text"?{type:"text",text:Z}:{type:"reasoning",text:Z})}function CQ(Q,$,Z){let J=Q.content[Q.content.length-1];if(J&&J.type==="reasoning"&&J.id===$){J.text=(J.text??"")+Z;return}Q.content.push($?{type:"reasoning",id:$,text:Z}:{type:"reasoning",text:Z})}function l3(Q){return dQ(Q)}async function dQ(Q,$={}){let Z=`gen_${crypto.randomUUID()}`,J=await o3(Q);if($.settled?.(J),!J.ok){if(Q.logErrors!==!1&&J.error.code!=="aborted")i3(Z,J.error,$.origin);if(Q.throwOnError)throw new JQ({runId:Z,messages:J.messages,finishReason:J.finishReason,usage:J.usage,error:J.error})}return J}function i3(Q,$,Z){let J=`[gemi/ai] generate() failed (${$.code}${$.status!==void 0?` ${$.status}`:""}): ${$.message}`,W={...Z,generateId:Q,error:$},G=!1;try{ZQ.error(J,W),G=!0}catch{}if(!G||Bun.env.NODE_ENV==="development")console.error(J,W)}async function o3(Q){let $=Q.messages??[];if($.length===0&&!Q.prompt)throw Error("generate() was given neither a `prompt` nor `messages`, so there is nothing to send the model.");let Z=[...$];if(Q.prompt)Z.push({id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:Q.prompt}],createdAt:new Date().toISOString()});let J={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()},W=Q.signal??new AbortController().signal,G=M(),X="stop",Y,H={},V="";try{let U=Q.provider.stream({messages:[...Z],systemPrompt:Q.instructions?.trim()?Q.instructions:void 0,output:FQ(Q.output),reasoning:Q.reasoning,maxOutputTokens:Q.maxOutputTokens,temperature:Q.temperature,signal:Q.signal})[Symbol.asyncIterator]();try{for(;;){let F=await y(Promise.resolve(U.next()),W);if(F.done)break;let D=F.value;switch(D.type){case"output-delta":V+=D.delta;break;case"text-delta":$Q(J,"text",D.delta);break;case"reasoning-delta":CQ(J,D.id,D.delta);break;case"finish":if(G=R(G,D.usage),!Y)X=D.reason;break;case"error":X="error",Y=D.error,H=x(D);break}}}finally{if(W.aborted)Promise.resolve(U.return?.()).catch(()=>{})}}catch(B){if(B instanceof k||W.aborted)X="aborted",Y=n3(W);else X="error",Y=Q.provider.normalizeError(B),H=x(B)}let K=!1,z;if(!Y)if(X==="length")Y={code:"invalid_output",message:"The model ran out of output tokens before finishing its structured answer, so it was cut off. Raise maxOutputTokens, or ask for a shorter answer.",retryable:!0};else if(!V.trim())Y={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let B=jQ(Q.output,V);if(B.ok===!0)K=!0,z=B.value;else Y=B.error}if(K)J.content.push({type:"output",value:z});else if(V)$Q(J,"text",V);for(let B of J.content)if((B.type==="text"||B.type==="reasoning")&&typeof B.text==="string")B.text=LQ(B.text);if(J.finishReason=X,J.usage=G,Z.push(J),K)return{ok:!0,output:z,messages:Z,usage:G,finishReason:X};return{ok:!1,error:{...Y,...H},messages:Z,usage:G,finishReason:X}}function n3(Q){return Q.reason?.name==="TimeoutError"?{code:"timeout",message:"The generation timed out.",retryable:!0}:{code:"aborted",message:"The generation was stopped.",retryable:!1}}import{createHmac as s3,hkdfSync as t3,randomBytes as Q$,timingSafeEqual as a3}from"crypto";class WQ{spent=new Map;sweepAt=1024;async consume(Q,$){return this.consumeSync(Q,$)}consumeSync(Q,$,Z=Date.now()){if(this.spent.size>=this.sweepAt)this.sweep(Z);let J=this.spent.get(Q);if(J!==void 0&&J>Z)return!1;return this.spent.set(Q,$),!0}get size(){return this.spent.size}sweep(Q){for(let[$,Z]of this.spent)if(Z<=Q)this.spent.delete($);this.sweepAt=Math.max(1024,this.spent.size*2)}}class lQ{injectedClient;prefix;constructor(Q={}){this.injectedClient=Q.client,this.prefix=Q.prefix??"gemi:ai:nonce"}async consume(Q,$){let Z=Math.max(1,Math.ceil($-Date.now()));return await this.client.send("SET",[`${this.prefix}:${Q}`,"1","PX",String(Z),"NX"])==="OK"}get client(){if(this.injectedClient)return this.injectedClient;let Q=PQ(),$=Q.bound(l)?Q.make(l).client:void 0;if(!$)throw Error("RedisNonceStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisNonceStore({ client }).");return $}}var i=new WQ;var iQ="agt2",OQ="agt1",$$=[iQ,OQ],oQ=86400000,r3=Date.now()+oQ;function Z$(Q){return Q<=r3}var J$="gemi.ai.pending-call.v1",W$="gemi.ai.nested-run.v1",e3="gemi.ai.execution-receipt.v1",QZ="gemi.ai.signing",qQ=new Map;function GQ(Q,$){let Z=nQ($),J=`${Q}\x00${Z}`,W=qQ.get(J);if(!W){if(W=Buffer.from(t3("sha256",Z,QZ,Q,32)),qQ.size>64)qQ.clear();qQ.set(J,W)}return W}function nQ(Q){let $=Q??process.env.SECRET;if(!$)throw Error("Signing a pending tool call needs an app secret. Set SECRET in the environment.");return $}function I(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(I).join(",")}]`;let $=Q;return`{${Object.keys($).filter((J)=>$[J]!==void 0).sort().map((J)=>`${JSON.stringify(J)}:${I($[J])}`).join(",")}}`}function $Z(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function g(Q,$){return s3("sha256",Q).update($Z($)).digest()}function G$(Q,$){let Z=Buffer.from(Q.split(".")[4],"base64url");return Z.length===$.length&&a3(Z,$)}function sQ(Q){return I(Q??null)}function X$(Q,$,Z){return[iQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),I(Q.input),I(Q.path??[]),sQ(Q.subject)]}function ZZ(Q,$,Z){let J=[OQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),I(Q.input)];if(Q.path&&Q.path.length>0)J.push(I(Q.path));return J}var V$=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),JZ=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function Y$(Q,$={}){let Z=GQ(J$,$.secret),W=($.now??Date.now())+($.ttlMs??oQ),G=Q$(12).toString("base64url"),X=g(Z,X$(Q,G,W)).toString("base64url");return[iQ,V$(Q.runId),G,W.toString(36),X].join(".")}function tQ(Q){return _Q(Q,$$)}function _Q(Q,$){let Z=Q.split(".");if(Z.length!==5||!$.includes(Z[0]))return null;let J=Number.parseInt(Z[3],36);if(!Number.isFinite(J))return null;try{return{runId:JZ(Z[1]),nonce:Z[2],expiresAt:J,version:Z[0]}}catch{return null}}function H$(Q,$,Z={}){let J=_Q(Q,$$);if(!J)return{ok:!1,reason:"malformed"};if(J.version===OQ&&!Z$(J.expiresAt))return{ok:!1,reason:"forged"};let W=J.version===OQ?g(nQ(Z.secret),ZZ($,J.nonce,J.expiresAt)):g(GQ(J$,Z.secret),X$($,J.nonce,J.expiresAt));if(!G$(Q,W))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>J.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:J.runId,nonce:J.nonce,expiresAt:J.expiresAt}}var aQ="agn2",NQ="agn1",K$=[aQ,NQ];function B$(Q,$,Z){return[...z$(Q,$,Z,aQ),sQ(Q.subject)]}function z$(Q,$,Z,J=NQ){return[J,Q.runId,I(Q.path),Q.nestedRunId,$,String(Z),I([...Q.open].sort()),I(Q.input)]}function U$(Q,$={}){let Z=GQ(W$,$.secret),W=($.now??Date.now())+($.ttlMs??oQ),G=Q$(12).toString("base64url"),X=g(Z,B$(Q,G,W)).toString("base64url");return[aQ,V$(Q.runId),G,W.toString(36),X].join(".")}function D$(Q,$,Z={}){let J=_Q(Q,K$);if(!J)return{ok:!1,reason:"malformed"};if(J.version===NQ&&!Z$(J.expiresAt))return{ok:!1,reason:"forged"};let W={...$,runId:J.runId},G=J.version===NQ?g(nQ(Z.secret),z$(W,J.nonce,J.expiresAt)):g(GQ(W$,Z.secret),B$(W,J.nonce,J.expiresAt));if(!G$(Q,G))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>J.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:J.runId,nonce:J.nonce,expiresAt:J.expiresAt}}function F$(Q,$,Z={}){let J=GQ(e3,Z.secret);return g(J,[Q,$.runId,$.toolCallId,$.name,$.kind,I($.input),I($.path??[]),sQ($.subject)]).toString("base64url")}function j$(Q,$){return C$($,tQ(Q))}function L$(Q,$){return C$($,_Q(Q,K$))}async function C$(Q,$){if(!$)return!1;return Q.consume($.nonce,$.expiresAt)}class XQ extends T{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class o extends T{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function rQ(Q){if(!Q||typeof Q.key!=="string"||Q.key.length===0)throw new o("An attachment scope needs a non-empty key. Return `null` from `attachmentScope()` for a request that has no subject \u2014 an empty key is a bucket every caller shares.");return Q}var f="gemi_att_";function eQ(){return`${f}${crypto.randomUUID()}`}class VQ{store;storage;scope;constructor(Q,$,Z){this.store=Q;this.storage=$;this.scope=Z;rQ(Z)}async get(Q){let $=await this.store.find(this.scope,Q);if(!$||$.scopeKey!==this.scope.key)throw new XQ(Q);return $}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,$){if(!$.objectName)throw new XQ(Q);return await this.storage.read({name:$.objectName})}async file(Q){let $=await this.get(Q),J=(await this.readRecord(Q,$)).body,W=J instanceof Blob?J:J?await new Response(J).blob():new Blob([]);return new File([W],$.name,{type:$.mimeType})}async put(Q,$={}){let Z=eQ(),J=$.mimeType??Q.type??"",W=$.name??(Q instanceof File?Q.name:Z),G=await this.storage.put({name:Q9(Z,W),body:Q,contentType:J||void 0}),X={id:Z,scopeKey:this.scope.key,objectName:G,name:W,mimeType:J||"application/octet-stream",size:Q.size,createdAt:new Date().toISOString(),destination:$.fileId?"both":"storage",...$.fileId?{fileId:$.fileId}:{}};return await this.store.put(this.scope,X),X}}function Q9(Q,$){let Z=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Q}${Z?`.${Z[1].toLowerCase()}`:""}`}class MQ{rows=new Map;async put(Q,$){rQ(Q),this.rows.set($.id,{...$,scopeKey:Q.key})}async find(Q,$){rQ(Q);let Z=this.rows.get($);if(!Z||Z.scopeKey!==Q.key)return null;return Z}get size(){return this.rows.size}}var SQ=new MQ;var $9=new TextEncoder;function P$(Q){return`id: ${Q.seq}
|
|
3
3
|
data: ${JSON.stringify(Q.event)}
|
|
4
4
|
|
|
5
5
|
`}var WZ=5000,GZ=`: keepalive
|
|
@@ -23,4 +23,4 @@ return held`,z1=`
|
|
|
23
23
|
if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end
|
|
24
24
|
return 0`;class p9{injectedClient;prefix;constructor(Q={}){this.injectedClient=Q.client,this.prefix=Q.prefix??"gemi:ai:receipt"}async claim(Q,$){let Z=await this.client.send("EVAL",[B1,"1",this.key(Q),V3,Y3($)]);if(Z==="claimed")return{status:"claimed"};let J=String(Z??"");if(J.startsWith(c9))return{status:"replay",result:JSON.parse(J.slice(c9.length))};return{status:"blocked"}}async complete(Q,$,Z){await this.client.send("SET",[this.key(Q),c9+JSON.stringify($),"PX",Y3(Z)])}async release(Q){await this.client.send("EVAL",[z1,"1",this.key(Q),V3])}key(Q){return`${this.prefix}:${Q}`}get client(){if(this.injectedClient)return this.injectedClient;let Q=PQ(),$=Q.bound(l)?Q.make(l).client:void 0;if(!$)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return $}}function Y3(Q){return String(Math.max(1,Math.ceil(Q-Date.now())))}class hQ{ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor(Q={}){this.ttlMs=Q.ttlMs??86400000,this.clientOwnedIds=Q.clientOwnedIds??!1}async createThread(Q){let $=crypto.randomUUID();return this.threads.set($,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:$}}async loadThread(Q){this.sweep();let $=this.threads.get(Q);if(!$)return this.clientOwnedIds?[]:null;return $.touchedAt=Date.now(),$.messages.slice()}async appendMessages(Q,$){this.sweep();let Z=this.threads.get(Q);if(!Z){if(!this.clientOwnedIds)throw Error(`Thread ${Q} does not exist here, or has expired.`);Z={messages:[],touchedAt:Date.now()},this.threads.set(Q,Z)}for(let J of $){let W=Z.messages.findIndex((G)=>G.id===J.id);if(W===-1)Z.messages.push(J);else Z.messages[W]=J}Z.touchedAt=Date.now()}async removeMessages(Q,$){this.sweep();let Z=this.threads.get(Q);if(!Z)return;let J=new Set($);Z.messages=Z.messages.filter((W)=>!J.has(W.id)),Z.touchedAt=Date.now()}delete(Q){this.threads.delete(Q)}get size(){return this.threads.size}sweep(Q=Date.now()){if(Q-this.lastSweep<60000)return;this.lastSweep=Q;for(let[$,Z]of this.threads)if(Q-Z.touchedAt>this.ttlMs)this.threads.delete($)}}var d9=new hQ;function z3(Q={}){return{messages:Q.messages?[...Q.messages]:[],pending:Q.pending?[...Q.pending]:[],error:null,threadId:Q.threadId,seq:Q.seq??-1,cursorRunId:Q.cursorRunId,runMessageIds:[],loadedTools:[]}}function U3(Q,$,Z=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==Q.cursorRunId)&&$.seq<=Q.seq)return Q;return{...D3(Q,$.event,Z),seq:$.seq}}function D3(Q,$,Z){switch($.type){case"run-start":return{...Q,messages:U1(Q.messages,$.runId),runId:$.runId,cursorRunId:$.runId,threadId:$.threadId??Q.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return d(Q,$.messageId,Z,(J)=>({...J,role:$.role}));case"text-delta":if(K3(Q,$.messageId))return Q;return d(Q,$.messageId,Z,(J)=>({...J,content:C1(J.content,$.delta)}));case"reasoning-delta":if(K3(Q,$.messageId))return Q;return d(Q,$.messageId,Z,(J)=>({...J,content:P1(J.content,$.delta,$.id)}));case"output-delta":return d(Q,$.messageId,Z,(J)=>({...J,content:B3(J.content,{type:"output",value:$.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return d(Q,$.messageId,Z,(J)=>{let W=J.content.findIndex((z)=>z.type==="tool-call"&&z.toolCallId===$.part.toolCallId),G=W===-1?void 0:J.content[W],X=$.part.progress??G?.progress,Y=$.part.nested??G?.nested,H=$.part.attachments??G?.attachments,V={...$.part,...X?{progress:X}:{},...Y?{nested:Y}:{},...H?{attachments:H}:{}},K=J.content.slice();if(W===-1)K.push(V);else K[W]=V;return{...J,content:K}});case"tool-search":{let J=$.loaded.filter((W)=>!Q.loadedTools.includes(W));if(J.length===0)return Q;return{...Q,loadedTools:[...Q.loadedTools,...J]}}case"tool-progress":return H3(Q,$.toolCallId,(J)=>({...J,progress:[...J.progress??[],$.data]}));case"nested-event":{let J=$;return H3(Q,$.toolCallId,(W)=>{let G=W.nested??[],X=G.findIndex((K)=>K.runId===J.runId),Y=G[X]??{runId:J.runId,agent:J.agent,messages:[]},H=j1(Y,J,Z),V=X===-1?[...G,H]:G.map((K,z)=>z===X?H:K);return{...W,nested:V}})}case"tool-result":{let J=d(Q,$.messageId,Z,(W)=>({...W,content:B3(W.content,$.part,(G)=>G.type==="tool-result"&&G.toolCallId===$.part.toolCallId)}));return{...J,pending:J.pending.filter((W)=>W.toolCallId!==$.part.toolCallId)}}case"message":{let J=Q.messages.findIndex((X)=>X.id===$.message.id),W=Q.messages.slice();if(J===-1)W.push($.message);else W[J]=$.message;let G=Q.runMessageIds.includes($.message.id)?Q.runMessageIds:[...Q.runMessageIds,$.message.id];return{...Q,messages:W,runMessageIds:G}}case"message-id":{let J=Q.messages.findIndex((G)=>G.id===$.localId);if(J===-1){if(!$.message||Q.messages.some((G)=>G.id===$.messageId))return Q;return{...Q,messages:[...Q.messages,$.message]}}let W=Q.messages.some((G)=>G.id===$.messageId)?Q.messages.filter((G,X)=>X!==J):Q.messages.map((G,X)=>X===J?{...G,id:$.messageId}:G);return{...Q,messages:W}}case"awaiting-input":return{...Q,runId:$.runId,pending:[...$.pending]};case"message-end":return d(Q,$.messageId,Z,(J)=>({...J,finishReason:$.finishReason,...$.outputTruncated?{outputTruncated:!0}:{},...$.usage?{usage:$.usage}:{},content:$.outputTruncated||$.finishReason==="length"?J.content.filter((W)=>!(W.type==="output"&&W.partial)):J.content.map((W)=>W.type==="output"&&W.partial?{...W,partial:!1}:W)}));case"usage":return{...Q,usage:$.usage};case"error":return{...Q,error:$.error,pending:[]};case"run-end":return{...Q,runId:void 0,finishReason:$.finishReason,messages:F3(Q,$.finishReason)};default:return Q}}function U1(Q,$){if(!Q.some((Z)=>Z.runId===$&&Z.finishReason===void 0))return Q;return Q.map((Z)=>{if(Z.runId!==$||Z.finishReason!==void 0)return Z;let{runId:J,...W}=Z;return{...W,content:[]}})}function F3(Q,$){return Q.messages.map((Z)=>Z.role==="assistant"&&Q.runMessageIds.includes(Z.id)?D1(Z,$):Z)}function D1(Q,$){let Z=Q.content.map((W)=>W.type==="tool-call"&&W.nested?.some((G)=>G.finishReason===void 0)?{...W,nested:W.nested.map((G)=>G.finishReason===void 0?F1(G,$):G)}:W);if(Q.finishReason===void 0)return{...Q,finishReason:$,content:Z};return Z.some((W,G)=>W!==Q.content[G])?{...Q,content:Z}:Q}function F1(Q,$){let Z={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((J)=>J.id),loadedTools:[]};return{...Q,finishReason:$,messages:F3(Z,$)}}function H3(Q,$,Z){for(let J=Q.messages.length-1;J>=0;J--){let W=Q.messages[J],G=W.content.findIndex((V)=>V.type==="tool-call"&&V.toolCallId===$);if(G===-1)continue;if(W.finishReason!==void 0&&!L1(Q,W,$))return Q;let X=W.content.slice();X[G]=Z(X[G]);let Y=Q.messages.slice();Y[J]={...W,content:X};let H=Q.runMessageIds.includes(W.id)?Q.runMessageIds:[...Q.runMessageIds,W.id];return{...Q,runMessageIds:H,messages:Y}}return Q}function j1(Q,$,Z){let J={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((G)=>G.id),loadedTools:[],finishReason:Q.finishReason},W=D3(J,$.event,Z);return{...Q,...$.label!==void 0?{label:$.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function L1(Q,$,Z){if($.finishReason!=="awaiting-input")return!1;return!Q.messages.some((J)=>J.content.some((W)=>W.type==="tool-result"&&W.toolCallId===Z))}function K3(Q,$){let Z=Q.messages.find((J)=>J.id===$);return Z!==void 0&&Z.finishReason!==void 0}function d(Q,$,Z,J){let W=Q.messages.findIndex((Y)=>Y.id===$),G=Q.runMessageIds.includes($)?Q.runMessageIds:[...Q.runMessageIds,$];if(W===-1){let Y={id:$,role:"assistant",content:[],createdAt:Z};return{...Q,runMessageIds:G,messages:[...Q.messages,J(Y)]}}let X=Q.messages.slice();return X[W]=J(X[W]),{...Q,runMessageIds:G,messages:X}}function C1(Q,$){let Z=Q[Q.length-1];if(Z&&Z.type==="text")return[...Q.slice(0,-1),{type:"text",text:Z.text+$}];return[...Q,{type:"text",text:$}]}function P1(Q,$,Z){let J=Q[Q.length-1];if(J&&J.type==="reasoning"&&J.id===Z)return[...Q.slice(0,-1),{...J,text:(J.text??"")+$}];return[...Q,Z?{type:"reasoning",id:Z,text:$}:{type:"reasoning",text:$}]}function B3(Q,$,Z){let J=Q.findIndex(Z);if(J===-1)return[...Q,$];let W=Q.slice();return W[J]=$,W}class i9{store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(Q,$,Z,J){this.store=Q;this.threadId=$;this.report=J;this.state=z3({messages:Z})}finish(Q){if(this.closed)return;this.done.add(Q.id),this.write(()=>[l9(Q)])}frame(Q){if(this.closed)return;let $=Q.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=U3(this.state,Q),$.type){case"message":this.write(()=>[l9($.message)]);return;case"tool-call":if($.part.partial)return;this.checkpoint($.messageId);return;case"message-start":case"tool-result":this.checkpoint($.messageId);return;default:return}}close(Q=[]){this.closed=!0;for(let $ of Q)this.done.add($.id)}settled(){return this.chain}checkpoint(Q){if(this.done.has(Q))return;let $=this.state.messages.find((J)=>J.id===Q);if(!$)return;let Z=this.runId;this.write(()=>{let J=l9($);if(J.finishReason===void 0&&Z)J.runId=Z;return[J]})}write(Q){let $;try{$=Q()}catch(Z){this.report(Z);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,$)).catch((Z)=>this.report(Z))}}function l9(Q){return structuredClone(Q)}async function j3(Q,$){let Z=[],J=null,W=Q.slice();for(let G=0;G<W.length;G++){let X=W[G];if(X.role!=="assistant"||X.finishReason!==void 0)continue;if(X.runId&&await $(X.runId))continue;J??=new Set(Q.flatMap((V)=>V.content.flatMap((K)=>K.type==="tool-result"?[K.toolCallId]:[])));let Y=X.content.map((V)=>V.type==="tool-call"?L3(V):V);for(let V of X.content){if(V.type!=="tool-call"||J.has(V.toolCallId))continue;let K={type:"tool-result",toolCallId:V.toolCallId,name:V.name,status:"denied",cause:"interrupted"};Y.push(K)}let H={...X,content:Y,finishReason:"interrupted"};W[G]=H,Z.push(H)}return{messages:W,settled:Z}}function L3(Q){let{partial:$,...Z}=Q;if(!Z.nested?.some((J)=>J.finishReason===void 0))return Z;return{...Z,nested:Z.nested.map(q1)}}function q1(Q){if(Q.finishReason!==void 0)return Q;return{...Q,finishReason:"interrupted",messages:Q.messages.map(($)=>$.role==="assistant"&&$.finishReason===void 0?{...$,finishReason:"interrupted",content:$.content.map((Z)=>Z.type==="tool-call"?L3(Z):Z)}:$)}}var O1=A3,yQ=new Map,C3=new WeakMap,gQ=new Map,N1=4194304,_1=1000,M1=5,P3=65536,w3=()=>{};class I3{byKey=new Map;take(Q,$,Z){let J=this.byKey.get(Q);if(!J?.has($)&&(J?.size??0)>=Z)return null;if(!J)J=new Map,this.byKey.set(Q,J);J.set($,(J.get($)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let G=this.byKey.get(Q),X=(G?.get($)??1)-1;if(!G)return;if(X>0)G.set($,X);else if(G.delete($),G.size===0)this.byKey.delete(Q)}}}var q3=new WeakMap;function S1(Q){let $=q3.get(Q);if(!$)$=new I3,q3.set(Q,$);return $}class r9 extends O1{static kind="agent-controller";store=d9;liveRuns=g9;attachments=SQ;attachmentStorage=x3;fileOwners=u9;nonces=i;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions(Q,$){}context(Q,$){return{}}requireThread=!1;maxBodyBytes=N1;maxHistoryMessages=_1;contextWindow=void 0;prepareStep(Q,$){}maxConcurrentRuns=M1;runLimitKey(Q,$){return $.owner}authorizeRequest(Q,$){}runOwner(Q){let $=Q.ctx?.()?.user,Z=$?.id??$?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}async stream(Q=new zQ){let $=await o9(Q,this.maxBodyBytes);if($.error)return uQ($);let Z=$.body,J=typeof Z.threadId==="string"?Z.threadId:void 0,W=w1(Z);if(W.error)return uQ({body:{},error:W.error});let G=W.turn,X=J!==void 0&&Z.regenerate===!0,Y=typeof Z.clientRunId==="string"?Z.clientRunId:void 0,H=v3(Z);if(this.requireThread&&!J)return b(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(X&&!this.store.removeMessages)return b(501,{code:"regenerate_unsupported",message:"This agent's store cannot remove messages, so a thread's answer cannot be regenerated. Implement `removeMessages` on the AgentStore."});if(!J&&Array.isArray(Z.messages)&&Z.messages.length>this.maxHistoryMessages)return t9(413,"history_too_long",`The conversation has ${Z.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let V=await this.runOwner(Q),K=Y?{cancelled:!1,owner:V}:null;if(K)gQ.set(Y,K);let z=null,B=[],U=async()=>{try{return await F()}finally{if(J&&B.length>0&&z===null)await this.store.appendMessages(J,B).catch((D)=>this.reportHookFailure(D))}},F=async()=>{let D;if(J){let P=await this.store.loadThread(J);if(!P)return b(404,{code:"thread_not_found",message:`Thread ${J} does not exist here, or has expired.`});if(D=await this.settleThread(J,P,{write:!0}),X){let q=h1(D);if(!q)return b(409,{code:"nothing_to_regenerate",message:`Thread ${J} has no user turn to answer again.`});B=D.slice(q.index),await this.store.removeMessages(J,B.map((g3)=>g3.id)),D=D.slice(0,q.index),G=G?.localId?{...q.turn,localId:G.localId}:q.turn}}else D=Array.isArray(Z.messages)?Z.messages:[],d1(this.nonces);let j=await this.instructions(Q,{body:H})||void 0,L=await this.context(Q,{body:H}),S=await this.attachmentsFor(Q,J,{body:H});if(K?.cancelled)return S3();let N=J?new i9(this.store,J,D,(P)=>this.reportHookFailure(P)):null,v=`run_${crypto.randomUUID()}`,E={req:Q,runId:v,threadId:J},_=this.agent.stream({runId:v,messages:D,turn:G,threadId:J,...N?{onMessage:(P)=>N.finish(P)}:{},instructions:j,context:L,attachments:S,body:H,redactError:(P,q)=>this.redactError(P,q,E),nonces:this.nonces,receipts:this.receipts,subject:V,...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...this.prepareStep!==r9.prototype.prepareStep?{prepareStep:(P)=>this.prepareStep(P,E)}:{}}),w=this.liveRuns.register(_,{threadId:J,owner:V,clientRunId:Y,onEvent:(P)=>this.dispatchEvent(P,E),onInternalError:(P)=>this.reportHookFailure(P),maxRunDurationMs:this.agent.maxRunDurationMs});if(z=_,N)this.follow(_,N);let{stored:O,hooks:C}=this.persistRun(_,E,w,N);return C3.set(_,O),Q.ctx?.()?.waitUntil(C),_.toResponse()};try{await this.authorizeRequest(Q,{route:"stream",threadId:J,body:H});let D=await this.foreignFile([...G?.files??[],...J?[]:g1(Z.messages)],V);if(D)return D;if(K?.cancelled)return S3();let j=await this.runLimitKey(Q,{owner:V,threadId:J}),L=j===null?w3:S1(this.liveRuns).take(j,J?`thread:${J}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!L)return t9(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);try{return J?await this.withThread(J,V,U):await U()}finally{let S=z;if(S)S.result().then(L,L);else L()}}finally{if(K&&gQ.get(Y)===K)gQ.delete(Y)}}async withThread(Q,$,Z){let J=yQ.get(Q)??Promise.resolve(),W,G=new Promise((Y)=>{W=Y}),X=J.then(()=>G);yQ.set(Q,X),await J;try{let Y=await this.liveRuns.find({threadId:Q});if(Y&&this.liveRuns.isRunning(Y.runId)&&!this.liveRuns.mayAccess(Y.runId,$))return cQ();let H=Y?this.liveRuns.get(Y.runId):null;if(H)H.stop({reason:"superseded by a later turn on this thread"}),await C3.get(H);return await Z()}finally{if(W(),yQ.get(Q)===X)yQ.delete(Q)}}async attach(Q=new zQ){let $=await o9(Q,P3);if($.error)return uQ($);let Z=$.body,J=typeof Z.threadId==="string"?Z.threadId:f1(Q,"threadId");if(!J)return b(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(Q,{route:"attach",threadId:J});let W=await this.liveRuns.find({threadId:J});if(W&&!this.liveRuns.mayAccess(W.runId,await this.runOwner(Q)))return cQ();if(!W)return b(404,{code:"no_live_run",message:`No run in progress for thread ${J} in this process.`});let G=typeof Z.runId==="string"?Z.runId:void 0,X=G&&G!==W.runId?void 0:v1(Q,Z);try{return q$(this.liveRuns.replay(W.runId,X))}catch(Y){if(Y instanceof e)return b(410,{code:Y.code,message:Y.message,oldestSeq:Y.oldest});if(Y instanceof BQ)return b(404,{code:Y.code,message:Y.message});throw Y}}async stop(Q=new zQ){let $=await o9(Q,P3);if($.error)return uQ($);let Z=$.body;await this.authorizeRequest(Q,{route:"stop",threadId:typeof Z.threadId==="string"?Z.threadId:void 0});let J=await this.runOwner(Q),W=typeof Z.runId==="string"?Z.runId:void 0;if(!W&&typeof Z.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId(Z.clientRunId)??void 0,!W){let X=gQ.get(Z.clientRunId);if(X){if(X.owner!==null&&X.owner!==J)return cQ();return X.cancelled=!0,{stopped:!0}}}}if(!W&&typeof Z.threadId==="string")W=(await this.liveRuns.find({threadId:Z.threadId}))?.runId;let G=W?this.liveRuns.get(W):null;if(!G)return{stopped:!1};if(!this.liveRuns.mayAccess(G.runId,J))return cQ();return G.stop({reason:typeof Z.reason==="string"?Z.reason:void 0}),{stopped:!0}}attachmentScope(Q,$,Z){let J=Q.ctx()?.user,W=J?.id??J?.publicId;if(W!==void 0&&W!==null&&String(W)!=="")return{key:`user:${String(W)}`};if($)return{key:`thread:${$}`};return null}attachmentLimits(Q){return null}attachmentDestination(Q,$){return"both"}async attachmentsFor(Q,$,Z={body:{}}){let J=await this.attachmentScope(Q,$,Z);if(!J)return null;return new VQ(this.attachments,this.attachmentStorage,J)}async upload(Q=new zQ){let $=await Q.rawRequest.formData(),Z=$.get("file");if(!(Z instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let J=Z instanceof File&&Z.name?Z.name:"upload",W=Z.type||"application/octet-stream",G=T1($.get("body")),X=$.get("threadId");await this.authorizeRequest(Q,{route:"upload",threadId:typeof X==="string"&&X.length>0?X:void 0,body:G});let Y=k1(await this.attachmentLimits(Q),Z,J,W);if(Y)throw new f3(Y.code,Y.message);let H=typeof X==="string"&&X.length>0&&await this.store.loadThread(X)!==null?X:void 0,V=await this.runOwner(Q),K=(N)=>this.fileOwners.record(N,{owner:V,name:J,mimeType:W,size:Z.size,createdAt:new Date().toISOString()}),z=await this.attachmentDestination(Z,Q),B=u1(z,$.get("destination")),U=await this.attachmentScope(Q,H,{body:G}),F=B!=="provider"&&!U;if(F){if(B==="storage")throw Error('This upload was routed to storage, but `attachmentScope()` returned null for the request, so there is no subject to file the attachment under. Guard the route (`this.agent(Chat).middleware({ upload: "auth" })`), send a `threadId` with the upload, or override `attachmentScope()`.');c1()}if(B==="provider"||!U){let N=await O3(this.agent.provider,Z);await K(N);let v={fileId:N,name:J,mimeType:W,size:Z.size,destination:"provider"};if(F)v.downgraded="no_scope";return v}let D=eQ(),j=await this.attachmentStorage.put({name:Q9(D,J),body:Z,contentType:W}),L=B==="both"?await O3(this.agent.provider,Z):void 0;if(L)await K(L);let S={id:D,scopeKey:U.key,fileId:L,objectName:j,name:J,mimeType:W,size:Z.size,createdAt:new Date().toISOString(),destination:B};return await this.attachments.put(U,S),{fileId:L,attachmentId:D,name:J,mimeType:W,size:Z.size,destination:B}}async foreignFile(Q,$){let Z=new Set(Q.map((J)=>J.fileId).filter((J)=>typeof J==="string"));for(let J of Z){let W=await this.fileOwners.get(J);if(W?W.owner!==null&&W.owner!==$:this.requireKnownFiles)return y1()}return null}onMessage(Q,$){}onToolCall(Q,$){}onAwaitingInput(Q,$){}redactError(Q,$,Z){return a9(Q,$)}onError(Q,$){}onStreamComplete(Q,$){}reportHookFailure(Q){console.error("[gemi/ai] agent controller hook failed",Q)}async dispatchEvent(Q,$){switch(Q.type){case"tool-call":if(!Q.part.partial&&!Q.resent)await this.onToolCall({toolCallId:Q.part.toolCallId,name:String(Q.part.name),input:Q.part.input},$);return;case"awaiting-input":await this.onAwaitingInput(Q.pending,$);return;case"error":await this.onError(b3(Q.error),$);return;default:return}}async readThread(Q){let $=await this.store.loadThread(Q);return $?await this.settleThread(Q,$,{write:!1}):null}isRunLive(Q,$){return this.liveRuns.get(Q)!==null}async settleThread(Q,$,{write:Z}){let{messages:J,settled:W}=await j3($,(G)=>this.isRunLive(G,Q));if(Z&&W.length>0)try{await this.store.appendMessages(Q,W)}catch(G){this.reportHookFailure(G)}return J}follow(Q,$){(async()=>{try{for await(let Z of Q.frames())$.frame(Z)}catch(Z){this.reportHookFailure(Z)}})()}persistRun(Q,$,Z,J=null){let W=Promise.resolve(),G=(async()=>{let Y;try{Y=await Q.result()}catch(V){J?.close(),await J?.settled(),W=this.safely(()=>this.onError({code:"unknown",message:V instanceof Error?V.message:String(V),retryable:!1},$));return}let H=Y.messages;if(J?.close(H),await J?.settled(),$.threadId&&H.length>0)try{await this.store.appendMessages($.threadId,H)}catch(V){this.reportHookFailure(V)}W=this.notifyRun(Y,H,$)})(),X=G.then(()=>p1(Promise.all([W,Z]).then(()=>{}),this.hookHoldMs));return{stored:G,hooks:X}}async notifyRun(Q,$,Z){for(let J of $)await this.safely(()=>this.onMessage(J,Z));await this.safely(()=>this.onStreamComplete(Q,Z))}async safely(Q){try{await Q()}catch($){this.reportHookFailure($)}}}var n9=["turn","clientRunId","threadId","messages","regenerate"],R1=["text","files","toolResults"];function v3(Q,$=y3(Q)?n9:[...n9,...R1]){let Z={};for(let[J,W]of Object.entries(Q)){if($.includes(J))continue;Object.defineProperty(Z,J,{value:W,writable:!0,enumerable:!0,configurable:!0})}return Z}function T1(Q){if(Q===null)return{};let $;if(typeof Q==="string")try{$=JSON.parse(Q)}catch{throw new s9("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new s9("The upload's `body` field must be a JSON object.");return v3($,n9)}class s9 extends mQ{constructor(Q){super(Q);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:Q}}},view:{}}}}async function O3(Q,$){try{return await Q.upload($)}catch(Z){if(Z instanceof h&&A1.has(Z.status))throw new h3(A(Z).message);throw Z}}var A1=new Set([400,413,415,422]);class f3 extends mQ{constructor(Q,$){super($);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:Q,message:$}}},view:{}}}}function k1(Q,$,Z,J){if(!Q)return null;let{maxBytes:W,accept:G}=Q;if(typeof W==="number"&&$.size>W)return{code:"file_too_large",message:`${JSON.stringify(Z)} is ${N3($.size)}; the limit is ${N3(W)}.`};if(G&&G.length>0&&!G.some((X)=>E1(X,Z,J)))return{code:"unsupported_file_type",message:`${JSON.stringify(Z)} is not a type this chat accepts. Accepted: ${G.join(", ")}.`};return null}function E1(Q,$,Z){let J=Q.trim().toLowerCase();if(!J)return!1;if(J.startsWith("."))return $.toLowerCase().endsWith(J);let W=Z.toLowerCase().split(";")[0].trim();if(J.endsWith("/*"))return W.startsWith(J.slice(0,-1));return W===J}function N3(Q){if(Q<1024)return`${Q} B`;let $=["KB","MB","GB"],Z=Q/1024,J=0;while(Z>=1024&&J<$.length-1)Z/=1024,J++;return`${Math.round(Z*10)/10} ${$[J]}`}class h3 extends mQ{constructor(Q){super(Q);this.name="RejectedUploadError";let $=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test(Q)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:$,message:Q}}},view:{}}}}async function o9(Q,$){let Z=Q?.rawRequest;if(!Z||Z.method==="GET"||Z.method==="HEAD"||!Z.body)return{body:{}};if(!x1(Z.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let J=Number(Z.headers.get("Content-Length"));if(Number.isFinite(J)&&J>$)return _3($);let W;try{let X=await b1(Z,$);if(X===null)return _3($);W=X}catch{return{body:{},error:"The request body could not be read."}}if(!W.trim())return{body:{}};let G;try{G=JSON.parse(W)}catch{return{body:{},error:"The request body is not valid JSON."}}if(G===null||typeof G!=="object"||Array.isArray(G))return{body:{},error:"The request body must be a JSON object."};return{body:G}}function x1(Q){return E3(Q)==="application/json"}async function b1(Q,$){if(!Number.isFinite($)||!Q.body)return await Q.text();let Z=Q.body.getReader(),J=[],W=0;for(;;){let{done:Y,value:H}=await Z.read();if(Y)break;if(W+=H.byteLength,W>$)return await Z.cancel().catch(w3),null;J.push(H)}let G=new Uint8Array(W),X=0;for(let Y of J)G.set(Y,X),X+=Y.byteLength;return new TextDecoder().decode(G)}function _3(Q){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${Q} bytes).`}}function t9(Q,$,Z){return b(Q,{...pQ(k3(Q),Z,Q),code:$})}function uQ(Q){if(Q.status===413)return t9(413,Q.code??"body_too_large",Q.error??"");return b(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function y3(Q){return Boolean(Q.turn)&&typeof Q.turn==="object"}function w1(Q){let $=y3(Q)?Q.turn:Q,Z={};if(typeof $.text==="string")Z.text=$.text;if(Array.isArray($.files)){let J=I1($.files);if(typeof J==="string")return{error:J};Z.files=J}if(Array.isArray($.toolResults))Z.toolResults=$.toolResults;if(Object.keys(Z).length===0)return{};if($===Q.turn&&$.localId!==void 0&&$.localId!==null&&$.localId!==""){let{localId:J}=$;if(typeof J!=="string")return{error:"turn.localId must be a string."};if(J.length>M3)return{error:`turn.localId is longer than ${M3} characters.`};Z.localId=J}return{turn:Z}}var M3=200;function I1(Q){let $=[];for(let[Z,J]of Q.entries()){let W=`turn.files[${Z}]`;if(!J||typeof J!=="object"||Array.isArray(J))return`${W} must be an object.`;let G={};for(let K of["fileId","attachmentId","name","mimeType"]){let z=J[K];if(z===void 0||z===null||z==="")continue;if(typeof z!=="string")return`${W}.${K} must be a string.`;G[K]=z}let{fileId:X,attachmentId:Y,name:H,mimeType:V}=G;if(X?.startsWith(f))return`${W}.fileId holds a gemi attachment id (${X}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(Y!==void 0&&!Y.startsWith(f))return`${W}.attachmentId is not a gemi attachment id: it must start with "${f}".`;if(!X&&!Y)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...X?{fileId:X}:{},...Y?{attachmentId:Y}:{},...H!==void 0?{name:H}:{},...V!==void 0?{mimeType:V}:{}})}return $}function v1(Q,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let J=Math.floor($.cursor);if(J>=0)return J+1;return}let Z=Q?.rawRequest?.headers?.get("Last-Event-ID");if(Z){let J=Number.parseInt(Z,10);if(Number.isFinite(J))return Math.max(0,J+1)}return}function f1(Q,$){let Z=Q?.search?.get($);return typeof Z==="string"?Z:void 0}function h1(Q){let $=u(Q);for(let Z=Q.length-1;Z>=0;Z--){let J=Q[Z];if(J.role!=="user"||$.has(J.id))continue;let W="",G=[];for(let X of J.content){if(X.type==="text")W+=X.text;if(X.type==="file")G.push({...X.fileId?{fileId:X.fileId}:{},...X.attachmentId?{attachmentId:X.attachmentId}:{},...X.name?{name:X.name}:{},...X.mimeType?{mimeType:X.mimeType}:{}})}if(!W&&G.length===0)continue;return{index:Z,turn:{...W?{text:W}:{},...G.length>0?{files:G}:{}}}}return null}function S3(){return b(409,{code:"stopped",message:"The turn was stopped before it started."})}function cQ(){return b(403,pQ("permission","This run belongs to someone else.",403))}function y1(){return b(403,pQ("permission","A file in this turn was uploaded by someone else.",403))}function g1(Q){if(!Array.isArray(Q))return[];let $=[];for(let Z of Q){let J=Z?.content;if(!Array.isArray(J))continue;for(let W of J)if(W&&typeof W==="object"&&typeof W.fileId==="string")$.push({fileId:W.fileId})}return $}function b(Q,$){return new Response(JSON.stringify({error:$}),{status:Q,headers:{"Content-Type":"application/json"}})}function u1(Q,$){if(typeof $!=="string"||$.length===0)return Q;if($!=="both"&&$!=="provider"&&$!=="storage")throw Error(`Unknown attachment destination "${$}". Expected "both", "provider" or "storage".`);if($===Q||Q==="both"&&$==="storage")return $;if(Q==="both"&&$==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${$}" destination, but the server's policy for it is "${Q}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var R3=!1;function c1(){if(R3)return;R3=!0,console.warn("[gemi/ai] An upload had no attachment scope, so its bytes were sent to the model provider only and no attachment id was minted \u2014 a tool cannot forward this file. Guard the route with auth, send a `threadId` with the upload, or override `attachmentScope()`.")}var m1=2147483647;function p1(Q,$){let Z=Q.then(()=>{},()=>{});if(!($<=m1))return Z;let J,W=new Promise((G)=>{J=setTimeout(G,$)});return Promise.race([Z,W]).finally(()=>clearTimeout(J))}var T3=!1;function d1(Q){if(T3||Bun.env.NODE_ENV!=="production")return;if(!(Q instanceof WQ))return;T3=!0,console.warn("[gemi/ai] A stateless agent chat is spending approval nonces in process memory. With more than one instance a replayed approval is accepted once per instance. Set `nonces = new RedisNonceStore()` (or your own NonceStore) on the AgentController.")}export{G9 as windowMessages,W9 as turnStarts,SZ as toAgentTools,QQ as supportsStrict,HZ as splitTurns,i1 as s,a9 as redactError,N$ as messageSize,g9 as liveRuns,u as injectedMessageIds,l3 as generate,K1 as evalChain,i as defaultNonceStore,u9 as defaultFileOwners,SQ as defaultAttachmentStore,d9 as defaultAgentStore,n as ToolNamespace,T as ToolError,z9 as Skill,VQ as ScopedAttachments,YQ as SKILLS_NAMESPACE,p9 as RedisReceiptStore,lQ as RedisNonceStore,c as PendingEscalation,I9 as OpenAIProvider,O9 as OpenAIImageProvider,m9 as MemoryReceiptStore,WQ as MemoryNonceStore,vQ as MemoryLiveRuns,fQ as MemoryFileOwners,IQ as MemoryCircuitStore,MQ as MemoryAttachmentStore,hQ as MemoryAgentStore,BQ as LiveRunNotFoundError,l1 as JSONSchemaError,o as InvalidAttachmentScopeError,xQ as ImageRequestError,bQ as ImageProvider,C9 as ImageModel,e as FrameCursorEvictedError,KQ as FallbackProvider,F9 as DEFAULT_MAX_RUN_DURATION_MS,_$ as DEFAULT_CONTEXT_WINDOW_STEP,M$ as DEFAULT_CONTEXT_WINDOW_NOTE,v9 as AzureOpenAIProvider,N9 as AzureOpenAIImageProvider,XQ as AttachmentNotFoundError,m as AgentTool,JQ as AgentRunError,r as AgentProvider,r9 as AgentController,j9 as Agent};
|
|
25
25
|
|
|
26
|
-
//# debugId=
|
|
26
|
+
//# debugId=D79E59278DA579ED64756E2164756E21
|