gemi 0.204.2 → 0.205.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/AgentProvider.d.ts +83 -3
- package/dist/ai/AgentProvider.d.ts.map +1 -1
- package/dist/ai/client/index.js +12 -10
- package/dist/ai/client/index.js.map +1 -1
- package/dist/ai/index.d.ts +2 -2
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +4 -4
- package/dist/ai/index.js.map +3 -3
- package/dist/ai/providers/anthropicRequest.d.ts +142 -0
- package/dist/ai/providers/anthropicRequest.d.ts.map +1 -0
- package/dist/ai/providers/anthropicStream.d.ts +54 -0
- package/dist/ai/providers/anthropicStream.d.ts.map +1 -0
- package/dist/ai/providers/call.d.ts +14 -3
- package/dist/ai/providers/call.d.ts.map +1 -1
- package/dist/ai/providers/capabilities.d.ts +31 -0
- package/dist/ai/providers/capabilities.d.ts.map +1 -1
- package/dist/ai/providers/endpoints.d.ts +51 -0
- package/dist/ai/providers/endpoints.d.ts.map +1 -1
- package/dist/ai/providers/http.d.ts.map +1 -1
- package/dist/ai/providers/request.d.ts +43 -1
- package/dist/ai/providers/request.d.ts.map +1 -1
- package/dist/ai/runtime.d.ts +5 -1
- package/dist/ai/runtime.d.ts.map +1 -1
- package/dist/ai/testing/RecordingProvider.d.ts +5 -2
- package/dist/ai/testing/RecordingProvider.d.ts.map +1 -1
- package/dist/ai/testing/index.js +3 -3
- package/dist/ai/testing/index.js.map +3 -3
- package/dist/ai/types.d.ts +34 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/usageMeter.d.ts +4 -1
- package/dist/ai/usageMeter.d.ts.map +1 -1
- package/dist/app/index.js +2 -2
- package/dist/app/index.js.map +1 -1
- 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-2t1eyzvq.js → chunk-06w8hhnk.js} +2 -2
- package/dist/{chunk-2t1eyzvq.js.map → chunk-06w8hhnk.js.map} +1 -1
- package/dist/{chunk-0t1d9s34.js → chunk-09hzyf9g.js} +3 -3
- package/dist/{chunk-0t1d9s34.js.map → chunk-09hzyf9g.js.map} +1 -1
- package/dist/{chunk-bq4pgzcd.js → chunk-0cckwd91.js} +2 -2
- package/dist/{chunk-bq4pgzcd.js.map → chunk-0cckwd91.js.map} +1 -1
- package/dist/{chunk-9hqnecjt.js → chunk-0eq7am78.js} +2 -2
- package/dist/{chunk-9hqnecjt.js.map → chunk-0eq7am78.js.map} +1 -1
- package/dist/{chunk-jma5d7zd.js → chunk-1em8t2x1.js} +3 -3
- package/dist/{chunk-jma5d7zd.js.map → chunk-1em8t2x1.js.map} +1 -1
- package/dist/{chunk-ek0dvbck.js → chunk-1tc6j8bn.js} +3 -3
- package/dist/{chunk-ek0dvbck.js.map → chunk-1tc6j8bn.js.map} +1 -1
- package/dist/{chunk-dk1xxtgk.js → chunk-24tj4dzx.js} +2 -2
- package/dist/{chunk-dk1xxtgk.js.map → chunk-24tj4dzx.js.map} +1 -1
- package/dist/{chunk-s5hdrpam.js → chunk-34vvev4a.js} +3 -3
- package/dist/{chunk-s5hdrpam.js.map → chunk-34vvev4a.js.map} +1 -1
- package/dist/{chunk-f52maa9b.js → chunk-3830ee5d.js} +2 -2
- package/dist/{chunk-f52maa9b.js.map → chunk-3830ee5d.js.map} +1 -1
- package/dist/{chunk-yykrvrpt.js → chunk-39dz1abf.js} +1 -1
- package/dist/{chunk-yjvqq4hj.js → chunk-3ek0s8fx.js} +2 -2
- package/dist/{chunk-yjvqq4hj.js.map → chunk-3ek0s8fx.js.map} +1 -1
- package/dist/{chunk-vsd5h2d9.js → chunk-3z8d8v8q.js} +3 -3
- package/dist/{chunk-vsd5h2d9.js.map → chunk-3z8d8v8q.js.map} +1 -1
- package/dist/{chunk-f9c8bnzx.js → chunk-460c8k50.js} +3 -3
- package/dist/{chunk-f9c8bnzx.js.map → chunk-460c8k50.js.map} +1 -1
- package/dist/{chunk-wxyxnbh6.js → chunk-4ksnhx8x.js} +4 -4
- package/dist/{chunk-wxyxnbh6.js.map → chunk-4ksnhx8x.js.map} +1 -1
- package/dist/chunk-4q59y78y.js +5 -0
- package/dist/{chunk-cf7xc02m.js.map → chunk-4q59y78y.js.map} +1 -1
- package/dist/{chunk-4m8t67px.js → chunk-65btke6p.js} +2 -2
- package/dist/{chunk-4m8t67px.js.map → chunk-65btke6p.js.map} +1 -1
- package/dist/{chunk-efnerp0c.js → chunk-6cx6kh04.js} +2 -2
- package/dist/{chunk-efnerp0c.js.map → chunk-6cx6kh04.js.map} +1 -1
- package/dist/{chunk-jmsfkzav.js → chunk-6ge27ygx.js} +2 -2
- package/dist/{chunk-jmsfkzav.js.map → chunk-6ge27ygx.js.map} +1 -1
- package/dist/{chunk-x26jb60f.js → chunk-6x2zbh1q.js} +2 -2
- package/dist/{chunk-x26jb60f.js.map → chunk-6x2zbh1q.js.map} +1 -1
- package/dist/{chunk-0hfzzb3k.js → chunk-6zpf257t.js} +3 -3
- package/dist/{chunk-0hfzzb3k.js.map → chunk-6zpf257t.js.map} +1 -1
- package/dist/{chunk-cq7hk8v9.js → chunk-72e857nw.js} +2 -2
- package/dist/{chunk-cq7hk8v9.js.map → chunk-72e857nw.js.map} +1 -1
- package/dist/{chunk-4v5c4mes.js → chunk-77dt2tap.js} +2 -2
- package/dist/{chunk-4v5c4mes.js.map → chunk-77dt2tap.js.map} +1 -1
- package/dist/{chunk-ptpzh61m.js → chunk-78g1cngk.js} +2 -2
- package/dist/{chunk-ptpzh61m.js.map → chunk-78g1cngk.js.map} +1 -1
- package/dist/{chunk-d7kknkmq.js → chunk-7wzhdq1x.js} +3 -3
- package/dist/{chunk-d7kknkmq.js.map → chunk-7wzhdq1x.js.map} +1 -1
- package/dist/{chunk-cg009t41.js → chunk-8a5wngew.js} +2 -2
- package/dist/{chunk-cg009t41.js.map → chunk-8a5wngew.js.map} +1 -1
- package/dist/{chunk-6g1xac70.js → chunk-8ar7180x.js} +2 -2
- package/dist/{chunk-6g1xac70.js.map → chunk-8ar7180x.js.map} +1 -1
- package/dist/{chunk-d3k38gk1.js → chunk-8d2g78vc.js} +2 -2
- package/dist/{chunk-d3k38gk1.js.map → chunk-8d2g78vc.js.map} +1 -1
- package/dist/{chunk-yrbvfda9.js → chunk-8ncqxja2.js} +1 -1
- package/dist/{chunk-6w6q9mxe.js → chunk-8q5kxzxn.js} +3 -3
- package/dist/{chunk-6w6q9mxe.js.map → chunk-8q5kxzxn.js.map} +1 -1
- package/dist/{chunk-y45whafz.js → chunk-9m6mkaqb.js} +2 -2
- package/dist/{chunk-y45whafz.js.map → chunk-9m6mkaqb.js.map} +1 -1
- package/dist/{chunk-zk1vwwv6.js → chunk-9qyet3nb.js} +2 -2
- package/dist/{chunk-zk1vwwv6.js.map → chunk-9qyet3nb.js.map} +1 -1
- package/dist/{chunk-p2nqksdq.js → chunk-a7rgrcs0.js} +3 -3
- package/dist/{chunk-p2nqksdq.js.map → chunk-a7rgrcs0.js.map} +1 -1
- package/dist/{chunk-x244kqcc.js → chunk-a7zqp5m7.js} +2 -2
- package/dist/{chunk-x244kqcc.js.map → chunk-a7zqp5m7.js.map} +1 -1
- package/dist/{chunk-y5kfqq4f.js → chunk-aed0vv5g.js} +2 -2
- package/dist/{chunk-y5kfqq4f.js.map → chunk-aed0vv5g.js.map} +1 -1
- package/dist/{chunk-9m7c4mws.js → chunk-ba1h9pm6.js} +2 -2
- package/dist/{chunk-9m7c4mws.js.map → chunk-ba1h9pm6.js.map} +1 -1
- package/dist/chunk-bb74k64k.js +11 -0
- package/dist/chunk-bb74k64k.js.map +21 -0
- package/dist/{chunk-7gxmf9rg.js → chunk-bpqkzpkt.js} +2 -2
- package/dist/{chunk-7gxmf9rg.js.map → chunk-bpqkzpkt.js.map} +1 -1
- package/dist/{chunk-qcrj4t72.js → chunk-bxznwntw.js} +2 -2
- package/dist/{chunk-qcrj4t72.js.map → chunk-bxznwntw.js.map} +1 -1
- package/dist/{chunk-4c0rb2ng.js → chunk-c8bvpkr2.js} +2 -2
- package/dist/{chunk-4c0rb2ng.js.map → chunk-c8bvpkr2.js.map} +1 -1
- package/dist/{chunk-jeq8wvj6.js → chunk-cffx7wqp.js} +2 -2
- package/dist/{chunk-jeq8wvj6.js.map → chunk-cffx7wqp.js.map} +1 -1
- package/dist/{chunk-8jfnn7v6.js → chunk-djnn8vvp.js} +2 -2
- package/dist/{chunk-8jfnn7v6.js.map → chunk-djnn8vvp.js.map} +1 -1
- package/dist/{chunk-s6bq91cm.js → chunk-dwya9z8p.js} +2 -2
- package/dist/{chunk-s6bq91cm.js.map → chunk-dwya9z8p.js.map} +1 -1
- package/dist/chunk-e0scxs81.js +5 -0
- package/dist/{chunk-xwqdh388.js.map → chunk-e0scxs81.js.map} +4 -4
- package/dist/{chunk-0shq2d31.js → chunk-eeq9ty68.js} +2 -2
- package/dist/{chunk-0shq2d31.js.map → chunk-eeq9ty68.js.map} +1 -1
- package/dist/{chunk-77x9vxht.js → chunk-emt36pxm.js} +2 -2
- package/dist/{chunk-77x9vxht.js.map → chunk-emt36pxm.js.map} +1 -1
- package/dist/{chunk-k62338g2.js → chunk-etcds9w3.js} +2 -2
- package/dist/{chunk-k62338g2.js.map → chunk-etcds9w3.js.map} +1 -1
- package/dist/{chunk-kgjcszx0.js → chunk-fe2nkshn.js} +2 -2
- package/dist/{chunk-kgjcszx0.js.map → chunk-fe2nkshn.js.map} +1 -1
- package/dist/{chunk-d5d3a8bm.js → chunk-fhn92are.js} +2 -2
- package/dist/{chunk-d5d3a8bm.js.map → chunk-fhn92are.js.map} +1 -1
- package/dist/{chunk-crqbzfd5.js → chunk-g6tqje74.js} +2 -2
- package/dist/{chunk-crqbzfd5.js.map → chunk-g6tqje74.js.map} +1 -1
- package/dist/{chunk-p9pwskv6.js → chunk-hke4hzfm.js} +2 -2
- package/dist/{chunk-p9pwskv6.js.map → chunk-hke4hzfm.js.map} +1 -1
- package/dist/{chunk-3gkxnfef.js → chunk-hqg4dfca.js} +2 -2
- package/dist/{chunk-3gkxnfef.js.map → chunk-hqg4dfca.js.map} +1 -1
- package/dist/{chunk-39hed4yr.js → chunk-hthyn5pj.js} +3 -3
- package/dist/{chunk-39hed4yr.js.map → chunk-hthyn5pj.js.map} +1 -1
- package/dist/{chunk-w3mc696j.js → chunk-jn1h76sa.js} +2 -2
- package/dist/{chunk-w3mc696j.js.map → chunk-jn1h76sa.js.map} +1 -1
- package/dist/{chunk-ezvtkbp9.js → chunk-jy26hy7z.js} +2 -2
- package/dist/{chunk-ezvtkbp9.js.map → chunk-jy26hy7z.js.map} +1 -1
- package/dist/{chunk-5km0np8s.js → chunk-jy61580r.js} +2 -2
- package/dist/{chunk-5km0np8s.js.map → chunk-jy61580r.js.map} +1 -1
- package/dist/{chunk-phvvxv1a.js → chunk-k8peybx0.js} +3 -3
- package/dist/{chunk-phvvxv1a.js.map → chunk-k8peybx0.js.map} +1 -1
- package/dist/{chunk-3xzhbkya.js → chunk-m3v661b3.js} +3 -3
- package/dist/{chunk-3xzhbkya.js.map → chunk-m3v661b3.js.map} +1 -1
- package/dist/{chunk-js9rm7g0.js → chunk-ndcqbwsj.js} +2 -2
- package/dist/{chunk-js9rm7g0.js.map → chunk-ndcqbwsj.js.map} +1 -1
- package/dist/{chunk-cdgnwzwf.js → chunk-ne51fxg2.js} +2 -2
- package/dist/{chunk-cdgnwzwf.js.map → chunk-ne51fxg2.js.map} +1 -1
- package/dist/{chunk-b1mdan5a.js → chunk-nfher0gz.js} +2 -2
- package/dist/{chunk-b1mdan5a.js.map → chunk-nfher0gz.js.map} +1 -1
- package/dist/{chunk-e5mqjren.js → chunk-njnng5ew.js} +4 -4
- package/dist/{chunk-e5mqjren.js.map → chunk-njnng5ew.js.map} +1 -1
- package/dist/{chunk-e3ehv27z.js → chunk-p9c5rc1z.js} +3 -3
- package/dist/{chunk-e3ehv27z.js.map → chunk-p9c5rc1z.js.map} +1 -1
- package/dist/{chunk-rr8bzm6k.js → chunk-q1t9gvm1.js} +2 -2
- package/dist/{chunk-rr8bzm6k.js.map → chunk-q1t9gvm1.js.map} +1 -1
- package/dist/{chunk-xvk6aqd7.js → chunk-q751b0jx.js} +3 -3
- package/dist/{chunk-xvk6aqd7.js.map → chunk-q751b0jx.js.map} +1 -1
- package/dist/{chunk-1kehwa3s.js → chunk-qc0e278w.js} +1 -1
- package/dist/{chunk-re9ac4tc.js → chunk-rbkvkv2m.js} +4 -4
- package/dist/{chunk-re9ac4tc.js.map → chunk-rbkvkv2m.js.map} +1 -1
- package/dist/{chunk-k1gt7fgy.js → chunk-rjtge67x.js} +3 -3
- package/dist/{chunk-k1gt7fgy.js.map → chunk-rjtge67x.js.map} +1 -1
- package/dist/{chunk-ybcdxrqx.js → chunk-s1fa5f8b.js} +2 -2
- package/dist/{chunk-ybcdxrqx.js.map → chunk-s1fa5f8b.js.map} +1 -1
- package/dist/{chunk-8pw4zjnx.js → chunk-scw0vknj.js} +1 -1
- package/dist/{chunk-gc9g7c4p.js → chunk-sjve1yvv.js} +3 -3
- package/dist/{chunk-gc9g7c4p.js.map → chunk-sjve1yvv.js.map} +1 -1
- package/dist/{chunk-wn4j741t.js → chunk-te4vz0rw.js} +2 -2
- package/dist/{chunk-wn4j741t.js.map → chunk-te4vz0rw.js.map} +1 -1
- package/dist/{chunk-2ngdhbz7.js → chunk-tx5zrdmb.js} +2 -2
- package/dist/{chunk-2ngdhbz7.js.map → chunk-tx5zrdmb.js.map} +1 -1
- package/dist/{chunk-pq15dt8j.js → chunk-v1d7xya8.js} +15 -15
- package/dist/{chunk-pq15dt8j.js.map → chunk-v1d7xya8.js.map} +5 -5
- package/dist/{chunk-fq5b1k4n.js → chunk-v2fd69at.js} +2 -2
- package/dist/{chunk-fq5b1k4n.js.map → chunk-v2fd69at.js.map} +1 -1
- package/dist/{chunk-n5k42dh7.js → chunk-vebstesm.js} +3 -3
- package/dist/{chunk-n5k42dh7.js.map → chunk-vebstesm.js.map} +1 -1
- package/dist/{chunk-n3kg99yw.js → chunk-vyaedzr8.js} +3 -3
- package/dist/{chunk-n3kg99yw.js.map → chunk-vyaedzr8.js.map} +1 -1
- package/dist/{chunk-9bjggtdt.js → chunk-wdrmzjtq.js} +2 -2
- package/dist/{chunk-9bjggtdt.js.map → chunk-wdrmzjtq.js.map} +1 -1
- package/dist/{chunk-5gvc03cv.js → chunk-wfees83q.js} +3 -3
- package/dist/{chunk-5gvc03cv.js.map → chunk-wfees83q.js.map} +1 -1
- package/dist/{chunk-n26atakz.js → chunk-wpfempaj.js} +3 -3
- package/dist/{chunk-n26atakz.js.map → chunk-wpfempaj.js.map} +1 -1
- package/dist/{chunk-0pgk811s.js → chunk-wrfz0jsw.js} +2 -2
- package/dist/{chunk-0pgk811s.js.map → chunk-wrfz0jsw.js.map} +1 -1
- package/dist/{chunk-c7nbzryd.js → chunk-xgc5tj8k.js} +3 -3
- package/dist/{chunk-c7nbzryd.js.map → chunk-xgc5tj8k.js.map} +1 -1
- package/dist/{chunk-1e82gfk9.js → chunk-yj1h4rzn.js} +3 -3
- package/dist/{chunk-1e82gfk9.js.map → chunk-yj1h4rzn.js.map} +1 -1
- package/dist/{chunk-k9882kqg.js → chunk-zf1eqgzt.js} +2 -2
- package/dist/{chunk-k9882kqg.js.map → chunk-zf1eqgzt.js.map} +1 -1
- package/dist/{chunk-4ex4s616.js → chunk-znw55n6g.js} +2 -2
- package/dist/{chunk-4ex4s616.js.map → chunk-znw55n6g.js.map} +1 -1
- package/dist/{chunk-6bfj0mbp.js → chunk-zvk6dydb.js} +3 -3
- package/dist/{chunk-6bfj0mbp.js.map → chunk-zvk6dydb.js.map} +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/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/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/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/probe/index.js +2 -2
- package/dist/probe/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vitest/index.js +2 -2
- package/dist/vitest/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-1x60thpm.js +0 -8
- package/dist/chunk-1x60thpm.js.map +0 -19
- package/dist/chunk-cf7xc02m.js +0 -5
- package/dist/chunk-xwqdh388.js +0 -5
- /package/dist/{chunk-yykrvrpt.js.map → chunk-39dz1abf.js.map} +0 -0
- /package/dist/{chunk-yrbvfda9.js.map → chunk-8ncqxja2.js.map} +0 -0
- /package/dist/{chunk-1kehwa3s.js.map → chunk-qc0e278w.js.map} +0 -0
- /package/dist/{chunk-8pw4zjnx.js.map → chunk-scw0vknj.js.map} +0 -0
|
@@ -7,6 +7,6 @@
|
|
|
7
7
|
"import type { Application, ShutdownReport } from \"../../foundation/Application\";\nimport {\n heldWork,\n heldWorkSettled,\n markShuttingDown,\n shutdownSettings,\n type ShutdownSettings,\n} from \"../../server/shutdown\";\nimport { memoryBroadcastInWorker } from \"../broadcast/workerWarning\";\nimport { QueueManager } from \"./QueueManager\";\n\n/** The part of a `Kernel` a worker drives. */\nexport type WorkerKernel = {\n readonly app: Application;\n waitForBoot(): Promise<void>;\n shutdown(options?: { timeoutMs?: number }): Promise<ShutdownReport>;\n};\n\n/**\n * A worker that was told to start in an application it cannot claim for. The\n * message is written for the operator reading the deploy's logs.\n */\nexport class QueueWorkerRefused extends Error {\n name = \"QueueWorkerRefused\";\n}\n\n/**\n * The process `gemi queue:work` runs: the application booted as a server boots\n * it, claiming from the queue, and no `Bun.serve`. It exists so job capacity\n * can be scaled apart from request traffic, which needs a driver both kinds of\n * process can reach; see `start` for why the memory driver is refused.\n *\n * The caller marks the process as a worker (`markQueueWorker`) before the\n * kernel registers, so every claim rule that asks `claimsInThisProcess` sees a\n * process that claims, whatever `GEMI_QUEUE_CLAIM` says.\n */\nexport class QueueWorker {\n private stopping: Promise<number> | undefined;\n private keepAlive: ReturnType<typeof setInterval> | undefined;\n private readonly settings: ShutdownSettings;\n\n /**\n * `settings` default to the `GEMI_SHUTDOWN_*` variables, read here rather\n * than at the signal so a bad value is warned about while the deploy is\n * being watched, as `Server.start` does.\n */\n constructor(\n private readonly kernel: WorkerKernel,\n settings: Partial<ShutdownSettings> = {},\n ) {\n this.settings = { ...shutdownSettings(), ...settings };\n }\n\n /**\n * Boots the application and starts claiming. Rejects with\n * `QueueWorkerRefused` when the application has no queue, or its queue uses\n * the memory driver.\n *\n * Refused rather than warned about, because a memory worker can never do\n * anything: its jobs live in a `Map` in the process that dispatched them,\n * so a worker's is always empty. Left running, it looks like a healthy\n * deploy — a process up, no errors — that runs nothing, and scaling it out\n * adds no capacity. An exit the platform reports as a crash loop is a form\n * of the mistake someone will see.\n */\n async start(): Promise<void> {\n await this.kernel.waitForBoot();\n // A signal during the boot has already drained and cleared the handle\n // below. Going on would start the loop again and arm a handle nothing\n // clears, holding open a worker that has finished shutting down.\n if (this.stopping) return;\n\n const application = this.kernel.app;\n // `bound`, not `make` in a try: an application built without the queue\n // provider is a configuration to name, not an unbound-token stack trace.\n if (!application.bound(QueueManager)) {\n throw new QueueWorkerRefused(\n \"[gemi] `gemi queue:work` has no queue to claim from: this application \" +\n \"does not register QueueServiceProvider.\",\n );\n }\n const queue = application.make(QueueManager);\n if (!queue.durable) {\n throw new QueueWorkerRefused(\n \"[gemi] `gemi queue:work` refuses to start: the queue uses the memory \" +\n \"driver, which keeps each job in the process that dispatched it, so \" +\n 'a worker never sees one. Set `driver: \"database\"` (or another driver ' +\n \"every process can reach) in app/config/queue.ts, or run jobs in the \" +\n \"server and drop the worker.\",\n );\n }\n\n // Idempotent: a production boot with a durable driver has already started\n // it (`startClaimingIfServing`). Development has not, and a worker claims\n // in either.\n queue.start();\n // The queue's poll timer is unref'd, so that a script's queue does not\n // hold it open; here the queue is the process, and without a handle of its\n // own an idle worker would exit 0 as soon as it booted.\n this.keepAlive = setInterval(() => {}, 1 << 30);\n console.log(\n `[gemi] Queue worker started: claiming up to ${queue.config.concurrency} job(s) at a time.`,\n );\n const broadcastWarning = memoryBroadcastInWorker(application);\n if (broadcastWarning) console.warn(broadcastWarning);\n }\n\n /**\n * Stops claiming, waits for the running jobs, runs every provider's\n * `shutdown()`, and resolves with the exit code: 0 when no job was left\n * running and every provider finished in time, 1 otherwise. Idempotent.\n *\n * `gemi start`'s drain, with the jobs where the requests were:\n * `isShuttingDown()` turns true, which stops a durable queue claiming;\n * running jobs get `timeoutMs` (`GEMI_SHUTDOWN_TIMEOUT`), which a server\n * spends on requests; then `Application.shutdown` gets `providerTimeoutMs`,\n * and in it the queue provider waits for whatever is still running and\n * names it. The two budgets add up as they do for a server, so a worker\n * fits the same grace period. `delayMs` is not waited: it is for a load\n * balancer, and nothing routes to a worker.\n */\n stop(settings: Partial<ShutdownSettings> = {}): Promise<number> {\n this.stopping ??= this.drain({ ...this.settings, ...settings });\n return this.stopping;\n }\n\n private async drain(settings: ShutdownSettings): Promise<number> {\n const deadline = Date.now() + settings.timeoutMs;\n markShuttingDown();\n const application = this.kernel.app;\n // Resolving the manager now would build a driver only to stop it, which\n // is what a signal during the boot, before the provider resolved it, finds.\n const queue = application.resolved(QueueManager) ? application.make(QueueManager) : undefined;\n if (queue) {\n console.log(\n `[gemi] Shutting down: waiting for ${queue.running} running job(s) ` +\n `(up to ${settings.timeoutMs / 1000}s).`,\n );\n await queue.drain(settings.timeoutMs);\n }\n // Work held with `holdShutdown` (#1210) gets what is left of the same budget.\n let held = heldWork() === 0;\n if (!held) {\n const remaining = deadline - Date.now();\n held =\n remaining > 0 &&\n (await Promise.race([\n heldWorkSettled().then(() => true),\n new Promise<false>((resolve) => setTimeout(() => resolve(false), remaining)),\n ]));\n if (!held) {\n console.error(\n `[gemi] Shutdown grace period elapsed with ${heldWork()} held background task(s) still running; abandoning them.`,\n );\n }\n }\n\n const report = await this.kernel.shutdown({ timeoutMs: settings.providerTimeoutMs });\n clearInterval(this.keepAlive);\n const clean =\n held && (queue?.running ?? 0) === 0 && report.failed.length === 0 && report.timedOut.length === 0;\n console.log(`[gemi] Shutdown ${clean ? \"complete\" : \"finished with errors\"}.`);\n return clean ? 0 : 1;\n }\n}\n"
|
|
8
8
|
],
|
|
9
9
|
"mappings": ";gdAYA,kBCDO,OAAS,DAAuB,DAAC,AAAyC,DAC/E,CAAI,DAAC,AAAY,KAAO,IAAI,gBAAgB,EAAG,OAAO,KACtD,IAAM,EAAS,EAAY,OAAO,IAAqB,YAAa,CAAC,CAAC,EAAE,OAGxE,GAAI,EADF,IAAW,QAAa,IAAW,UAAY,aAAkB,GACtD,OAAO,KACpB,MACE,uNCIG,MAAM,UAA2B,KAAM,CAC5C,KAAO,oBACT,CAYO,MAAM,CAAY,CAWJ,OAVX,SACA,UACS,SAOjB,WAAW,CACQ,EACjB,EAAsC,CAAC,EACvC,CAFiB,cAGjB,KAAK,SAAW,IAAK,EAAiB,KAAM,CAAS,OAejD,MAAK,EAAkB,CAK3B,GAJA,MAAM,KAAK,OAAO,YAAY,EAI1B,KAAK,SAAU,OAEnB,IAAM,EAAc,KAAK,OAAO,IAGhC,GAAI,CAAC,EAAY,MAAM,CAAY,EACjC,MAAM,IAAI,EACR,+GAEF,EAEF,IAAM,EAAQ,EAAY,KAAK,CAAY,EAC3C,GAAI,CAAC,EAAM,QACT,MAAM,IAAI,EACR,8SAKF,EAMF,EAAM,MAAM,EAIZ,KAAK,UAAY,YAAY,IAAM,GAAI,UAAO,EAC9C,QAAQ,IACN,+CAA+C,EAAM,OAAO,+BAC9D,EACA,IAAM,EAAmB,EAAwB,CAAW,EAC5D,GAAI,EAAkB,QAAQ,KAAK,CAAgB,EAiBrD,IAAI,CAAC,EAAsC,CAAC,EAAoB,CAE9D,OADA,KAAK,WAAa,KAAK,MAAM,IAAK,KAAK,YAAa,CAAS,CAAC,EACvD,KAAK,cAGA,MAAK,CAAC,EAA6C,CAC/D,IAAM,EAAW,KAAK,IAAI,EAAI,EAAS,UACvC,EAAiB,EACjB,IAAM,EAAc,KAAK,OAAO,IAG1B,EAAQ,EAAY,SAAS,CAAY,EAAI,EAAY,KAAK,CAAY,EAAI,OACpF,GAAI,EACF,QAAQ,IACN,qCAAqC,EAAM,iCAC/B,EAAS,UAAY,SACnC,EACA,MAAM,EAAM,MAAM,EAAS,SAAS,EAGtC,IAAI,EAAO,EAAS,IAAM,EAC1B,GAAI,CAAC,EAAM,CACT,IAAM,EAAY,EAAW,KAAK,IAAI,EAOtC,GANA,EACE,EAAY,GACX,MAAM,QAAQ,KAAK,CAClB,EAAgB,EAAE,KAAK,IAAM,EAAI,EACjC,IAAI,QAAe,CAAC,IAAY,WAAW,IAAM,EAAQ,EAAK,EAAG,CAAS,CAAC,CAC7E,CAAC,EACC,CAAC,EACH,QAAQ,MACN,6CAA6C,EAAS,2DACxD,EAIJ,IAAM,EAAS,MAAM,KAAK,OAAO,SAAS,CAAE,UAAW,EAAS,iBAAkB,CAAC,EACnF,cAAc,KAAK,SAAS,EAC5B,IAAM,EACJ,IAAS,GAAO,SAAW,KAAO,GAAK,EAAO,OAAO,SAAW,GAAK,EAAO,SAAS,SAAW,EAElG,OADA,QAAQ,IAAI,mBAAmB,EAAQ,WAAa,yBAAyB,EACtE,EAAQ,EAAI,EAEvB,CFjJA,eAAe,CAAI,EAAgC,CACjD,IAAM,EAAU,EAAY,EAI5B,QAAQ,IAAI,SAAW,EACvB,QAAQ,IAAI,QAAU,EAAK,KAAK,EAAS,KAAK,EAE9C,EAAgB,EAEhB,IAAM,EAAa,EAAK,KAAK,EAAS,sBAAsB,GACpD,QAAS,GAAY,MAAa,UAG1C,GAAI,OAAO,IAAW,WAEpB,OADA,QAAQ,MAAM,UAAU,kDAA2D,EAC5E,EAET,IAAM,EAAS,IAAI,EACnB,EAAO,KAAK,EAEZ,IAAM,EAAS,IAAI,EAAY,CAAM,EAKrC,EAAuB,IAAM,EAAO,KAAK,CAAC,EAE1C,GAAI,CACF,MAAM,EAAO,MAAM,EACnB,MAAO,EAAO,CACd,GAAI,EAAE,aAAiB,GAAqB,MAAM,EAElD,OADA,QAAQ,MAAM,EAAM,OAAO,EACpB,EAGT,OAGF,EAAK,EAAE,KACL,CAAC,IAAS,CACR,GAAI,IAAS,OAAW,QAAQ,KAAK,CAAI,GAE3C,CAAC,IAAU,CACT,QAAQ,MAAM,2CAA4C,CAAK,EAC/D,QAAQ,KAAK,CAAC,EAElB",
|
|
10
|
-
"debugId": "
|
|
10
|
+
"debugId": "E1831072F405A02364756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"../chunk-
|
|
2
|
+
import"../chunk-zf1eqgzt.js";import M from"path";import{writeFileSync as Q}from"fs";var L=new Set(["FILE","REDIRECT"]);function H(j){return j.run(()=>{let x=[];for(let{group:z,view:D}of j.domains().viewGroups())for(let[G,B]of Object.entries(D.flatViewRoutes)){let C=D.routeManifest[G]??B.segments.map((K)=>K.viewPath);if(C.length===0||L.has(C.at(-1)))continue;x.push({path:G,group:z,views:C,...B.static?{static:{...B.static.layout?{layout:B.static.layout}:{},...B.static.navigation?{navigation:!0}:{}}}:{}})}return x})}var J=process.argv[2];async function U(){if(!J)throw Error("usage: route-table <out.json>");let j=M.resolve(process.cwd(),"app/kernel/Kernel.ts"),x=await import(j);if(typeof x.default!=="function")throw Error(`${j} has no default export (the Kernel subclass).`);let z=new x.default;z.boot();try{Q(J,JSON.stringify(H(z)))}finally{z.destroy()}}U().then(()=>process.exit(0),(j)=>{console.error(j?.stack??String(j)),process.exit(1)});
|
|
3
3
|
|
|
4
4
|
//# debugId=05EB0087C5A2060D64756E2164756E21
|
package/dist/support/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Le as Y}from"../chunk-3830ee5d.js";import{Xk as M}from"../chunk-24tj4dzx.js";import{bm as P,dm as R}from"../chunk-vyaedzr8.js";import"../chunk-djnn8vvp.js";import{Am as W,xm as Q,ym as U,zm as V}from"../chunk-77dt2tap.js";import"../chunk-zf1eqgzt.js";class S{static token;async boot(){}onShutdown(x){}static inject(){if(!this.token)throw Error(`Service [${this.name}] does not declare a \`static token\`, so the container has no key to resolve it by.`);try{return R(this)}catch(x){throw Error(`Could not inject [${this.name}]. Services are constructed when the kernel boots, so `+"inject() only works from code that runs after that \u2014 a constructor default or a method "+`body, never module top level. Check that [${this.name}] is listed in \`services\` on your Kernel.`,{cause:x})}}static with(x){let f=new this;for(let[C,g]of Object.entries(x))if(g!==void 0)f[C]=g;return f}}import{readdir as z}from"fs/promises";import{join as B,parse as j}from"path";var H=[".ts",".tsx",".js",".mjs",".jsx"];function J(x={}){let f={};for(let[C,g]of Object.entries(x))f[C]=q(g);return new P(f)}async function L(x,f=new P){let C=[];try{C=await z(x)}catch(D){return f}let g=C.filter((D)=>{let{ext:v,name:F}=j(D);return H.includes(v)&&!F.startsWith(".")}).sort();for(let D of g){let{name:v}=j(D),F=await import(B(x,D));f.set(v,q(F))}return f}function q(x){if(x&&typeof x==="object"&&"default"in x)return x.default;return x}export{M as withDefaults,Q as sourceFiles,W as projectRoot,L as loadConfigFrom,V as discoverClasses,J as createConfigRepository,Y as ServiceProvider,S as Service,P as Repository,U as DiscoveryError};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=A14047831E087B7A64756E2164756E21
|
|
@@ -6,6 +6,6 @@
|
|
|
6
6
|
"import { readdir } from \"node:fs/promises\";\nimport { join, parse } from \"node:path\";\n\nimport { Repository } from \"./Repository\";\n\nconst CONFIG_EXTENSIONS = [\".ts\", \".tsx\", \".js\", \".mjs\", \".jsx\"];\n\n// Builds a Repository from an already-imported map of config modules. The map\n// key becomes the top-level config key, so `{ mail: mailModule }` is readable\n// as `config.get(\"mail.driver\")`. Each entry may be either the module namespace\n// (its `default` export is unwrapped) or the config object itself.\nexport function createConfigRepository(\n modules: Record<string, any> = {},\n): Repository {\n const items: Record<string, any> = {};\n\n for (const [key, mod] of Object.entries(modules)) {\n items[key] = unwrap(mod);\n }\n\n return new Repository(items);\n}\n\n// Reads every config module in an app's `app/config` directory into a\n// Repository. The file's basename is the top-level key: `app/config/mail.ts`\n// populates `mail.*`. A missing directory yields an empty Repository so apps\n// that declare no config still boot.\nexport async function loadConfigFrom(\n directory: string,\n repository = new Repository(),\n): Promise<Repository> {\n let entries: string[] = [];\n\n try {\n entries = await readdir(directory);\n } catch (err) {\n return repository;\n }\n\n const files = entries\n .filter((entry) => {\n const { ext, name } = parse(entry);\n return CONFIG_EXTENSIONS.includes(ext) && !name.startsWith(\".\");\n })\n .sort();\n\n for (const file of files) {\n const { name } = parse(file);\n const mod = await import(join(directory, file));\n repository.set(name, unwrap(mod));\n }\n\n return repository;\n}\n\nfunction unwrap(mod: any) {\n if (mod && typeof mod === \"object\" && \"default\" in mod) {\n return mod.default;\n }\n return mod;\n}\n"
|
|
7
7
|
],
|
|
8
8
|
"mappings": ";2RAiCO,CAAe,JAAQ,EAOrB,OAMD,AAAI,EAAkB,EAmB5B,UAAU,CAAC,EAEkD,QAmBtD,OAAS,EAKX,CACH,GAAI,CAAC,KAAK,MACR,MAAU,MACR,YAAY,KAAK,0FACnB,EAGF,GAAI,CACF,OAAO,EAAI,IAAuB,EAClC,MAAO,EAAO,CACd,MAAU,MACR,qBAAqB,KAAK,6DACxB,+FACA,6CAA6C,KAAK,kDAEpD,CAAE,OAAM,CACV,SAoBG,KAAuB,CAAoB,EAA0B,CAC1E,IAAM,EAAW,IAAI,KACrB,QAAY,EAAK,KAAU,OAAO,QAAQ,CAAS,EACjD,GAAI,IAAU,OAAW,EAAS,GAAO,EAE3C,OAAO,EAEX,CCtIA,kBAAS,oBACT,eAAS,WAAM,aAIf,IAAM,EAAoB,CAAC,MAAO,OAAQ,MAAO,OAAQ,MAAM,EAMxD,SAAS,CAAsB,CACpC,EAA+B,CAAC,EACpB,CACZ,IAAM,EAA6B,CAAC,EAEpC,QAAY,EAAK,KAAQ,OAAO,QAAQ,CAAO,EAC7C,EAAM,GAAO,EAAO,CAAG,EAGzB,OAAO,IAAI,EAAW,CAAK,EAO7B,eAAsB,CAAc,CAClC,EACA,EAAa,IAAI,EACI,CACrB,IAAI,EAAoB,CAAC,EAEzB,GAAI,CACF,EAAU,MAAM,EAAQ,CAAS,EACjC,MAAO,EAAK,CACZ,OAAO,EAGT,IAAM,EAAQ,EACX,OAAO,CAAC,IAAU,CACjB,IAAQ,MAAK,QAAS,EAAM,CAAK,EACjC,OAAO,EAAkB,SAAS,CAAG,GAAK,CAAC,EAAK,WAAW,GAAG,EAC/D,EACA,KAAK,EAER,QAAW,KAAQ,EAAO,CACxB,IAAQ,QAAS,EAAM,CAAI,EACrB,EAAM,MAAa,SAAK,EAAW,CAAI,GAC7C,EAAW,IAAI,EAAM,EAAO,CAAG,CAAC,EAGlC,OAAO,EAGT,SAAS,CAAM,CAAC,EAAU,CACxB,GAAI,GAAO,OAAO,IAAQ,UAAY,YAAa,EACjD,OAAO,EAAI,QAEb,OAAO",
|
|
9
|
-
"debugId": "
|
|
9
|
+
"debugId": "A14047831E087B7A64756E2164756E21",
|
|
10
10
|
"names": []
|
|
11
11
|
}
|
package/dist/vitest/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{ua as B,va as D}from"../chunk-4ksnhx8x.js";import"../chunk-m3v661b3.js";import"../chunk-zvk6dydb.js";import{Pa as J}from"../chunk-1tc6j8bn.js";import"../chunk-tx5zrdmb.js";import"../chunk-zf1eqgzt.js";function N(){return{name:"gemi-custom-request",enforce:"pre",async transform(G,H){let j=H.split("?",1)[0];if(j.includes("/node_modules/")||!B.test(j))return null;return{code:await D(G),map:null}}}}export{N as gemiRequestPlugin,J as gemiIslandPlugin};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=54630B516034F10064756E2164756E21
|
package/dist/vitest/index.js.map
CHANGED
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"import type { Plugin } from \"vite\";\nimport {\n CUSTOM_REQUEST_FILTER,\n customRequestParser,\n} from \"../bun/customRequestParser\";\n\n/**\n * The request-param rewrite, as a Vite plugin, for running an app's routes\n * under vitest.\n *\n * gemi calls a route handler and a controller method with no arguments, and a\n * handler written `async (req: HttpRequest<…>) => …` only gets its request\n * because the build rewrites it to `async (req = new HttpRequest()) => …`, which\n * reads the current request from the request context. The app's build and dev\n * server get that rewrite from `gemi/bun/plugin`. Vitest loads modules through\n * Vite instead, even under `bun --bun vitest`, so without this plugin a route\n * dispatched with `App.fetch` in a test sees `req === undefined`.\n *\n * Same transform, same files (`/http/controllers/` and `/http/routes/`) as the\n * Bun plugin. `enforce: \"pre\"` so it sees the TypeScript annotations before\n * Vite strips them.\n *\n * ```ts\n * // vitest.config.ts\n * import { defineConfig } from \"vitest/config\";\n * import { gemiRequestPlugin } from \"gemi/vitest\";\n *\n * export default defineConfig({ plugins: [gemiRequestPlugin()] });\n * ```\n */\nexport function gemiRequestPlugin(): Plugin {\n return {\n name: \"gemi-custom-request\",\n enforce: \"pre\",\n async transform(code, id) {\n const path = id.split(\"?\", 1)[0];\n if (path.includes(\"/node_modules/\") || !CUSTOM_REQUEST_FILTER.test(path)) {\n return null;\n }\n return { code: await customRequestParser(code), map: null };\n },\n };\n}\n\n/**\n * gemi's island transform, for an app's `vitest.config.ts`: with it, a test\n * that renders a static view through `App.fetch` sees each\n * `island(() => import(\"./Counter\"))` with the same module key as the build,\n * and a hydrated view renders the component in place instead of lazily.\n *\n * Without it islands still render (the component is loaded with the\n * `import()`), but their keys are unknown.\n *\n * ```ts\n * // vitest.config.ts\n * import { defineConfig } from \"vitest/config\";\n * import { gemiIslandPlugin, gemiRequestPlugin } from \"gemi/vitest\";\n *\n * export default defineConfig({ plugins: [gemiRequestPlugin(), gemiIslandPlugin()] });\n * ```\n */\nexport { gemiIslandPlugin } from \"../vite/islandPlugin\";\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";yOA8BO,IAAS,JAAiB,HAAW,JAC1C,CAAO,CACL,KAAM,sBACN,QAAS,WACH,UAAS,CAAC,EAAM,EAAI,CACxB,IAAM,EAAO,EAAG,MAAM,IAAK,CAAC,EAAE,GAC9B,GAAI,EAAK,SAAS,gBAAgB,GAAK,CAAC,EAAsB,KAAK,CAAI,EACrE,OAAO,KAET,MAAO,CAAE,KAAM,MAAM,EAAoB,CAAI,EAAG,IAAK,IAAK,EAE9D",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "54630B516034F10064756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
package/package.json
CHANGED
package/dist/chunk-1x60thpm.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Kd as YJ,Qd as S,Rd as f,Sd as AJ,Td as RJ,Ud as TJ,Vd as T,Wd as D,ud as kJ,wd as m}from"./chunk-xwqdh388.js";import{Rj as PJ}from"./chunk-6g1xac70.js";var cJ=500,BJ=20000;function mJ(J,Q){if(!J)return;let $=J.trim();if(/^\d+(\.\d+)?$/.test($))return Math.max(0,Number($)*1000);let Z=Date.parse($);if(Number.isNaN(Z))return;return Math.max(0,Z-Q)}function g(J,Q){let $=Math.min(BJ,cJ*2**J);return Math.round($*(0.5+Q()*0.5))}function dJ(J){return J===429||J===408||J===409||J>=500}function pJ(J,Q){return dJ(J)&&D(Q).retryable}function VJ(J){return J.reason??new DOMException("The operation was aborted.","AbortError")}function UJ(J,Q){return new Promise(($,Z)=>{let G=setTimeout($,J);Q?.addEventListener("abort",()=>{clearTimeout(G),Z(VJ(Q))},{once:!0})})}async function p(J,Q,$=UJ){if(!Q)return await $(J);Q.throwIfAborted();let Z;try{await Promise.race([$(J,Q),new Promise((G,K)=>{Z=()=>K(VJ(Q)),Q.addEventListener("abort",Z,{once:!0})})])}finally{if(Z)Q.removeEventListener("abort",Z)}}async function h(J,Q,$){let Z=$.fetchImpl??((j,W)=>fetch(j,W)),G=$.sleep??UJ,K=$.random??Math.random,X=$.now??Date.now,H=Math.max(0,$.maxRetries),B=$.startedAt??X(),Y=(j,W,V,q)=>{try{$.onRetry?.({attempt:W+1,maxRetries:H,error:D(V),...T(V),timedOut:q,delayMs:j,elapsedMs:X()-B})}catch{}return p(j,$.signal,G)},U;for(let j=0;j<=H;j++){$.signal?.throwIfAborted();let W=new AbortController,V=()=>W.abort($.signal?.reason);$.signal?.addEventListener("abort",V,{once:!0});let q=!1,z=$.timeoutMs>0?setTimeout(()=>{q=!0,W.abort()},$.timeoutMs):void 0,L;try{L=await Z(J,{...Q,signal:W.signal})}catch(M){if(z!==void 0)clearTimeout(z);if($.signal?.removeEventListener("abort",V),$.signal?.aborted)throw M;if(U=q?new f($.timeoutMs):M,q&&$.retryTimeouts===!1)throw U;if(j===H)throw U;await Y(g(j,K),j,U,q);continue}if(z!==void 0)clearTimeout(z);if(L.ok)return L;$.signal?.removeEventListener("abort",V);let N=await lJ(L),_=new S(L.status,N,L.headers.get("x-request-id")??void 0,mJ(L.headers.get("retry-after"),X()));if(j===H||!pJ(L.status,_))throw _;let A=_.retryAfter??(L.status===429?D(_).retryAfter:void 0);await Y(A===void 0?g(j,K):Math.min(A,BJ),j,_,!1),U=_}throw U??Error("Provider request failed with no response.")}async function lJ(J){let Q;try{Q=await J.text()}catch{return null}try{return JSON.parse(Q)}catch{return Q}}function jJ(J,Q,$){let Z=Q.idleMs>0?Q.idleMs:0,G=Q.maxMs>0?Q.maxMs:0;if(!J||!Z&&!G)return J;let K=G?performance.now()+G:1/0,X=J.getReader();return new ReadableStream({async pull(H){let B,Y,U=Math.max(0,K-performance.now()),j=!Z||U<=Z,W=j?U:Z,V=new Promise((q,z)=>{B=setTimeout(()=>{Y=j?$.max():$.idle(),z(Y)},W)});try{let q=await Promise.race([X.read(),V]);if(q.done)H.close();else H.enqueue(q.value)}catch(q){let z=Y??q;H.error(z),X.cancel(z).catch(()=>{})}finally{clearTimeout(B)}},cancel(H){return X.cancel(H)}},{highWaterMark:0})}var i=30000,FJ=10,qJ=7200,iJ=600,nJ="gpt-live-transcribe";function rJ(J){return J.type==="transcription"}function aJ(J){if(J.language!==void 0&&J.languages!==void 0)throw TypeError("A transcription session takes `languages` or `language`, not both (gpt-live-transcribe reads `languages`).");for(let G of J.keywords??[])if(/[<>\r\n]/.test(G))throw TypeError(`Transcription keywords must be one line without "<" or ">", got ${JSON.stringify(G)}.`);let Q={model:J.model??nJ};if(J.prompt!==void 0)Q.prompt=J.prompt;if(J.keywords?.length)Q.keywords=J.keywords;if(J.languages?.length)Q.languages=J.languages;if(J.language!==void 0)Q.language=J.language;if(J.delay!==void 0)Q.delay=J.delay;let $={transcription:Q,turn_detection:J.turnDetection?zJ(J.turnDetection):null};if(J.noiseReduction!==void 0)$.noise_reduction=J.noiseReduction&&{type:J.noiseReduction};let Z={type:"transcription",audio:{input:$}};if(J.logprobs)Z.include=["item.input_audio_transcription.logprobs"];return{...Z,...J.vendor}}function oJ(J){if(!J)return{type:"object",properties:{}};return PJ(J)?J.toJSONSchema():J}function u(J,Q){if(rJ(J))return aJ(J);let $={type:"realtime"},Z=J.model??Q;if(Z)$.model=Z;if(J.instructions!==void 0)$.instructions=J.instructions;if(J.outputModalities)$.output_modalities=J.outputModalities;if(J.maxOutputTokens!==void 0)$.max_output_tokens=J.maxOutputTokens;if(J.truncation!==void 0)$.truncation=J.truncation;if(J.tools)$.tools=J.tools.map((X)=>({type:"function",name:X.name,...X.description?{description:X.description}:{},parameters:oJ(X.parameters)}));if(J.toolChoice!==void 0)$.tool_choice=typeof J.toolChoice==="string"?J.toolChoice:{type:"function",name:J.toolChoice.name};let G={};if(J.turnDetection!==void 0)G.turn_detection=J.turnDetection&&zJ(J.turnDetection);if(J.transcription!==void 0)G.transcription=J.transcription;if(J.noiseReduction!==void 0)G.noise_reduction=J.noiseReduction&&{type:J.noiseReduction};let K={};if(J.voice!==void 0)K.voice=J.voice;if(J.speed!==void 0)K.speed=J.speed;if(Object.keys(G).length||Object.keys(K).length)$.audio={...Object.keys(G).length?{input:G}:{},...Object.keys(K).length?{output:K}:{}};return{...$,...J.vendor}}function zJ(J){let Q={type:J.type};if(J.createResponse!==void 0)Q.create_response=J.createResponse;if(J.interruptResponse!==void 0)Q.interrupt_response=J.interruptResponse;if(J.type==="semantic_vad"){if(J.eagerness!==void 0)Q.eagerness=J.eagerness}else{if(J.threshold!==void 0)Q.threshold=J.threshold;if(J.prefixPaddingMs!==void 0)Q.prefix_padding_ms=J.prefixPaddingMs;if(J.silenceDurationMs!==void 0)Q.silence_duration_ms=J.silenceDurationMs;if(J.idleTimeoutMs!==void 0)Q.idle_timeout_ms=J.idleTimeoutMs}return Q}function n(J){let Q=Number(J?.input_tokens??0),$=Number(J?.output_tokens??0),Z={inputTokens:Q,outputTokens:$,totalTokens:Number(J?.total_tokens??Q+$)},G=J?.input_token_details??J?.input_tokens_details,K=J?.output_token_details??J?.output_tokens_details;if(typeof G?.cached_tokens==="number")Z.cachedInputTokens=G.cached_tokens;if(typeof G?.audio_tokens==="number")Z.audioInputTokens=G.audio_tokens;let X=G?.cached_tokens_details?.audio_tokens;if(typeof X==="number")Z.cachedAudioInputTokens=X;if(typeof G?.image_tokens==="number"&&G.image_tokens>0)Z.imageInputTokens=G.image_tokens;if(typeof K?.audio_tokens==="number")Z.audioOutputTokens=K.audio_tokens;return Z}class v extends Error{code;retryable;status;constructor(J,Q={}){super(J.message,{cause:Q.cause});if(this.name="RealtimeRequestError",this.code=J.code,this.retryable=J.retryable,Q.status!==void 0)this.status=Q.status}}var sJ=60;class c{model;target;options;constructor(J,Q){this.target=J,this.options=Q,this.model=Q.model}url(J){return`${this.target.base}/realtime${J}${this.target.query}`}sidebandUrl(J){let Q=this.target.base.replace(/^http(s?):/i,(Z,G)=>`ws${G}:`),$=this.target.query?`${this.target.query}&`:"?";return`${Q}/realtime${$}call_id=${encodeURIComponent(J)}`}async createCall(J){let Q=J.flow??this.options.callFlow??"unified",$,Z;if(Q==="ephemeral")$={authorization:`Bearer ${(await this.clientSecret({session:J.session,ttlSeconds:sJ,signal:J.signal})).value}`,"content-type":"application/sdp"},Z=J.sdp;else{let B=new FormData;B.set("sdp",J.sdp),B.set("session",JSON.stringify(u(J.session??{},this.model))),$=await this.target.headers(),Z=B}if(J.safetyIdentifier)$["OpenAI-Safety-Identifier"]=J.safetyIdentifier;let G=this.url("/calls"),K=await this.request(J.webrtcFilter?`${G}${G.includes("?")?"&":"?"}webrtcfilter=on`:G,{method:"POST",headers:$,body:Z},J.signal),X=await K.text(),H=eJ(K);if(!H)throw new v({code:"provider_error",message:"The provider started a realtime call but did not say which one (no Location).",retryable:!1});return{sdpAnswer:X,callId:H}}async clientSecret(J={}){let Q=J.ttlSeconds??iJ;if(!Number.isInteger(Q)||Q<FJ||Q>qJ)throw RangeError(`ttlSeconds must be a whole number from ${FJ} to ${qJ}, got ${Q}.`);let $={...await this.target.headers(),"content-type":"application/json"};if(J.safetyIdentifier)$["OpenAI-Safety-Identifier"]=J.safetyIdentifier;let G=await(await this.request(this.url("/client_secrets"),{method:"POST",headers:$,body:JSON.stringify({expires_after:{anchor:"created_at",seconds:Q},session:u(J.session??{},this.model)})},J.signal)).json();if(typeof G?.value!=="string")throw new v({code:"provider_error",message:"The provider answered a client secret request with no secret.",retryable:!1});return{value:G.value,expiresAt:Number(G.expires_at??0),session:G.session,callsUrl:this.url("/calls")}}async hangup(J,Q={}){try{await this.request(this.url(`/calls/${encodeURIComponent(J)}/hangup`),{method:"POST",headers:await this.target.headers()},Q.signal)}catch($){if(tJ($,J))return;throw $}}sideband(J,Q={}){return new l({...Q,callId:J,url:this.sidebandUrl(J),headers:this.target.headers,webSocket:Q.webSocket??this.options.webSocket,hangup:()=>this.hangup(J)})}async request(J,Q,$){try{return await h(J,Q,{maxRetries:this.target.maxRetries,timeoutMs:this.target.timeoutMs,retryTimeouts:!1,signal:$,fetchImpl:this.options.fetchImpl})}catch(Z){if($?.aborted)throw Z;throw new v(D(Z),{cause:Z,...Z instanceof S?{status:Z.status}:{}})}}}function tJ(J,Q){if(!(J instanceof v)||J.status!==404)return!1;let $=J.cause instanceof S?J.cause.body:void 0,Z=$?.error??$,G=String(Z?.code??"").toLowerCase(),K=String(Z?.message??"").toLowerCase();if(G.includes("call"))return!0;if(K.includes(Q.toLowerCase()))return!0;return/\bcall\b/.test(K)&&/not (be )?found|does not exist|no longer|ended/.test(K)}function eJ(J){let Q=J.headers.get("location");if(!Q)return;let $=Q.split("?")[0].replace(/\/+$/,""),Z=$.slice($.lastIndexOf("/")+1);return Z?decodeURIComponent(Z):void 0}var JQ={"response.audio_transcript.delta":"response.output_audio_transcript.delta","response.audio_transcript.done":"response.output_audio_transcript.done","response.text.delta":"response.output_text.delta","response.text.done":"response.output_text.done","response.audio.delta":"response.output_audio.delta","response.audio.done":"response.output_audio.done"};function QQ(J){if(typeof J!=="string")return;let Q;try{Q=JSON.parse(J)}catch{return}if(!Q||typeof Q!=="object"||typeof Q.type!=="string")return;let $=JQ[Q.type];if($)Q.type=$;if(Q.type==="response.done"&&Q.response?.usage)Q.usage=n(Q.response.usage);if(Q.type==="conversation.item.input_audio_transcription.completed"&&Q.usage)if(Q.usage.type==="duration"){let Z=Number(Q.usage.seconds);if(Number.isFinite(Z))Q.transcriptionSeconds=Z}else Q.transcriptionUsage=n(Q.usage);return Q}var LJ=1,$Q=500;function ZQ(J,Q){let $=globalThis.WebSocket;if(!$)throw Error("No global WebSocket: the realtime sideband needs Bun or Node 22+.");return new $(J,{headers:Q.headers})}class l{callId;ready;closed;init;socket;finalEvent;outbox=[];subscribers=new Set;listeners=new Set;backlog=[];closing=!1;finished=!1;everOpened=!1;failures=0;resolveReady;rejectReady;resolveClosed;constructor(J){this.init=J,this.callId=J.callId,this.ready=new Promise((Q,$)=>{this.resolveReady=Q,this.rejectReady=$}),this.ready.catch(()=>{}),this.closed=new Promise((Q)=>this.resolveClosed=Q),this.open()}send(J){if(this.finished||this.closing)return;let Q=JSON.stringify(J);if(this.socket?.readyState===LJ)this.socket.send(Q);else this.outbox.push(Q)}updateSession(J){this.send({type:"session.update",session:u(J)})}addItem(J){this.send({type:"conversation.item.create",item:J})}addNote(J){this.addItem({type:"message",role:"system",content:[{type:"input_text",text:J}]})}functionOutput(J,Q){this.addItem({type:"function_call_output",call_id:J,output:typeof Q==="string"?Q:JSON.stringify(Q)})}createResponse(J={}){let Q={};if(J.instructions!==void 0)Q.instructions=J.instructions;if(J.toolChoice!==void 0)Q.tool_choice=typeof J.toolChoice==="string"?J.toolChoice:{type:"function",name:J.toolChoice.name};if(J.outputModalities)Q.output_modalities=J.outputModalities;if(J.conversation)Q.conversation=J.conversation;if(J.metadata)Q.metadata=J.metadata;Object.assign(Q,J.vendor),this.send(Object.keys(Q).length?{type:"response.create",response:Q}:{type:"response.create"})}cancelResponse(J){this.send(J?{type:"response.cancel",response_id:J}:{type:"response.cancel"})}on(J){return this.listeners.add(J),()=>this.listeners.delete(J)}[Symbol.asyncIterator](){let J={queue:this.backlog??[],done:this.finished};return this.backlog=void 0,this.subscribers.add(J),{next:async()=>{for(;;){let $=J.queue.shift();if($)return{value:$,done:!1};if(J.done)return this.subscribers.delete(J),{value:void 0,done:!0};await new Promise((Z)=>J.wake=Z),J.wake=void 0}},return:async()=>{return J.done=!0,J.queue.length=0,this.subscribers.delete(J),{value:void 0,done:!0}}}}close(J=1000,Q="closed"){if(this.finished||this.closing)return;if(this.closing=!0,this.socket&&this.socket.readyState<=LJ)this.socket.close(J,Q);else this.finish(J,Q,!0)}async hangup(){try{await this.init.hangup()}catch(J){if(this.finalEvent&&!this.finalEvent.byClient&&this.finalEvent.code===1000)return;throw J}this.close(1000,"hangup")}async open(){let J;try{let $=await this.init.headers();if(this.closing)return this.finish(1000,"closed",!0);J=(this.init.webSocket??ZQ)(this.init.url,{headers:$})}catch($){return this.dropped(1006,$ instanceof Error?$.message:String($),!1)}this.socket=J;let Q=!1;J.addEventListener("open",()=>{Q=!0;let $=this.everOpened;this.everOpened=!0;let Z=this.failures;this.failures=0;for(let G of this.outbox.splice(0))J.send(G);if(this.resolveReady(),$)this.emit({type:"sideband.reconnected",attempt:Z})}),J.addEventListener("message",($)=>{let Z=QQ($.data);if(Z)this.emit(Z)}),J.addEventListener("close",($)=>{if(this.socket!==J)return;this.dropped($.code??1006,$.reason??"",Q)}),J.addEventListener("error",()=>{})}dropped(J,Q,$){if(this.socket=void 0,this.closing)return this.finish(J,Q,!0);let Z=this.init.reconnect?.attempts??3;if(!((J!==1000||!$)&&this.failures<Z))return this.finish(J,Q,!1);this.failures+=1;let K=(this.init.reconnect?.delayMs??500)*2**(this.failures-1);setTimeout(()=>void this.open(),K)}finish(J,Q,$){if(this.finished)return;this.finished=!0,this.outbox.length=0;let Z={type:"sideband.closed",code:J,reason:Q,byClient:$};this.finalEvent=Z,this.emit(Z);for(let G of this.subscribers)G.done=!0,G.wake?.();if(!this.everOpened)this.rejectReady(Error(`Realtime sideband did not open (${J} ${Q}).`));this.resolveClosed(Z)}emit(J){if(this.backlog){if(this.backlog.push(J),this.backlog.length>$Q)this.backlog.shift()}for(let Q of this.subscribers){if(Q.done)continue;Q.queue.push(J),Q.wake?.()}for(let Q of this.listeners)try{Q(J)}catch{}}}var NJ=3;function r(J){let Q=new Map;for(let $ of J)for(let Z of $.content??[]){if(Z.type!=="file"||!Z.fileId||Q.has(Z.fileId))continue;Q.set(Z.fileId,{name:Z.name,mimeType:Z.mimeType})}return Q}function CJ(J,Q,$=new Map){if(!(Q instanceof S))return[];if(Q.status!==400&&Q.status!==404)return[];let Z=KQ(Q.body);if(!Z)return[];let G=GQ(J.input);if(G.length===0)return[];let K=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(K){let Y=J.input[Number(K[1])],U=o(Y)[Number(K[2])],j=U&&typeof U.file_id==="string"?U.file_id:void 0;if(j)return[j]}let X=Z.message??"",H=DJ(G.map((Y)=>Y.fileId).filter((Y)=>YQ(X,Y)));if(H.length>0)return H;let B=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(X);if(B){let Y=B[1].toLowerCase()==="image type"?"input_image":"input_file",U=B[2].toLowerCase(),j=DJ(G.filter((V)=>V.type===Y).map((V)=>V.fileId)),W=j.filter((V)=>($.get(V)?.name??"").trim().toLowerCase().endsWith(`.${U}`));if(W.length===1)return W;if(W.length===0&&j.length===1)return j}return[]}function _J(J,Q,$=new Map){return{...J,input:J.input.map((Z)=>{let G=o(Z);if(!G.some((K)=>xJ(K,Q)))return Z;return{...Z,content:G.map((K)=>xJ(K,Q)?{type:"input_text",text:a($.get(String(K.file_id))?.name)}:K)}})}}function a(J){return`[${J?`attachment ${JSON.stringify(J)}`:"an attachment"} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`}function xJ(J,Q){return typeof J.file_id==="string"&&Q.has(J.file_id)}function o(J){let Q=J?.content;return Array.isArray(Q)?Q:[]}function GQ(J){let Q=[];for(let $ of J)for(let Z of o($))if(typeof Z.file_id==="string"&&Z.file_id)Q.push({type:String(Z.type),fileId:Z.file_id});return Q}function KQ(J){if(!J||typeof J!=="object")return null;let Q=J,$=Q.error&&typeof Q.error==="object"?Q.error:J;return{message:typeof $.message==="string"?$.message:void 0,param:typeof $.param==="string"?$.param:void 0}}function YQ(J,Q){let $=Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${$}($|[^A-Za-z0-9_-])`).test(J)}function DJ(J){return[...new Set(J)]}async function*WQ(J){let Q="",$="",Z=[],G,K=()=>{if(Z.length===0&&!$)return null;let B={event:$,data:Z.join(`
|
|
3
|
-
`),id:G};return $="",Z=[],G=void 0,B.data?B:null},X=(B)=>{let Y=B.endsWith("\r")?B.slice(0,-1):B;if(Y==="")return K();if(Y.startsWith(":"))return null;let U=Y.indexOf(":"),j=U===-1?Y:Y.slice(0,U),W=U===-1?"":Y.slice(U+1);if(W.startsWith(" "))W=W.slice(1);if(j==="event")$=W;else if(j==="data")Z.push(W);else if(j==="id")G=W;return null};for await(let B of J){Q+=B;let Y=Q.indexOf(`
|
|
4
|
-
`);while(Y!==-1){let U=Q.slice(0,Y);Q=Q.slice(Y+1);let j=X(U);if(j)yield j;Y=Q.indexOf(`
|
|
5
|
-
`)}}if(Q.length>0){let B=X(Q);if(B)yield B}let H=K();if(H)yield H}async function*MJ(J,Q={}){let $=new Map,Z=new Set,G,K=!1,X,H=(B,Y)=>({type:"finish",reason:B,usage:Y,...X?{model:X}:{}});for await(let B of WQ(J)){if(B.data==="[DONE]")break;let Y;try{Y=JSON.parse(B.data)}catch{continue}let U=typeof Y.type==="string"?Y.type:B.event,j=Y.response?.model;if(typeof j==="string"&&j)X=j;switch(U){case"response.output_text.delta":{let W=String(Y.delta??"");if(!W)break;yield Q.structuredOutput?{type:"output-delta",delta:W}:{type:"text-delta",delta:W};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let W=String(Y.delta??"");if(!W)break;yield{type:"reasoning-delta",delta:W,id:Y.item_id};break}case"response.output_item.added":{let W=Y.item;if(!W)break;if(W.type==="function_call"){let V=String(W.id??Y.item_id??W.call_id??"");$.set(V,{callId:String(W.call_id??V),name:String(W.name??""),namespace:typeof W.namespace==="string"&&W.namespace?W.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let W=$.get(String(Y.item_id??""));if(!W)break;let V=String(Y.delta??"");if(!V)break;yield{type:"tool-call-delta",toolCallId:W.callId,name:W.name,argsDelta:V,...W.namespace?{namespace:W.namespace}:{}};break}case"response.function_call_arguments.done":{let W=String(Y.item_id??""),V=$.get(W);if(!V)break;V.done=!0,yield{type:"tool-call",toolCallId:V.callId,name:V.name,args:String(Y.arguments??""),...V.namespace?{namespace:V.namespace}:{}};break}case"response.output_item.done":{let W=Y.item;if(!W)break;if(W.type==="function_call"){let V=String(W.id??Y.item_id??W.call_id??""),q=$.get(V);if(q?.done)break;let z=(typeof W.namespace==="string"?W.namespace:"")||q?.namespace;if(yield{type:"tool-call",toolCallId:String(W.call_id??V),name:String(W.name??q?.name??""),args:String(W.arguments??""),...z?{namespace:z}:{}},q)q.done=!0;break}if(W.type==="tool_search_call"||W.type==="tool_search_output"){if(W.type==="tool_search_call"&&W.arguments!==void 0)G=W.arguments;let V=XQ(W);if(V.loaded.length===0&&V.namespaces.length===0)break;let q=String(W.tool_search_call_id??W.id??"");if(Z.has(q))break;Z.add(q);let z=G;G=void 0,yield{type:"tool-search",...V,...z!==void 0&&z!==null?{arguments:z}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(Y.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{K=!0,yield H("stop",s(Y.response?.usage));break}case"response.incomplete":{K=!0;let W=s(Y.response?.usage),V=Y.response?.incomplete_details?.reason;if(V==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:HQ(Y.response?.content_filters),retryable:!1}},yield H("error",W);break}yield H(V==="max_output_tokens"?"length":"stop",W);break}case"response.failed":case"error":{K=!0;let W=Y.response?.error??Y.error??Y;yield{type:"error",error:BQ(W)},yield H("error",s(Y.response?.usage));break}}if(K)return}if(!K)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield H("error",C())}function XQ(J){let Q=[],$=[];return OJ(J.results??J.tools??J.loaded??J.output,Q,$,0),{loaded:t(Q),namespaces:t($)}}function OJ(J,Q,$,Z){if(!Array.isArray(J)||Z>4)return;for(let G of J){if(typeof G==="string"){Q.push(G);continue}if(!G||typeof G!=="object")continue;let K=G,X=typeof K.name==="string"?K.name:typeof K.tool_name==="string"?K.tool_name:"",H=K.tools??K.functions;if(Array.isArray(H)){if(X)$.push(X);OJ(H,Q,$,Z+1);continue}if(X)Q.push(X)}}function t(J){return J.filter((Q,$)=>J.indexOf(Q)===$)}function HQ(J){if(!Array.isArray(J))return"The provider's content filter blocked this request.";let $=[];for(let Z of J){if(!Z||typeof Z!=="object")continue;let G=Z,K=G.content_filter_results;if(!K||typeof K!=="object")continue;for(let[X,H]of Object.entries(K))if(H&&typeof H==="object"&&H.filtered===!0)$.push(`${X} (${String(G.source_type??"unknown")})`)}return $.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${t($).join(", ")}.`}function BQ(J){let Q=typeof J?.message==="string"?J.message:"The provider stream failed.",$=String(J?.code??"").toLowerCase();if($==="rate_limit_exceeded")return{code:"rate_limited",message:Q,retryable:!0};if($==="context_length_exceeded")return{code:"context_length_exceeded",message:Q,retryable:!1};if($.includes("content_filter"))return{code:"content_filtered",message:Q,retryable:!1};return{code:"provider_error",message:Q,retryable:!0}}function C(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function s(J){if(!J)return C();let Q=Number(J.input_tokens??0),$=Number(J.output_tokens??0),Z={inputTokens:Q,outputTokens:$,totalTokens:Number(J.total_tokens??Q+$)},G=J.output_tokens_details?.reasoning_tokens;if(typeof G==="number")Z.reasoningTokens=G;let K=J.input_tokens_details?.cached_tokens;if(typeof K==="number")Z.cachedInputTokens=K;return Z}async function*SJ(J){if(!J)return;let Q=J.getReader(),$=new TextDecoder;try{while(!0){let{done:G,value:K}=await Q.read();if(G)break;if(K)yield $.decode(K,{stream:!0})}let Z=$.decode();if(Z)yield Z}finally{Q.releaseLock()}}function e(J){return{responsesUrl:`${J.base}/responses${J.query}`,filesUrl:`${J.base}/files${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,streamIdleTimeoutMs:J.streamIdleTimeoutMs,streamMaxDurationMs:J.streamMaxDurationMs,maxToolArgumentChars:J.maxToolArgumentChars,maxRetries:J.maxRetries}}async function*JJ(J,Q,$){let Z=Q,G=new Set,K=0,X=Math.max(0,J.maxRetries),H=J.random??Math.random,B,Y=(L)=>{if(!B)return L;let N=m(m(C(),B),L.usage);return B=void 0,{...L,usage:N}},U=()=>Y({type:"finish",reason:"aborted",usage:C()}),j=J.streamIdleTimeoutMs??0,W=J.streamMaxDurationMs??0,V=J.maxToolArgumentChars??0,q=J.now??Date.now,z=q();for(let L=0;;L++){let N=new AbortController,_=$.signal?AbortSignal.any([$.signal,N.signal]):N.signal,A;while(A===void 0)try{let P=[],F=()=>{},x=h(J.responsesUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify(Z)},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,signal:_,fetchImpl:J.fetchImpl,sleep:J.sleep,random:J.random,now:J.now,startedAt:z,onRetry:(R)=>{P.push({type:"retry",...R,phase:"request"}),F()}}),O=x.then(()=>!0,()=>!0);for(;;){let R=new Promise((uJ)=>F=()=>uJ(!1)),fJ=await Promise.race([O,R]);if(yield*P.splice(0),fJ)break}A=await x}catch(P){let F=K<NJ?CJ(Z,P,$.files).filter((O)=>!G.has(O)):[];if(F.length>0){K++;let O=D(P).message;for(let R of F)G.add(R),yield{type:"file-rejected",fileId:R,message:O,...T(P)};Z=_J(Z,new Set(F),$.files);continue}let x=D(P);if(x.code==="aborted"){yield U();return}yield{type:"error",error:x,...T(P)},yield Y({type:"finish",reason:"error",usage:C()});return}let M=[],b=!1,y,HJ=!1,w=new Map;try{let P=jJ(A.body,{idleMs:j,maxMs:W},{idle:()=>{let F=new AJ(j);return N.abort(F),F},max:()=>{let F=new RJ(W);return N.abort(F),F}});for await(let F of MJ(SJ(P),{structuredOutput:$.structuredOutput})){if(F.type==="tool-call-delta"){let x=(w.get(F.toolCallId)??0)+F.argsDelta.length;if(w.set(F.toolCallId,x),V>0&&x>V){let O=new TJ(V,F.name);throw N.abort(O),O}yield F;continue}if(F.type==="tool-call")w.delete(F.toolCallId);if(b){yield F.type==="finish"?Y(F):F;continue}if(kJ(F)){b=!0,yield*M.splice(0),yield F;continue}if(F.type==="error")y=F.error;M.push(F)}}catch(P){HJ=P instanceof f;let F=D(P);if(F.code==="aborted"||$.signal?.aborted){yield U();return}if(b){yield{type:"error",error:F},yield Y({type:"finish",reason:"error",usage:C()});return}y=F,M.push({type:"error",error:F},{type:"finish",reason:"error",usage:C()})}if(b)return;if(y?.retryable&&L<X&&!$.signal?.aborted){let P={};for(let x of M){if(x.type==="finish")B=m(B??C(),x.usage);if(x.type==="error")P=T(x)}if(w.size>0)yield{type:"tool-call-discard",toolCallIds:[...w.keys()]};let F=g(L,H);yield{type:"retry",attempt:L+1,maxRetries:X,error:y,...P,phase:"stream",timedOut:HJ,delayMs:F,elapsedMs:q()-z};try{await p(F,$.signal,J.sleep)}catch{yield U();return}continue}for(let P of M)yield P.type==="finish"?Y(P):P;return}}async function QJ(J,Q,$="user_data"){let Z=new FormData;Z.set("purpose",$),Z.set("file",Q);let K=await(await h(J.filesUrl,{method:"POST",headers:await J.headers(),body:Z},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,fetchImpl:J.fetchImpl})).json();if(!K?.id)throw Error("The provider accepted the upload but returned no file id.");return K.id}function $J(J){let Q=VQ(J);if(Q.startsWith("gpt-3.5")||Q.startsWith("text-")||Q.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let $=UQ(Q);if($?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:$.major>1,toolSearch:IJ($)};if($?.kind==="gpt")return{reasoning:$.major>=5,structuredOutput:$.major>4||Q.startsWith("gpt-4o")||Q.startsWith("gpt-4.1"),fileInput:$.major>4||Q.startsWith("gpt-4o")||Q.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:IJ($)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function IJ(J){if(J.kind==="o")return J.major>=5;return J.major>5||J.major===5&&J.minor>=2}function VQ(J){return J.trim().toLowerCase()}function UQ(J){let Q=/^gpt-(\d+)(?:\.(\d+))?/.exec(J);if(Q?.[1])return{kind:"gpt",major:Number(Q[1]),minor:Number(Q[2]??0)};let $=/^o(\d+)(?:[-.]|$)/.exec(J);if($?.[1])return{kind:"o",major:Number($[1]),minor:0};return null}function k(J){return typeof process>"u"?void 0:process.env?.[J]}var jQ="preview";function EJ(J){let Q=J.trim().replace(/\/+$/,"");if(!Q)return"";return`${Q.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function FQ(J){return/^\d{4}-\d{2}-\d{2}/.test(J)?"":"/v1"}function ZJ(J,Q={}){return{base:(J.baseURL??k("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=J.apiKey??k("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...J.headers}},timeoutMs:J.timeoutMs??Q.timeoutMs??120000,streamIdleTimeoutMs:J.streamIdleTimeoutMs??120000,streamMaxDurationMs:J.streamMaxDurationMs??300000,maxToolArgumentChars:J.maxToolArgumentChars??0,maxRetries:J.maxRetries??2}}function wJ(J){let Q=J.baseURL??J.endpoint??k("AZURE_OPENAI_ENDPOINT");if(Q)return EJ(Q);let $=J.resourceName??k("AZURE_OPENAI_RESOURCE_NAME")??k("AZURE_RESOURCE_NAME");return $?EJ(`https://${$.trim()}.cognitiveservices.azure.com`):""}function GJ(J,Q={}){let $=J.apiVersion??k("AZURE_OPENAI_API_VERSION")??jQ;return{base:`${wJ(J)}${FQ($)}`,query:`?api-version=${encodeURIComponent($)}`,headers:async()=>{if(J.getToken)return{authorization:`Bearer ${await J.getToken()}`,...J.headers};let Z=J.apiKey??k("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...J.headers}},timeoutMs:J.timeoutMs??Q.timeoutMs??120000,streamIdleTimeoutMs:J.streamIdleTimeoutMs??120000,streamMaxDurationMs:J.streamMaxDurationMs??300000,maxToolArgumentChars:J.maxToolArgumentChars??0,maxRetries:J.maxRetries??2}}function hJ(J,Q={}){return{...GJ(J,Q),base:`${wJ(J)}/v1`,query:""}}function WJ(J,Q){let{capabilities:$}=Q,Z={model:Q.model,input:qQ(J.messages,$,J.tools),stream:!0};if(J.systemPrompt)Z.instructions=J.systemPrompt;let G=OQ(J.tools,$);if(G.length>0){if(Z.tools=G,!$.parallelToolCalls)Z.parallel_tool_calls=!1;if(J.toolChoice!==void 0)Z.tool_choice=typeof J.toolChoice==="string"?J.toolChoice:{type:"function",name:J.toolChoice.name}}if(J.output)Z.text={format:{type:"json_schema",name:J.output.name,schema:J.output.schema,strict:J.output.strict}};if(J.reasoning&&$.reasoning)Z.reasoning=J.reasoning==="none"?{effort:"none"}:{effort:J.reasoning,summary:"auto"};if(typeof J.temperature==="number")Z.temperature=J.temperature;if(typeof J.maxOutputTokens==="number")Z.max_output_tokens=J.maxOutputTokens;if(J.promptCacheKey)Z.prompt_cache_key=J.promptCacheKey;return Z}function qQ(J,Q,$){let Z=[],G=new Map;if(Q.toolSearch){for(let K of $??[])if(d(K))G.set(K.name,K)}for(let K of J){let X=K.role,H=[],B=()=>{if(H.length===0)return;Z.push({type:"message",role:X,content:H}),H=[]};for(let Y of K.content??[])switch(Y.type){case"text":{if(!Y.text)break;H.push(I(X,Y.text));break}case"output":{if(Y.partial)break;H.push(I(X,JSON.stringify(Y.value)));break}case"file":{if(X==="assistant")break;let U=LQ(Y);if(!Q.fileInput){if(U)H.push(I(X,KJ(Y,!1)));break}if(Y.fileId?.startsWith(YJ))throw Error(`FilePart.fileId holds a gemi attachment id (${Y.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(!Y.fileId&&!U)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(Y.providerRejected){if(U)H.push(I(X,KJ(Y,!1)));H.push(I(X,a(Y.name)));break}if(U)H.push(I(X,KJ(Y,!!Y.fileId)));if(Y.fileId)H.push(xQ(Y));break}case"reasoning":{B();let U=CQ(Y);if(U)Z.push(U);break}case"tool-call":{if(Y.partial)break;if(B(),Q.toolSearch&&Array.isArray(Y.toolSearches))for(let j of Y.toolSearches)Z.push(...MQ(j,$??[]));let U={type:"function_call",call_id:Y.toolCallId,name:String(Y.name),arguments:JSON.stringify(Y.input??{})};if(Y.namespace&&G.has(Y.namespace))U.namespace=Y.namespace;Z.push(U);break}case"tool-result":{B(),Z.push({type:"function_call_output",call_id:Y.toolCallId,output:_Q(Y)});break}}B()}return zQ(Z)}var PQ="No result was recorded for this tool call. Assume it did not complete.";function zQ(J){let Q=new Set,$=new Set,Z=[];for(let K of J){if(K.type==="function_call"){let X=String(K.call_id);if(Q.has(X))continue;Q.add(X)}else if(K.type==="function_call_output"){let X=String(K.call_id);if(!Q.has(X)||$.has(X))continue;$.add(X)}Z.push(K)}if($.size===Q.size)return Z;let G=[];for(let K of Z){if(G.push(K),K.type!=="function_call")continue;let X=String(K.call_id);if($.has(X))continue;$.add(X),G.push({type:"function_call_output",call_id:X,output:PQ})}return G}function I(J,Q){return{type:J==="assistant"?"output_text":"input_text",text:Q}}function LQ(J){let Q=J.attachmentId;return typeof Q==="string"&&Q.startsWith(YJ)?Q:void 0}function KJ(J,Q){let $=[`id=${JSON.stringify(J.attachmentId)}`];if(J.name)$.push(`name=${JSON.stringify(J.name)}`);if(J.mimeType)$.push(`mimeType=${JSON.stringify(J.mimeType)}`);let Z=`attachment ${$.join(" ")}`;return Q?`[${Z}]`:`[${Z} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function xQ(J){let Q=J.mimeType?.trim().toLowerCase()??"";return{type:(Q?Q.startsWith("image/")&&Q!=="image/svg+xml":DQ(J.name))?"input_image":"input_file",file_id:J.fileId}}function DQ(J){let Q=/\.([a-z0-9]+)$/.exec(J?.trim().toLowerCase()??"");return Q?.[1]!==void 0&&NQ.has(Q[1])}var NQ=new Set(["jpeg","jpg","png","gif","webp"]);function CQ(J){if(!J.id)return null;let Q={type:"reasoning",id:J.id};return Q.summary=J.text?[{type:"summary_text",text:J.text}]:[],Q}function _Q(J){if(J.status==="ok"){let Q=J.modelOutput!==void 0?J.modelOutput:J.output;return typeof Q==="string"?Q:JSON.stringify(Q??null)}if(J.status==="running"){let Q=J.job?.summary===void 0?"":` Started with: ${JSON.stringify(J.job.summary)}.`;return`Started background job ${J.job?.id??"(unknown)"}. It is still running, so there is no result yet: this message will be replaced by the result when it finishes. Do not start it again.${Q}`}if(J.status==="denied"){let Q=J.reason?` Reason given: ${J.reason}`:"";if(J.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${Q}`;if(J.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${Q}`;return`The user declined this tool call, so it did not run.${Q}`}return`The tool call failed and produced no result. Error (${J.error?.code??"unknown"}): ${J.error?.message??"no message"}`}function MQ(J,Q){let $=new Set(vJ(J?.loaded)),Z=vJ(J?.namespaces),G=new Set(Z),K=[];for(let H of Q)if(d(H)){if(!G.has(H.name))continue;let B=H.tools.filter((Y)=>$.size===0||$.has(Y.name));if(B.length===0)continue;K.push({type:"namespace",name:H.name,description:H.description,tools:B.map((Y)=>E(Y,!0))})}else if(H.deferred&&$.has(H.name))K.push(E(H,!0));if(K.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:J.arguments&&typeof J.arguments==="object"?J.arguments:{paths:Z.length>0?Z:[...$]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:K}]}function vJ(J){return Array.isArray(J)?J.filter((Q)=>typeof Q==="string"):[]}function d(J){return Array.isArray(J.tools)}function OQ(J,Q){if(!J||J.length===0)return[];if(!Q.toolSearch){let G=[];for(let K of J)if(d(K))for(let X of K.tools)G.push(E(X,!1));else G.push(E(K,!1));return G}let $=[],Z=!1;for(let G of J)if(d(G)){let K=G.tools.map((X)=>{if(X.deferred)Z=!0;return E(X,!0)});$.push({type:"namespace",name:G.name,description:G.description,tools:K})}else{if(G.deferred)Z=!0;$.push(E(G,!0))}if(Z)$.push({type:"tool_search"});return $}function E(J,Q){let $={type:"function",name:J.name,description:J.description,parameters:J.parameters,strict:J.strict};if(Q&&J.deferred)$.defer_loading=!0;return $}class XJ{static models(){return[]}normalizeError(J){return D(J)}}var bJ=["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 yJ extends XJ{model;capabilities;config;constructor(J,Q={}){super();this.model=J,this.capabilities=$J(J),this.config=Q}static model(J,Q){return new yJ(J,Q)}static models(){return bJ}stream(J){let Q=WJ(J,{model:this.model,capabilities:this.capabilities});return JJ(this.endpoint(),Q,{signal:J.signal,structuredOutput:Boolean(J.output),files:r(J.messages)})}upload(J){return QJ(this.endpoint(),J)}endpoint(){return e(ZJ(this.config))}get realtime(){return new c(ZJ(this.config,{timeoutMs:i}),{model:this.model})}}class gJ extends XJ{model;capabilities;config;constructor(J,Q={}){super();this.model=J,this.capabilities=$J(J),this.config=Q}static model(J,Q){return new gJ(J,Q)}static models(){return bJ}stream(J){let Q=WJ(J,{model:this.deployment(),capabilities:this.capabilities});return JJ(this.endpoint(),Q,{signal:J.signal,structuredOutput:Boolean(J.output),files:r(J.messages)})}upload(J){return QJ(this.endpoint(),J,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return e(GJ(this.config))}get realtime(){return new c(hJ(this.config,{timeoutMs:i}),{model:this.deployment(),callFlow:"ephemeral"})}}
|
|
6
|
-
export{ZJ as ca,GJ as da,h as ea,l as fa,nJ as ga,n as ha,v as ia,c as ja,tJ as ka,XJ as la,yJ as ma,gJ as na};
|
|
7
|
-
|
|
8
|
-
//# debugId=C4C92C34D42F203064756E2164756E21
|