gemi 0.207.2 → 0.208.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/Agent.d.ts +83 -1
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/AgentController.d.ts +7 -1
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/AgentProvider.d.ts +20 -2
- package/dist/ai/AgentProvider.d.ts.map +1 -1
- package/dist/ai/FallbackProvider.d.ts.map +1 -1
- package/dist/ai/index.d.ts +4 -4
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +38 -38
- package/dist/ai/index.js.map +4 -4
- package/dist/ai/providers/call.d.ts +3 -1
- package/dist/ai/providers/call.d.ts.map +1 -1
- package/dist/ai/providers/capabilities.d.ts.map +1 -1
- package/dist/ai/providers/endpoints.d.ts +9 -0
- package/dist/ai/providers/endpoints.d.ts.map +1 -1
- package/dist/ai/providers/errors.d.ts +4 -2
- package/dist/ai/providers/errors.d.ts.map +1 -1
- package/dist/ai/providers/http.d.ts +33 -0
- package/dist/ai/providers/http.d.ts.map +1 -1
- package/dist/ai/providers/request.d.ts.map +1 -1
- package/dist/ai/store/stubAgentRun.d.ts +2 -1
- package/dist/ai/store/stubAgentRun.d.ts.map +1 -1
- package/dist/ai/testing/index.js +2 -2
- package/dist/ai/testing/index.js.map +1 -1
- package/dist/ai/types.d.ts +31 -2
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-24tj4dzx.js → chunk-094hbhc8.js} +2 -2
- package/dist/{chunk-24tj4dzx.js.map → chunk-094hbhc8.js.map} +1 -1
- package/dist/{chunk-1em8t2x1.js → chunk-101rvvje.js} +3 -3
- package/dist/{chunk-1em8t2x1.js.map → chunk-101rvvje.js.map} +1 -1
- package/dist/{chunk-qc0e278w.js → chunk-12gthjxx.js} +1 -1
- package/dist/{chunk-8ar7180x.js → chunk-1agwddws.js} +2 -2
- package/dist/{chunk-8ar7180x.js.map → chunk-1agwddws.js.map} +1 -1
- package/dist/{chunk-nfher0gz.js → chunk-1vnbw1d8.js} +2 -2
- package/dist/{chunk-nfher0gz.js.map → chunk-1vnbw1d8.js.map} +1 -1
- package/dist/{chunk-53fv4c39.js → chunk-24z18t5q.js} +4 -4
- package/dist/{chunk-53fv4c39.js.map → chunk-24z18t5q.js.map} +1 -1
- package/dist/{chunk-6ge27ygx.js → chunk-2jbdbvd8.js} +2 -2
- package/dist/{chunk-6ge27ygx.js.map → chunk-2jbdbvd8.js.map} +1 -1
- package/dist/{chunk-fhn92are.js → chunk-2k438dp6.js} +2 -2
- package/dist/{chunk-fhn92are.js.map → chunk-2k438dp6.js.map} +1 -1
- package/dist/{chunk-rjtge67x.js → chunk-3raywsbj.js} +2 -2
- package/dist/{chunk-rjtge67x.js.map → chunk-3raywsbj.js.map} +1 -1
- package/dist/{chunk-k8peybx0.js → chunk-3rgf7rsy.js} +3 -3
- package/dist/{chunk-k8peybx0.js.map → chunk-3rgf7rsy.js.map} +1 -1
- package/dist/{chunk-hthyn5pj.js → chunk-3wsmgdcr.js} +3 -3
- package/dist/{chunk-hthyn5pj.js.map → chunk-3wsmgdcr.js.map} +1 -1
- package/dist/{chunk-3830ee5d.js → chunk-5399t8zm.js} +2 -2
- package/dist/{chunk-3830ee5d.js.map → chunk-5399t8zm.js.map} +1 -1
- package/dist/{chunk-ndcqbwsj.js → chunk-641fns6j.js} +2 -2
- package/dist/{chunk-ndcqbwsj.js.map → chunk-641fns6j.js.map} +1 -1
- package/dist/{chunk-wrfz0jsw.js → chunk-6zcqa5fz.js} +2 -2
- package/dist/{chunk-wrfz0jsw.js.map → chunk-6zcqa5fz.js.map} +1 -1
- package/dist/{chunk-6zpf257t.js → chunk-716832vw.js} +2 -2
- package/dist/{chunk-6zpf257t.js.map → chunk-716832vw.js.map} +1 -1
- package/dist/{chunk-e0scxs81.js → chunk-8gyq2etb.js} +3 -3
- package/dist/{chunk-e0scxs81.js.map → chunk-8gyq2etb.js.map} +3 -3
- package/dist/{chunk-8q5kxzxn.js → chunk-8ty6yp6r.js} +3 -3
- package/dist/{chunk-8q5kxzxn.js.map → chunk-8ty6yp6r.js.map} +1 -1
- package/dist/{chunk-8ncqxja2.js → chunk-9d8tz60r.js} +1 -1
- package/dist/{chunk-xgc5tj8k.js → chunk-9qyedsvw.js} +3 -3
- package/dist/{chunk-xgc5tj8k.js.map → chunk-9qyedsvw.js.map} +1 -1
- package/dist/{chunk-zf1eqgzt.js → chunk-a76a7869.js} +2 -2
- package/dist/{chunk-72e857nw.js.map → chunk-a76a7869.js.map} +1 -1
- package/dist/{chunk-djnn8vvp.js → chunk-achvynaf.js} +2 -2
- package/dist/{chunk-djnn8vvp.js.map → chunk-achvynaf.js.map} +1 -1
- package/dist/{chunk-0eq7am78.js → chunk-ad0dx73f.js} +2 -2
- package/dist/{chunk-0eq7am78.js.map → chunk-ad0dx73f.js.map} +1 -1
- package/dist/{chunk-092magz7.js → chunk-ag5nhjcr.js} +2 -2
- package/dist/{chunk-092magz7.js.map → chunk-ag5nhjcr.js.map} +1 -1
- package/dist/{chunk-emt36pxm.js → chunk-agrr8f8y.js} +2 -2
- package/dist/{chunk-emt36pxm.js.map → chunk-agrr8f8y.js.map} +1 -1
- package/dist/{chunk-znw55n6g.js → chunk-arzp5dne.js} +2 -2
- package/dist/{chunk-znw55n6g.js.map → chunk-arzp5dne.js.map} +1 -1
- package/dist/{chunk-jn1h76sa.js → chunk-b1y54j6v.js} +2 -2
- package/dist/{chunk-jn1h76sa.js.map → chunk-b1y54j6v.js.map} +1 -1
- package/dist/{chunk-te4vz0rw.js → chunk-b51a77kv.js} +2 -2
- package/dist/{chunk-te4vz0rw.js.map → chunk-b51a77kv.js.map} +1 -1
- package/dist/{chunk-wfees83q.js → chunk-bdzj9znx.js} +3 -3
- package/dist/{chunk-wfees83q.js.map → chunk-bdzj9znx.js.map} +1 -1
- package/dist/{chunk-39dz1abf.js → chunk-bhc9vk13.js} +1 -1
- package/dist/{chunk-460c8k50.js → chunk-cfbhhfkv.js} +3 -3
- package/dist/{chunk-460c8k50.js.map → chunk-cfbhhfkv.js.map} +1 -1
- package/dist/{chunk-78g1cngk.js → chunk-dje6exhs.js} +2 -2
- package/dist/{chunk-78g1cngk.js.map → chunk-dje6exhs.js.map} +1 -1
- package/dist/{chunk-bpqkzpkt.js → chunk-dm6tkkwv.js} +2 -2
- package/dist/{chunk-bpqkzpkt.js.map → chunk-dm6tkkwv.js.map} +1 -1
- package/dist/{chunk-bxznwntw.js → chunk-enq03rgh.js} +2 -2
- package/dist/{chunk-bxznwntw.js.map → chunk-enq03rgh.js.map} +1 -1
- package/dist/{chunk-34vvev4a.js → chunk-ewhgsw1n.js} +2 -2
- package/dist/{chunk-34vvev4a.js.map → chunk-ewhgsw1n.js.map} +1 -1
- package/dist/{chunk-8gyanh1b.js → chunk-f0sfh1r2.js} +2 -2
- package/dist/{chunk-8gyanh1b.js.map → chunk-f0sfh1r2.js.map} +1 -1
- package/dist/{chunk-a7zqp5m7.js → chunk-fsae9dgb.js} +2 -2
- package/dist/{chunk-a7zqp5m7.js.map → chunk-fsae9dgb.js.map} +1 -1
- package/dist/{chunk-hqg4dfca.js → chunk-fv6ncgbc.js} +2 -2
- package/dist/{chunk-hqg4dfca.js.map → chunk-fv6ncgbc.js.map} +1 -1
- package/dist/{chunk-etcds9w3.js → chunk-h1f4f9wx.js} +2 -2
- package/dist/{chunk-etcds9w3.js.map → chunk-h1f4f9wx.js.map} +1 -1
- package/dist/{chunk-m3v661b3.js → chunk-h4byt0x3.js} +2 -2
- package/dist/{chunk-m3v661b3.js.map → chunk-h4byt0x3.js.map} +1 -1
- package/dist/{chunk-c8bvpkr2.js → chunk-hbdqv48k.js} +2 -2
- package/dist/{chunk-c8bvpkr2.js.map → chunk-hbdqv48k.js.map} +1 -1
- package/dist/{chunk-9m6mkaqb.js → chunk-hcysexst.js} +2 -2
- package/dist/{chunk-9m6mkaqb.js.map → chunk-hcysexst.js.map} +1 -1
- package/dist/{chunk-wpfempaj.js → chunk-hmccxtd3.js} +2 -2
- package/dist/{chunk-wpfempaj.js.map → chunk-hmccxtd3.js.map} +1 -1
- package/dist/{chunk-tx5zrdmb.js → chunk-jggtz103.js} +2 -2
- package/dist/{chunk-tx5zrdmb.js.map → chunk-jggtz103.js.map} +1 -1
- package/dist/{chunk-sjve1yvv.js → chunk-jr9y6k90.js} +1 -1
- package/dist/{chunk-6x2zbh1q.js → chunk-kax9ghny.js} +2 -2
- package/dist/{chunk-6x2zbh1q.js.map → chunk-kax9ghny.js.map} +1 -1
- package/dist/{chunk-q1t9gvm1.js → chunk-kbkyde5f.js} +2 -2
- package/dist/{chunk-q1t9gvm1.js.map → chunk-kbkyde5f.js.map} +1 -1
- package/dist/{chunk-77dt2tap.js → chunk-mtf5kzza.js} +2 -2
- package/dist/{chunk-77dt2tap.js.map → chunk-mtf5kzza.js.map} +1 -1
- package/dist/{chunk-3z8d8v8q.js → chunk-mxedsqbe.js} +3 -3
- package/dist/{chunk-3z8d8v8q.js.map → chunk-mxedsqbe.js.map} +1 -1
- package/dist/{chunk-jy61580r.js → chunk-n0sbg84n.js} +2 -2
- package/dist/{chunk-jy61580r.js.map → chunk-n0sbg84n.js.map} +1 -1
- package/dist/{chunk-06w8hhnk.js → chunk-n65hk6bq.js} +2 -2
- package/dist/{chunk-06w8hhnk.js.map → chunk-n65hk6bq.js.map} +1 -1
- package/dist/{chunk-4ksnhx8x.js → chunk-ntcj2sgv.js} +3 -3
- package/dist/{chunk-4ksnhx8x.js.map → chunk-ntcj2sgv.js.map} +1 -1
- package/dist/{chunk-scw0vknj.js → chunk-p27ft91c.js} +1 -1
- package/dist/{chunk-vyaedzr8.js → chunk-p608rrfc.js} +3 -3
- package/dist/{chunk-vyaedzr8.js.map → chunk-p608rrfc.js.map} +1 -1
- package/dist/chunk-pag82mxh.js +5 -0
- package/dist/{chunk-4q59y78y.js.map → chunk-pag82mxh.js.map} +1 -1
- package/dist/{chunk-yj1h4rzn.js → chunk-q634cwbc.js} +3 -3
- package/dist/{chunk-yj1h4rzn.js.map → chunk-q634cwbc.js.map} +1 -1
- package/dist/{chunk-09hzyf9g.js → chunk-q7x7ddw0.js} +3 -3
- package/dist/{chunk-09hzyf9g.js.map → chunk-q7x7ddw0.js.map} +1 -1
- package/dist/{chunk-65btke6p.js → chunk-qc7x8q1q.js} +2 -2
- package/dist/{chunk-65btke6p.js.map → chunk-qc7x8q1q.js.map} +1 -1
- package/dist/{chunk-wdrmzjtq.js → chunk-r5ggnywk.js} +2 -2
- package/dist/{chunk-wdrmzjtq.js.map → chunk-r5ggnywk.js.map} +1 -1
- package/dist/{chunk-72e857nw.js → chunk-raejxs3y.js} +2 -2
- package/dist/{chunk-zf1eqgzt.js.map → chunk-raejxs3y.js.map} +1 -1
- package/dist/{chunk-k8a41gkt.js → chunk-rffpqhn8.js} +2 -2
- package/dist/{chunk-k8a41gkt.js.map → chunk-rffpqhn8.js.map} +1 -1
- package/dist/{chunk-p9c5rc1z.js → chunk-rhyhxgxg.js} +3 -3
- package/dist/{chunk-p9c5rc1z.js.map → chunk-rhyhxgxg.js.map} +1 -1
- package/dist/{chunk-eeq9ty68.js → chunk-t0xfzpfa.js} +2 -2
- package/dist/{chunk-eeq9ty68.js.map → chunk-t0xfzpfa.js.map} +1 -1
- package/dist/chunk-t9gc6mhq.js +11 -0
- package/dist/{chunk-2e40rx0p.js.map → chunk-t9gc6mhq.js.map} +8 -8
- package/dist/{chunk-9qyet3nb.js → chunk-tj8wbxyz.js} +2 -2
- package/dist/{chunk-9qyet3nb.js.map → chunk-tj8wbxyz.js.map} +1 -1
- package/dist/{chunk-q751b0jx.js → chunk-tjfvkzq8.js} +1 -1
- package/dist/{chunk-njnng5ew.js → chunk-v10kckwp.js} +4 -4
- package/dist/{chunk-njnng5ew.js.map → chunk-v10kckwp.js.map} +1 -1
- package/dist/{chunk-ne51fxg2.js → chunk-vrpsgq3x.js} +2 -2
- package/dist/{chunk-ne51fxg2.js.map → chunk-vrpsgq3x.js.map} +1 -1
- package/dist/{chunk-jy26hy7z.js → chunk-w92n83g2.js} +2 -2
- package/dist/{chunk-jy26hy7z.js.map → chunk-w92n83g2.js.map} +1 -1
- package/dist/{chunk-dwya9z8p.js → chunk-wcpqn1pg.js} +2 -2
- package/dist/{chunk-dwya9z8p.js.map → chunk-wcpqn1pg.js.map} +1 -1
- package/dist/{chunk-zvk6dydb.js → chunk-wkh9xcdq.js} +2 -2
- package/dist/{chunk-zvk6dydb.js.map → chunk-wkh9xcdq.js.map} +1 -1
- package/dist/{chunk-7wzhdq1x.js → chunk-wy87gc0b.js} +3 -3
- package/dist/{chunk-7wzhdq1x.js.map → chunk-wy87gc0b.js.map} +1 -1
- package/dist/{chunk-aed0vv5g.js → chunk-xt90xbes.js} +2 -2
- package/dist/{chunk-aed0vv5g.js.map → chunk-xt90xbes.js.map} +1 -1
- package/dist/{chunk-6cx6kh04.js → chunk-y16vp7yf.js} +2 -2
- package/dist/{chunk-6cx6kh04.js.map → chunk-y16vp7yf.js.map} +1 -1
- package/dist/{chunk-e05rbjn2.js → chunk-ykh78bct.js} +2 -2
- package/dist/{chunk-e05rbjn2.js.map → chunk-ykh78bct.js.map} +1 -1
- package/dist/{chunk-cffx7wqp.js → chunk-yn3pf1fp.js} +2 -2
- package/dist/{chunk-cffx7wqp.js.map → chunk-yn3pf1fp.js.map} +1 -1
- package/dist/{chunk-s1fa5f8b.js → chunk-yzbj11dd.js} +2 -2
- package/dist/{chunk-s1fa5f8b.js.map → chunk-yzbj11dd.js.map} +1 -1
- package/dist/{chunk-vebstesm.js → chunk-zcx8n3mk.js} +3 -3
- package/dist/{chunk-vebstesm.js.map → chunk-zcx8n3mk.js.map} +1 -1
- package/dist/chunk-zrqzxc50.js +48 -0
- package/dist/chunk-zrqzxc50.js.map +27 -0
- package/dist/{chunk-8d2g78vc.js → chunk-zv6a6w1v.js} +2 -2
- package/dist/{chunk-8d2g78vc.js.map → chunk-zv6a6w1v.js.map} +1 -1
- package/dist/{chunk-1tc6j8bn.js → chunk-zzs96hc8.js} +2 -2
- package/dist/{chunk-1tc6j8bn.js.map → chunk-zzs96hc8.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 +1 -1
- package/package.json +1 -1
- package/dist/chunk-2e40rx0p.js +0 -11
- package/dist/chunk-4q59y78y.js +0 -5
- package/dist/chunk-v1d7xya8.js +0 -46
- package/dist/chunk-v1d7xya8.js.map +0 -27
- /package/dist/{chunk-qc0e278w.js.map → chunk-12gthjxx.js.map} +0 -0
- /package/dist/{chunk-8ncqxja2.js.map → chunk-9d8tz60r.js.map} +0 -0
- /package/dist/{chunk-39dz1abf.js.map → chunk-bhc9vk13.js.map} +0 -0
- /package/dist/{chunk-sjve1yvv.js.map → chunk-jr9y6k90.js.map} +0 -0
- /package/dist/{chunk-scw0vknj.js.map → chunk-p27ft91c.js.map} +0 -0
- /package/dist/{chunk-q751b0jx.js.map → chunk-tjfvkzq8.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": "B16EA13C05C89E8764756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"../chunk-
|
|
2
|
+
import"../chunk-a76a7869.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{Me as Y}from"../chunk-5399t8zm.js";import{Yk as M}from"../chunk-094hbhc8.js";import{cm as P,em as R}from"../chunk-p608rrfc.js";import"../chunk-achvynaf.js";import{Am as V,Bm as W,ym as Q,zm as U}from"../chunk-mtf5kzza.js";import"../chunk-a76a7869.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=220406E8528B61FF64756E2164756E21
|
|
@@ -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": "220406E8528B61FF64756E2164756E21",
|
|
10
10
|
"names": []
|
|
11
11
|
}
|
package/dist/vitest/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ua as B,va as D}from"../chunk-
|
|
2
|
+
import{ua as B,va as D}from"../chunk-ntcj2sgv.js";import"../chunk-h4byt0x3.js";import"../chunk-wkh9xcdq.js";import{Pa as J}from"../chunk-zzs96hc8.js";import"../chunk-jggtz103.js";import"../chunk-a76a7869.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
4
|
//# debugId=54630B516034F10064756E2164756E21
|
package/package.json
CHANGED
package/dist/chunk-2e40rx0p.js
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Md as jQ,Sd as O,Td as l,Ud as dQ,Vd as lQ,Wd as iQ,Xd as I,Yd as M,wd as a,yd as r}from"./chunk-e0scxs81.js";import{Tj as wQ}from"./chunk-8ar7180x.js";var z5=500,SQ=20000;function L5(Q,$){if(!Q)return;let J=Q.trim();if(/^\d+(\.\d+)?$/.test(J))return Math.max(0,Number(J)*1000);let Z=Date.parse(J);if(Number.isNaN(Z))return;return Math.max(0,Z-$)}function d(Q,$){let J=Math.min(SQ,z5*2**Q);return Math.round(J*(0.5+$()*0.5))}function q5(Q){return Q===429||Q===408||Q===409||Q>=500}function D5(Q,$){return q5(Q)&&M($).retryable}function RQ(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function AQ(Q,$){return new Promise((J,Z)=>{let X=setTimeout(J,Q);$?.addEventListener("abort",()=>{clearTimeout(X),Z(RQ($))},{once:!0})})}async function JQ(Q,$,J=AQ){if(!$)return await J(Q);$.throwIfAborted();let Z;try{await Promise.race([J(Q,$),new Promise((X,Y)=>{Z=()=>Y(RQ($)),$.addEventListener("abort",Z,{once:!0})})])}finally{if(Z)$.removeEventListener("abort",Z)}}async function y(Q,$,J){let Z=J.fetchImpl??((V,W)=>fetch(V,W)),X=J.sleep??AQ,Y=J.random??Math.random,G=J.now??Date.now,F=Math.max(0,J.maxRetries),j=J.startedAt??G(),K=(V,W,H,U)=>{try{J.onRetry?.({attempt:W+1,maxRetries:F,error:M(H),...I(H),timedOut:U,delayMs:V,elapsedMs:G()-j})}catch{}return JQ(V,J.signal,X)},B;for(let V=0;V<=F;V++){J.signal?.throwIfAborted();let W=new AbortController,H=()=>W.abort(J.signal?.reason);J.signal?.addEventListener("abort",H,{once:!0});let U=!1,L=J.timeoutMs>0?setTimeout(()=>{U=!0,W.abort()},J.timeoutMs):void 0,P;try{P=await Z(Q,{...$,signal:W.signal})}catch(u){if(L!==void 0)clearTimeout(L);if(J.signal?.removeEventListener("abort",H),J.signal?.aborted)throw u;if(B=U?new l(J.timeoutMs):u,U&&J.retryTimeouts===!1)throw B;if(V===F)throw B;await K(d(V,Y),V,B,U);continue}if(L!==void 0)clearTimeout(L);if(P.ok)return P;J.signal?.removeEventListener("abort",H);let g=await C5(P),D=new O(P.status,g,P.headers.get("x-request-id")??P.headers.get("request-id")??void 0,L5(P.headers.get("retry-after"),G()));if(V===F||!D5(P.status,D))throw D;let _=D.retryAfter??(P.status===429?M(D).retryAfter:void 0);await K(_===void 0?d(V,Y):Math.min(_,SQ),V,D,!1),B=D}throw B??Error("Provider request failed with no response.")}async function C5(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}function IQ(Q,$,J){let Z=$.idleMs>0?$.idleMs:0,X=$.maxMs>0?$.maxMs:0;if(!Q||!Z&&!X)return Q;let Y=X?performance.now()+X:1/0,G=Q.getReader();return new ReadableStream({async pull(F){let j,K,B=Math.max(0,Y-performance.now()),V=!Z||B<=Z,W=V?B:Z,H=new Promise((U,L)=>{j=setTimeout(()=>{K=V?J.max():J.idle(),L(K)},W)});try{let U=await Promise.race([G.read(),H]);if(U.done)F.close();else F.enqueue(U.value)}catch(U){let L=K??U;F.error(L),G.cancel(L).catch(()=>{})}finally{clearTimeout(j)}},cancel(F){return G.cancel(F)}},{highWaterMark:0})}var XQ=30000,TQ=10,EQ=7200,N5=600,P5="gpt-live-transcribe";function M5(Q){return Q.type==="transcription"}function x5(Q){if(Q.language!==void 0&&Q.languages!==void 0)throw TypeError("A transcription session takes `languages` or `language`, not both (gpt-live-transcribe reads `languages`).");for(let X of Q.keywords??[])if(/[<>\r\n]/.test(X))throw TypeError(`Transcription keywords must be one line without "<" or ">", got ${JSON.stringify(X)}.`);let $={model:Q.model??P5};if(Q.prompt!==void 0)$.prompt=Q.prompt;if(Q.keywords?.length)$.keywords=Q.keywords;if(Q.languages?.length)$.languages=Q.languages;if(Q.language!==void 0)$.language=Q.language;if(Q.delay!==void 0)$.delay=Q.delay;let J={transcription:$,turn_detection:Q.turnDetection?kQ(Q.turnDetection):null};if(Q.noiseReduction!==void 0)J.noise_reduction=Q.noiseReduction&&{type:Q.noiseReduction};let Z={type:"transcription",audio:{input:J}};if(Q.logprobs)Z.include=["item.input_audio_transcription.logprobs"];return{...Z,...Q.vendor}}function _5(Q){if(!Q)return{type:"object",properties:{}};return wQ(Q)?Q.toJSONSchema():Q}function i(Q,$){if(M5(Q))return x5(Q);let J={type:"realtime"},Z=Q.model??$;if(Z)J.model=Z;if(Q.instructions!==void 0)J.instructions=Q.instructions;if(Q.outputModalities)J.output_modalities=Q.outputModalities;if(Q.maxOutputTokens!==void 0)J.max_output_tokens=Q.maxOutputTokens;if(Q.truncation!==void 0)J.truncation=Q.truncation;if(Q.tools)J.tools=Q.tools.map((G)=>({type:"function",name:G.name,...G.description?{description:G.description}:{},parameters:_5(G.parameters)}));if(Q.toolChoice!==void 0)J.tool_choice=typeof Q.toolChoice==="string"?Q.toolChoice:{type:"function",name:Q.toolChoice.name};let X={};if(Q.turnDetection!==void 0)X.turn_detection=Q.turnDetection&&kQ(Q.turnDetection);if(Q.transcription!==void 0)X.transcription=Q.transcription;if(Q.noiseReduction!==void 0)X.noise_reduction=Q.noiseReduction&&{type:Q.noiseReduction};let Y={};if(Q.voice!==void 0)Y.voice=Q.voice;if(Q.speed!==void 0)Y.speed=Q.speed;if(Object.keys(X).length||Object.keys(Y).length)J.audio={...Object.keys(X).length?{input:X}:{},...Object.keys(Y).length?{output:Y}:{}};return{...J,...Q.vendor}}function kQ(Q){let $={type:Q.type};if(Q.createResponse!==void 0)$.create_response=Q.createResponse;if(Q.interruptResponse!==void 0)$.interrupt_response=Q.interruptResponse;if(Q.type==="semantic_vad"){if(Q.eagerness!==void 0)$.eagerness=Q.eagerness}else{if(Q.threshold!==void 0)$.threshold=Q.threshold;if(Q.prefixPaddingMs!==void 0)$.prefix_padding_ms=Q.prefixPaddingMs;if(Q.silenceDurationMs!==void 0)$.silence_duration_ms=Q.silenceDurationMs;if(Q.idleTimeoutMs!==void 0)$.idle_timeout_ms=Q.idleTimeoutMs}return $}function YQ(Q){let $=Number(Q?.input_tokens??0),J=Number(Q?.output_tokens??0),Z={inputTokens:$,outputTokens:J,totalTokens:Number(Q?.total_tokens??$+J)},X=Q?.input_token_details??Q?.input_tokens_details,Y=Q?.output_token_details??Q?.output_tokens_details;if(typeof X?.cached_tokens==="number")Z.cachedInputTokens=X.cached_tokens;if(typeof X?.audio_tokens==="number")Z.audioInputTokens=X.audio_tokens;let G=X?.cached_tokens_details?.audio_tokens;if(typeof G==="number")Z.cachedAudioInputTokens=G;if(typeof X?.image_tokens==="number"&&X.image_tokens>0)Z.imageInputTokens=X.image_tokens;if(typeof Y?.audio_tokens==="number")Z.audioOutputTokens=Y.audio_tokens;return Z}class b extends Error{code;retryable;status;constructor(Q,$={}){super(Q.message,{cause:$.cause});if(this.name="RealtimeRequestError",this.code=Q.code,this.retryable=Q.retryable,$.status!==void 0)this.status=$.status}}var O5=60;class n{model;target;options;constructor(Q,$){this.target=Q,this.options=$,this.model=$.model}url(Q){return`${this.target.base}/realtime${Q}${this.target.query}`}sidebandUrl(Q){let $=this.target.base.replace(/^http(s?):/i,(Z,X)=>`ws${X}:`),J=this.target.query?`${this.target.query}&`:"?";return`${$}/realtime${J}call_id=${encodeURIComponent(Q)}`}async createCall(Q){let $=Q.flow??this.options.callFlow??"unified",J,Z;if($==="ephemeral")J={authorization:`Bearer ${(await this.clientSecret({session:Q.session,ttlSeconds:O5,signal:Q.signal})).value}`,"content-type":"application/sdp"},Z=Q.sdp;else{let j=new FormData;j.set("sdp",Q.sdp),j.set("session",JSON.stringify(i(Q.session??{},this.model))),J=await this.target.headers(),Z=j}if(Q.safetyIdentifier)J["OpenAI-Safety-Identifier"]=Q.safetyIdentifier;let X=this.url("/calls"),Y=await this.request(Q.webrtcFilter?`${X}${X.includes("?")?"&":"?"}webrtcfilter=on`:X,{method:"POST",headers:J,body:Z},Q.signal),G=await Y.text(),F=R5(Y);if(!F)throw new b({code:"provider_error",message:"The provider started a realtime call but did not say which one (no Location).",retryable:!1});return{sdpAnswer:G,callId:F}}async clientSecret(Q={}){let $=Q.ttlSeconds??N5;if(!Number.isInteger($)||$<TQ||$>EQ)throw RangeError(`ttlSeconds must be a whole number from ${TQ} to ${EQ}, got ${$}.`);let J={...await this.target.headers(),"content-type":"application/json"};if(Q.safetyIdentifier)J["OpenAI-Safety-Identifier"]=Q.safetyIdentifier;let X=await(await this.request(this.url("/client_secrets"),{method:"POST",headers:J,body:JSON.stringify({expires_after:{anchor:"created_at",seconds:$},session:i(Q.session??{},this.model)})},Q.signal)).json();if(typeof X?.value!=="string")throw new b({code:"provider_error",message:"The provider answered a client secret request with no secret.",retryable:!1});return{value:X.value,expiresAt:Number(X.expires_at??0),session:X.session,callsUrl:this.url("/calls")}}async hangup(Q,$={}){try{await this.request(this.url(`/calls/${encodeURIComponent(Q)}/hangup`),{method:"POST",headers:await this.target.headers()},$.signal)}catch(J){if(S5(J,Q))return;throw J}}sideband(Q,$={}){return new ZQ({...$,callId:Q,url:this.sidebandUrl(Q),headers:this.target.headers,webSocket:$.webSocket??this.options.webSocket,hangup:()=>this.hangup(Q)})}async request(Q,$,J){try{return await y(Q,$,{maxRetries:this.target.maxRetries,timeoutMs:this.target.timeoutMs,retryTimeouts:!1,signal:J,fetchImpl:this.options.fetchImpl})}catch(Z){if(J?.aborted)throw Z;throw new b(M(Z),{cause:Z,...Z instanceof O?{status:Z.status}:{}})}}}function S5(Q,$){if(!(Q instanceof b)||Q.status!==404)return!1;let J=Q.cause instanceof O?Q.cause.body:void 0,Z=J?.error??J,X=String(Z?.code??"").toLowerCase(),Y=String(Z?.message??"").toLowerCase();if(X.includes("call"))return!0;if(Y.includes($.toLowerCase()))return!0;return/\bcall\b/.test(Y)&&/not (be )?found|does not exist|no longer|ended/.test(Y)}function R5(Q){let $=Q.headers.get("location");if(!$)return;let J=$.split("?")[0].replace(/\/+$/,""),Z=J.slice(J.lastIndexOf("/")+1);return Z?decodeURIComponent(Z):void 0}var A5={"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 I5(Q){if(typeof Q!=="string")return;let $;try{$=JSON.parse(Q)}catch{return}if(!$||typeof $!=="object"||typeof $.type!=="string")return;let J=A5[$.type];if(J)$.type=J;if($.type==="response.done"&&$.response?.usage)$.usage=YQ($.response.usage);if($.type==="conversation.item.input_audio_transcription.completed"&&$.usage)if($.usage.type==="duration"){let Z=Number($.usage.seconds);if(Number.isFinite(Z))$.transcriptionSeconds=Z}else $.transcriptionUsage=YQ($.usage);return $}var vQ=1,T5=500;function E5(Q,$){let J=globalThis.WebSocket;if(!J)throw Error("No global WebSocket: the realtime sideband needs Bun or Node 22+.");return new J(Q,{headers:$.headers})}class ZQ{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(Q){this.init=Q,this.callId=Q.callId,this.ready=new Promise(($,J)=>{this.resolveReady=$,this.rejectReady=J}),this.ready.catch(()=>{}),this.closed=new Promise(($)=>this.resolveClosed=$),this.open()}send(Q){if(this.finished||this.closing)return;let $=JSON.stringify(Q);if(this.socket?.readyState===vQ)this.socket.send($);else this.outbox.push($)}updateSession(Q){this.send({type:"session.update",session:i(Q)})}addItem(Q){this.send({type:"conversation.item.create",item:Q})}addNote(Q){this.addItem({type:"message",role:"system",content:[{type:"input_text",text:Q}]})}functionOutput(Q,$){this.addItem({type:"function_call_output",call_id:Q,output:typeof $==="string"?$:JSON.stringify($)})}createResponse(Q={}){let $={};if(Q.instructions!==void 0)$.instructions=Q.instructions;if(Q.toolChoice!==void 0)$.tool_choice=typeof Q.toolChoice==="string"?Q.toolChoice:{type:"function",name:Q.toolChoice.name};if(Q.outputModalities)$.output_modalities=Q.outputModalities;if(Q.conversation)$.conversation=Q.conversation;if(Q.metadata)$.metadata=Q.metadata;Object.assign($,Q.vendor),this.send(Object.keys($).length?{type:"response.create",response:$}:{type:"response.create"})}cancelResponse(Q){this.send(Q?{type:"response.cancel",response_id:Q}:{type:"response.cancel"})}on(Q){return this.listeners.add(Q),()=>this.listeners.delete(Q)}[Symbol.asyncIterator](){let Q={queue:this.backlog??[],done:this.finished};return this.backlog=void 0,this.subscribers.add(Q),{next:async()=>{for(;;){let J=Q.queue.shift();if(J)return{value:J,done:!1};if(Q.done)return this.subscribers.delete(Q),{value:void 0,done:!0};await new Promise((Z)=>Q.wake=Z),Q.wake=void 0}},return:async()=>{return Q.done=!0,Q.queue.length=0,this.subscribers.delete(Q),{value:void 0,done:!0}}}}close(Q=1000,$="closed"){if(this.finished||this.closing)return;if(this.closing=!0,this.socket&&this.socket.readyState<=vQ)this.socket.close(Q,$);else this.finish(Q,$,!0)}async hangup(){try{await this.init.hangup()}catch(Q){if(this.finalEvent&&!this.finalEvent.byClient&&this.finalEvent.code===1000)return;throw Q}this.close(1000,"hangup")}async open(){let Q;try{let J=await this.init.headers();if(this.closing)return this.finish(1000,"closed",!0);Q=(this.init.webSocket??E5)(this.init.url,{headers:J})}catch(J){return this.dropped(1006,J instanceof Error?J.message:String(J),!1)}this.socket=Q;let $=!1;Q.addEventListener("open",()=>{$=!0;let J=this.everOpened;this.everOpened=!0;let Z=this.failures;this.failures=0;for(let X of this.outbox.splice(0))Q.send(X);if(this.resolveReady(),J)this.emit({type:"sideband.reconnected",attempt:Z})}),Q.addEventListener("message",(J)=>{let Z=I5(J.data);if(Z)this.emit(Z)}),Q.addEventListener("close",(J)=>{if(this.socket!==Q)return;this.dropped(J.code??1006,J.reason??"",$)}),Q.addEventListener("error",()=>{})}dropped(Q,$,J){if(this.socket=void 0,this.closing)return this.finish(Q,$,!0);let Z=this.init.reconnect?.attempts??3;if(!((Q!==1000||!J)&&this.failures<Z))return this.finish(Q,$,!1);this.failures+=1;let Y=(this.init.reconnect?.delayMs??500)*2**(this.failures-1);setTimeout(()=>void this.open(),Y)}finish(Q,$,J){if(this.finished)return;this.finished=!0,this.outbox.length=0;let Z={type:"sideband.closed",code:Q,reason:$,byClient:J};this.finalEvent=Z,this.emit(Z);for(let X of this.subscribers)X.done=!0,X.wake?.();if(!this.everOpened)this.rejectReady(Error(`Realtime sideband did not open (${Q} ${$}).`));this.resolveClosed(Z)}emit(Q){if(this.backlog){if(this.backlog.push(Q),this.backlog.length>T5)this.backlog.shift()}for(let $ of this.subscribers){if($.done)continue;$.queue.push(Q),$.wake?.()}for(let $ of this.listeners)try{$(Q)}catch{}}}var hQ=3;function GQ(Q){let $=new Map;for(let J of Q)for(let Z of J.content??[]){if(Z.type!=="file"||!Z.fileId||$.has(Z.fileId))continue;$.set(Z.fileId,{name:Z.name,mimeType:Z.mimeType})}return $}function fQ(Q,$,J=new Map){if(!($ instanceof O))return[];if($.status!==400&&$.status!==404)return[];let Z=VQ($.body);if(!Z)return[];let X=w5(Q.input);if(X.length===0)return[];let Y=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(Y){let K=Q.input[Number(Y[1])],B=WQ(K)[Number(Y[2])],V=B&&typeof B.file_id==="string"?B.file_id:void 0;if(V)return[V]}let G=Z.message??"",F=bQ(X.map((K)=>K.fileId).filter((K)=>k5(G,K)));if(F.length>0)return F;let j=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(G);if(j){let K=j[1].toLowerCase()==="image type"?"input_image":"input_file",B=j[2].toLowerCase(),V=bQ(X.filter((H)=>H.type===K).map((H)=>H.fileId)),W=V.filter((H)=>(J.get(H)?.name??"").trim().toLowerCase().endsWith(`.${B}`));if(W.length===1)return W;if(W.length===0&&V.length===1)return V}return[]}function gQ(Q,$,J=new Map){return{...Q,input:Q.input.map((Z)=>{let X=WQ(Z);if(!X.some((Y)=>yQ(Y,$)))return Z;return{...Z,content:X.map((Y)=>yQ(Y,$)?{type:"input_text",text:h(J.get(String(Y.file_id))?.name)}:Y)}})}}function h(Q){return`[${Q?`attachment ${JSON.stringify(Q)}`:"an attachment"} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`}function yQ(Q,$){return typeof Q.file_id==="string"&&$.has(Q.file_id)}function WQ(Q){let $=Q?.content;return Array.isArray($)?$:[]}function w5(Q){let $=[];for(let J of Q)for(let Z of WQ(J))if(typeof Z.file_id==="string"&&Z.file_id)$.push({type:String(Z.type),fileId:Z.file_id});return $}function VQ(Q){if(!Q||typeof Q!=="object")return null;let $=Q,J=$.error&&typeof $.error==="object"?$.error:Q;return{message:typeof J.message==="string"?J.message:void 0,param:typeof J.param==="string"?J.param:void 0}}function k5(Q,$){let J=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${J}($|[^A-Za-z0-9_-])`).test(Q)}function bQ(Q){return[...new Set(Q)]}function uQ(Q,$){if(!($ instanceof O))return null;if($.status!==400&&$.status!==404)return null;let J=Q?.input;if(!Array.isArray(J))return null;let Z=VQ($.body)?.message??"",X=/Item with id '([^']+)' not found/i.exec(Z)?.[1];if(!X)return null;let Y=(G)=>G?.type==="reasoning";if(!J.some((G)=>Y(G)&&G.id===X))return null;return{...Q,input:J.filter((G)=>!Y(G))}}async function*HQ(Q){let $="",J="",Z=[],X,Y=()=>{if(Z.length===0&&!J)return null;let j={event:J,data:Z.join(`
|
|
3
|
-
`),id:X};return J="",Z=[],X=void 0,j.data?j:null},G=(j)=>{let K=j.endsWith("\r")?j.slice(0,-1):j;if(K==="")return Y();if(K.startsWith(":"))return null;let B=K.indexOf(":"),V=B===-1?K:K.slice(0,B),W=B===-1?"":K.slice(B+1);if(W.startsWith(" "))W=W.slice(1);if(V==="event")J=W;else if(V==="data")Z.push(W);else if(V==="id")X=W;return null};for await(let j of Q){$+=j;let K=$.indexOf(`
|
|
4
|
-
`);while(K!==-1){let B=$.slice(0,K);$=$.slice(K+1);let V=G(B);if(V)yield V;K=$.indexOf(`
|
|
5
|
-
`)}}if($.length>0){let j=G($);if(j)yield j}let F=Y();if(F)yield F}async function*cQ(Q,$={}){let J=new Map,Z=new Set,X,Y=!1,G,F=(j,K)=>({type:"finish",reason:j,usage:K,...G?{model:G}:{}});for await(let j of HQ(Q)){if(j.data==="[DONE]")break;let K;try{K=JSON.parse(j.data)}catch{continue}let B=typeof K.type==="string"?K.type:j.event,V=K.response?.model;if(typeof V==="string"&&V)G=V;switch(B){case"response.output_text.delta":{let W=String(K.delta??"");if(!W)break;yield $.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(K.delta??"");if(!W)break;yield{type:"reasoning-delta",delta:W,id:K.item_id};break}case"response.output_item.added":{let W=K.item;if(!W)break;if(W.type==="function_call"){let H=String(W.id??K.item_id??W.call_id??"");J.set(H,{callId:String(W.call_id??H),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=J.get(String(K.item_id??""));if(!W)break;let H=String(K.delta??"");if(!H)break;yield{type:"tool-call-delta",toolCallId:W.callId,name:W.name,argsDelta:H,...W.namespace?{namespace:W.namespace}:{}};break}case"response.function_call_arguments.done":{let W=String(K.item_id??""),H=J.get(W);if(!H)break;H.done=!0,yield{type:"tool-call",toolCallId:H.callId,name:H.name,args:String(K.arguments??""),...H.namespace?{namespace:H.namespace}:{}};break}case"response.output_item.done":{let W=K.item;if(!W)break;if(W.type==="function_call"){let H=String(W.id??K.item_id??W.call_id??""),U=J.get(H);if(U?.done)break;let L=(typeof W.namespace==="string"?W.namespace:"")||U?.namespace;if(yield{type:"tool-call",toolCallId:String(W.call_id??H),name:String(W.name??U?.name??""),args:String(W.arguments??""),...L?{namespace:L}:{}},U)U.done=!0;break}if(W.type==="tool_search_call"||W.type==="tool_search_output"){if(W.type==="tool_search_call"&&W.arguments!==void 0)X=W.arguments;let H=v5(W);if(H.loaded.length===0&&H.namespaces.length===0)break;let U=String(W.tool_search_call_id??W.id??"");if(Z.has(U))break;Z.add(U);let L=X;X=void 0,yield{type:"tool-search",...H,...L!==void 0&&L!==null?{arguments:L}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(K.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{Y=!0,yield F("stop",KQ(K.response?.usage));break}case"response.incomplete":{Y=!0;let W=KQ(K.response?.usage),H=K.response?.incomplete_details?.reason;if(H==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:y5(K.response?.content_filters),retryable:!1}},yield F("error",W);break}yield F(H==="max_output_tokens"?"length":"stop",W);break}case"response.failed":case"error":{Y=!0;let W=K.response?.error??K.error??K;yield{type:"error",error:b5(W)},yield F("error",KQ(K.response?.usage));break}}if(Y)return}if(!Y)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield F("error",x())}function v5(Q){let $=[],J=[];return mQ(Q.results??Q.tools??Q.loaded??Q.output,$,J,0),{loaded:BQ($),namespaces:BQ(J)}}function mQ(Q,$,J,Z){if(!Array.isArray(Q)||Z>4)return;for(let X of Q){if(typeof X==="string"){$.push(X);continue}if(!X||typeof X!=="object")continue;let Y=X,G=typeof Y.name==="string"?Y.name:typeof Y.tool_name==="string"?Y.tool_name:"",F=Y.tools??Y.functions;if(Array.isArray(F)){if(G)J.push(G);mQ(F,$,J,Z+1);continue}if(G)$.push(G)}}function BQ(Q){return Q.filter(($,J)=>Q.indexOf($)===J)}function y5(Q){if(!Array.isArray(Q))return"The provider's content filter blocked this request.";let J=[];for(let Z of Q){if(!Z||typeof Z!=="object")continue;let X=Z,Y=X.content_filter_results;if(!Y||typeof Y!=="object")continue;for(let[G,F]of Object.entries(Y))if(F&&typeof F==="object"&&F.filtered===!0)J.push(`${G} (${String(X.source_type??"unknown")})`)}return J.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${BQ(J).join(", ")}.`}function b5(Q){let $=typeof Q?.message==="string"?Q.message:"The provider stream failed.",J=String(Q?.code??"").toLowerCase();if(J==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(J==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(J.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function x(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function KQ(Q){if(!Q)return x();let $=Number(Q.input_tokens??0),J=Number(Q.output_tokens??0),Z={inputTokens:$,outputTokens:J,totalTokens:Number(Q.total_tokens??$+J)},X=Q.output_tokens_details?.reasoning_tokens;if(typeof X==="number")Z.reasoningTokens=X;let Y=Q.input_tokens_details?.cached_tokens;if(typeof Y==="number")Z.cachedInputTokens=Y;return Z}async function*pQ(Q){if(!Q)return;let $=Q.getReader(),J=new TextDecoder;try{while(!0){let{done:X,value:Y}=await $.read();if(X)break;if(Y)yield J.decode(Y,{stream:!0})}let Z=J.decode();if(Z)yield Z}finally{$.releaseLock()}}function s(Q){return{responsesUrl:`${Q.base}/responses${Q.query}`,filesUrl:`${Q.base}/files${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,streamIdleTimeoutMs:Q.streamIdleTimeoutMs,streamMaxDurationMs:Q.streamMaxDurationMs,maxToolArgumentChars:Q.maxToolArgumentChars,maxRetries:Q.maxRetries}}async function*o(Q,$,J){let Z=J.parse??cQ,X=$,Y=new Set,G=0,F=!1,j=Math.max(0,Q.maxRetries),K=Q.random??Math.random,B,V=(D)=>{if(!B)return D;let _=r(r(x(),B),D.usage);return B=void 0,{...D,usage:_}},W=()=>V({type:"finish",reason:"aborted",usage:x()}),H=Q.streamIdleTimeoutMs??0,U=Q.streamMaxDurationMs??0,L=Q.maxToolArgumentChars??0,P=Q.now??Date.now,g=P();for(let D=0;;D++){let _=new AbortController,u=J.signal?AbortSignal.any([J.signal,_.signal]):_.signal,$Q;while($Q===void 0)try{let q=[],z=()=>{},C=y(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify(X)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:u,fetchImpl:Q.fetchImpl,sleep:Q.sleep,random:Q.random,now:Q.now,startedAt:g,onRetry:(A)=>{q.push({type:"retry",...A,phase:"request"}),z()}}),R=C.then(()=>!0,()=>!0);for(;;){let A=new Promise((p)=>z=()=>p(!1)),v=await Promise.race([R,A]);if(yield*q.splice(0),v)break}$Q=await C}catch(q){let z=X,C=J.files&&G<hQ?fQ(z,q,J.files).filter((v)=>!Y.has(v)):[];if(C.length>0){G++;let v=M(q).message;for(let p of C)Y.add(p),yield{type:"file-rejected",fileId:p,message:v,...I(q)};X=gQ(z,new Set(C),J.files);continue}let R=F?null:uQ(X,q);if(R){F=!0,X=R;continue}let A=M(q);if(A.code==="aborted"){yield W();return}yield{type:"error",error:A,...I(q)},yield V({type:"finish",reason:"error",usage:x()});return}let w=[],c=!1,m,OQ=!1,k=new Map;try{let q=IQ($Q.body,{idleMs:H,maxMs:U},{idle:()=>{let z=new dQ(H);return _.abort(z),z},max:()=>{let z=new lQ(U);return _.abort(z),z}});for await(let z of Z(pQ(q),{structuredOutput:J.structuredOutput})){if(z.type==="tool-call-delta"){let C=(k.get(z.toolCallId)??0)+z.argsDelta.length;if(k.set(z.toolCallId,C),L>0&&C>L){let R=new iQ(L,z.name);throw _.abort(R),R}yield z;continue}if(z.type==="tool-call")k.delete(z.toolCallId);if(c){yield z.type==="finish"?V(z):z;continue}if(a(z)){c=!0,yield*w.splice(0),yield z;continue}if(z.type==="error")m=z.error;w.push(z)}}catch(q){OQ=q instanceof l;let z=M(q);if(z.code==="aborted"||J.signal?.aborted){yield W();return}if(c){yield{type:"error",error:z},yield V({type:"finish",reason:"error",usage:x()});return}m=z,w.push({type:"error",error:z},{type:"finish",reason:"error",usage:x()})}if(c)return;if(m?.retryable&&D<j&&!J.signal?.aborted){let q={};for(let C of w){if(C.type==="finish")B=r(B??x(),C.usage);if(C.type==="error")q=I(C)}if(k.size>0)yield{type:"tool-call-discard",toolCallIds:[...k.keys()]};let z=d(D,K);yield{type:"retry",attempt:D+1,maxRetries:j,error:m,...q,phase:"stream",timedOut:OQ,delayMs:z,elapsedMs:P()-g};try{await JQ(z,J.signal,Q.sleep)}catch{yield W();return}continue}for(let q of w)yield q.type==="finish"?V(q):q;return}}async function t(Q,$,J="user_data"){let Z=new FormData;if(J)Z.set("purpose",J);Z.set("file",$);let Y=await(await y(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:Z},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl})).json();if(!Y?.id)throw Error("The provider accepted the upload but returned no file id.");return Y.id}function FQ(Q,$){let{capabilities:J}=$,Z={model:$.model,input:h5(Q.messages,J,Q.tools),stream:!0};if(Q.systemPrompt)Z.instructions=Q.systemPrompt;let X=i5(Q.tools,J);if(X.length>0){if(Z.tools=X,!J.parallelToolCalls)Z.parallel_tool_calls=!1;if(Q.toolChoice!==void 0)Z.tool_choice=typeof Q.toolChoice==="string"?Q.toolChoice:{type:"function",name:Q.toolChoice.name}}if(Q.output)Z.text={format:{type:"json_schema",name:Q.output.name,schema:Q.output.schema,strict:Q.output.strict}};if(Q.reasoning&&J.reasoning)Z.reasoning=Q.reasoning==="none"?{effort:"none"}:{effort:Q.reasoning,summary:"auto"};if(typeof Q.temperature==="number")Z.temperature=Q.temperature;if(typeof Q.maxOutputTokens==="number")Z.max_output_tokens=Q.maxOutputTokens;if(Q.promptCacheKey)Z.prompt_cache_key=Q.promptCacheKey;return Z}function h5(Q,$,J){let Z=[],X=new Map;if($.toolSearch){for(let Y of J??[])if(e(Y))X.set(Y.name,Y)}for(let Y of Q){let G=Y.role,F=!p5.has(Y.finishReason),j=[],K=()=>{if(j.length===0)return;Z.push({type:"message",role:G,content:j}),j=[]};for(let B of Y.content??[])switch(B.type){case"text":{if(!B.text)break;j.push(T(G,B.text));break}case"output":{if(B.partial)break;j.push(T(G,JSON.stringify(B.value)));break}case"file":{if(G==="assistant")break;let V=UQ(B);if(!$.fileInput){if(V)j.push(T(G,f(B,!1)));break}if(LQ(B,V),B.providerRejected){if(V)j.push(T(G,f(B,!1)));j.push(T(G,h(B.name)));break}if(V)j.push(T(G,f(B,!!B.fileId)));if(B.fileId)j.push(u5(B));break}case"reasoning":{if(K(),!F)break;let V=d5(B);if(V)Z.push(V);break}case"tool-call":{if(B.partial)break;if(K(),$.toolSearch&&Array.isArray(B.toolSearches))for(let W of B.toolSearches)Z.push(...l5(W,J??[]));let V={type:"function_call",call_id:B.toolCallId,name:String(B.name),arguments:JSON.stringify(B.input??{})};if(B.namespace&&X.has(B.namespace))V.namespace=B.namespace;Z.push(V);break}case"tool-result":{K(),Z.push({type:"function_call_output",call_id:B.toolCallId,output:qQ(B)});break}}K()}return g5(Z)}var f5="No result was recorded for this tool call. Assume it did not complete.";function g5(Q){let $=new Set,J=new Set,Z=[];for(let Y of Q){if(Y.type==="function_call"){let G=String(Y.call_id);if($.has(G))continue;$.add(G)}else if(Y.type==="function_call_output"){let G=String(Y.call_id);if(!$.has(G)||J.has(G))continue;J.add(G)}Z.push(Y)}if(J.size===$.size)return Z;let X=[];for(let Y of Z){if(X.push(Y),Y.type!=="function_call")continue;let G=String(Y.call_id);if(J.has(G))continue;J.add(G),X.push({type:"function_call_output",call_id:G,output:f5})}return X}function T(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function UQ(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(jQ)?$:void 0}function f(Q,$){let J=[`id=${JSON.stringify(Q.attachmentId)}`];if(Q.name)J.push(`name=${JSON.stringify(Q.name)}`);if(Q.mimeType)J.push(`mimeType=${JSON.stringify(Q.mimeType)}`);let Z=`attachment ${J.join(" ")}`;return $?`[${Z}]`:`[${Z} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function u5(Q){return{type:zQ(Q)?"input_image":"input_file",file_id:Q.fileId}}function zQ(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return $?$.startsWith("image/")&&$!=="image/svg+xml":c5(Q.name)}function LQ(Q,$){if(Q.fileId?.startsWith(jQ))throw Error(`FilePart.fileId holds a gemi attachment id (${Q.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(!Q.fileId&&!$)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.")}function c5(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&m5.has($[1])}var m5=new Set(["jpeg","jpg","png","gif","webp"]),p5=new Set(["error","aborted","interrupted"]);function d5(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function qQ(Q){if(Q.status==="ok"){let $=Q.modelOutput!==void 0?Q.modelOutput:Q.output;return typeof $==="string"?$:JSON.stringify($??null)}if(Q.status==="running"){let $=Q.job?.summary===void 0?"":` Started with: ${JSON.stringify(Q.job.summary)}.`;return`Started background job ${Q.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.${$}`}if(Q.status==="denied"){let $=Q.reason?` Reason given: ${Q.reason}`:"";if(Q.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${$}`;if(Q.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${Q.error?.code??"unknown"}): ${Q.error?.message??"no message"}`}function l5(Q,$){let J=new Set(nQ(Q?.loaded)),Z=nQ(Q?.namespaces),X=new Set(Z),Y=[];for(let F of $)if(e(F)){if(!X.has(F.name))continue;let j=F.tools.filter((K)=>J.size===0||J.has(K.name));if(j.length===0)continue;Y.push({type:"namespace",name:F.name,description:F.description,tools:j.map((K)=>E(K,!0))})}else if(F.deferred&&J.has(F.name))Y.push(E(F,!0));if(Y.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:Q.arguments&&typeof Q.arguments==="object"?Q.arguments:{paths:Z.length>0?Z:[...J]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:Y}]}function nQ(Q){return Array.isArray(Q)?Q.filter(($)=>typeof $==="string"):[]}function e(Q){return Array.isArray(Q.tools)}function i5(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let X=[];for(let Y of Q)if(e(Y))for(let G of Y.tools)X.push(E(G,!1));else X.push(E(Y,!1));return X}let J=[],Z=!1;for(let X of Q)if(e(X)){let Y=X.tools.map((G)=>{if(G.deferred)Z=!0;return E(G,!0)});J.push({type:"namespace",name:X.name,description:X.description,tools:Y})}else{if(X.deferred)Z=!0;J.push(E(X,!0))}if(Z)J.push({type:"tool_search"});return J}function E(Q,$){let J={type:"function",name:Q.name,description:Q.description,parameters:Q.parameters,strict:Q.strict};if($&&Q.deferred)J.defer_loading=!0;return J}var n5=64000;function rQ(Q,$){let J={model:$.model,max_tokens:Q.maxOutputTokens??n5,messages:X6(Q.messages,$.capabilities),stream:!0},Z=Q.output,X=!!Z?.strict&&!$6(Z.schema),Y=Z&&!X?J6(Z.schema):void 0,G=[Q.systemPrompt,Y].filter(Boolean);if(G.length>0)J.system=[{type:"text",text:G.join(`
|
|
6
|
-
|
|
7
|
-
`)}];let F=$.capabilities.reasoning?Q.reasoning:void 0;if(F==="none"){if(/^claude-sonnet-5-5(?:-\d{8})?$/.test($.modelId))J.thinking={type:"between_tools"};J.output_config={effort:"low"}}else if(F)J.thinking={type:"adaptive",display:"summarized"},J.output_config={effort:a5(F,$.modelId)};else if($.capabilities.reasoning&&r5(J.messages))J.thinking={type:"adaptive"};if(J.thinking?.type==="adaptive"&&$.blockBinding)J.thinking.block_binding={prefix_mismatch_behavior:"drop_block"};if(Z&&X)J.output_config={...J.output_config,format:{type:"json_schema",schema:Q6(Z.schema)}};let j=U6(Q.tools);if(j.length>0){J.tools=j;let K=Z6(Q.toolChoice,$.forcedToolChoice);if(!$.capabilities.parallelToolCalls)K.disable_parallel_tool_use=!0;if(Q.toolChoice!==void 0||K.disable_parallel_tool_use)J.tool_choice=K}return s5(J)}function r5(Q){return Q.some(($)=>$.content.some((J)=>J.type==="thinking"||J.type==="redacted_thinking"))}var DQ="thinking-binding-controls-2026-08-01";function aQ(Q){if(/bound to a different conversation|Invalid `signature` in `thinking` block/i.test(Q))return"thinking";if(/schema is too complex/i.test(Q))return"schema";return}function sQ(Q){let $=[];for(let J of Q.messages){let Z=J.content.filter((Y)=>Y.type!=="thinking"&&Y.type!=="redacted_thinking");if(Z.length===0)continue;let X=$.at(-1);if(X?.role===J.role)X.content.push(...Z);else $.push({role:J.role,content:Z})}return{...Q,messages:$}}function a5(Q,$){if(Q==="none"||Q==="minimal")return"low";if(Q==="xhigh"&&/^claude-(?:opus|sonnet)-4-6(?:-|$)/.test($))return"high";return Q}function s5(Q){let $=(Z)=>{if(Z)Z.cache_control={type:"ephemeral"}};$(Q.tools?.at(-1)),$(Q.system?.at(-1));let J=Q.messages.at(-1)?.content??[];return $([...J].reverse().find((Z)=>Z.type!=="thinking"&&Z.type!=="redacted_thinking")),Q}var o5=new Set(["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","maxItems","uniqueItems"]),t5=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),e5=/\\[1-9]|\(\?<?[=!]|\\[bB]/,oQ=new Set(["properties","patternProperties","$defs","definitions"]);function Q6(Q){let $=(J)=>{if(Array.isArray(J))return J.map($);if(!S(J))return J;let Z={},X=[];for(let[Y,G]of Object.entries(J)){if(o5.has(Y)||Y==="minItems"&&typeof G==="number"&&G>1||Y==="format"&&typeof G==="string"&&!t5.has(G)||Y==="pattern"&&typeof G==="string"&&e5.test(G)){X.push(`${Y}: ${JSON.stringify(G)}`);continue}Z[Y]=oQ.has(Y)&&S(G)?Object.fromEntries(Object.entries(G).map(([j,K])=>[j,$(K)])):$(G)}if(X.length>0){let Y=`{${X.join(", ")}}`;Z.description=typeof Z.description==="string"?`${Z.description} ${Y}`:Y}if(Z.type==="object"||S(Z.properties))Z.additionalProperties=!1;return Z};return $(Q)}function $6(Q){let $=0,J=0,Z=(X)=>{if(Array.isArray(X))return X.forEach(Z);if(!S(X))return;if(Array.isArray(X.anyOf)||Array.isArray(X.type))J++;if(S(X.properties)){let Y=new Set(Array.isArray(X.required)?X.required:[]);$+=Object.keys(X.properties).filter((G)=>!Y.has(G)).length}for(let[Y,G]of Object.entries(X))if(oQ.has(Y)&&S(G))Object.values(G).forEach(Z);else Z(G)};return Z(Q),$>24||J>16}function J6(Q){return`Answer with only a JSON value (no prose, no code fence) that matches this JSON schema:
|
|
8
|
-
${JSON.stringify(Q)}`}function Z6(Q,$){if(Q==="none")return{type:"none"};if(Q==="required")return $?{type:"any"}:{type:"auto"};if(Q&&typeof Q==="object")return $?{type:"tool",name:Q.name}:{type:"auto"};return{type:"auto"}}function X6(Q,$){let J=[],Z=new Map;for(let B of Q){let V=B.role==="assistant"?"assistant":"user";J.push("step-end");for(let W of B.content??[])switch(W.type){case"text":{if(V==="assistant"?!!W.text:!!W.text?.trim())J.push({role:V,block:{type:"text",text:W.text}});break}case"output":{if(W.partial)break;let H=W.text??JSON.stringify(W.value);J.push({role:V,block:{type:"text",text:H}});break}case"file":{if(V==="assistant")break;for(let H of B6(W,$))J.push({role:V,block:H});break}case"reasoning":{let H=V==="assistant"?K6(W):void 0;if(H)J.push({role:V,block:H});break}case"tool-call":{if(W.partial)break;J.push({role:"assistant",block:{type:"tool_use",id:W.toolCallId,name:String(W.name),input:S(W.input)?W.input:{}}});break}case"tool-result":{if(J.push("step-end"),Z.has(W.toolCallId))break;Z.set(W.toolCallId,{type:"tool_result",tool_use_id:W.toolCallId,content:qQ(W),...W.status==="error"?{is_error:!0}:{}});break}}}let X=[],Y=(B,V)=>{let W=X[X.length-1];if(W&&W.role===B)W.content.push(V);else X.push({role:B,content:[V]})},G=new Set,F=[],j=!1,K=()=>{for(let B of F)Y("user",Z.get(B)??V6(B));F=[],j=!1};for(let B of J){if(B==="step-end"){j=!0;continue}let{role:V,block:W}=B;if(j||V==="user")K();if(W.type==="tool_use"){let H=String(W.id);if(G.has(H))continue;G.add(H),F.push(H)}Y(V,W)}if(K(),X[0]?.role==="assistant")X.unshift({role:"user",content:[{type:"text",text:Y6}]});if(X.at(-1)?.role==="assistant")X.push({role:"user",content:[{type:"text",text:G6}]});return X}var Y6="(The conversation continues from an earlier point.)",G6="Continue.",W6="No result was recorded for this tool call. Assume it did not complete.";function V6(Q){return{type:"tool_result",tool_use_id:Q,content:W6}}function K6(Q){let $=Q.providerMetadata?.anthropic;if(!S($))return;if($.type==="thinking"&&typeof $.signature==="string")return{type:"thinking",thinking:Q.text??"",signature:$.signature};if($.type==="redacted_thinking"&&typeof $.data==="string")return{type:"redacted_thinking",data:$.data};return}function B6(Q,$){let J=UQ(Q),Z=(Y)=>J?[{type:"text",text:f(Q,Y)}]:[];if(!$.fileInput)return Z(!1);if(LQ(Q,J),!Q.fileId)return Z(!1);let X=Q.providerRejected?void 0:j6(Q);if(!X)return[...Z(!1),{type:"text",text:h(Q.name)}];return[...Z(!0),{type:X,source:{type:"file",file_id:Q.fileId}}]}var H6=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function j6(Q){let $=Q.mimeType?.trim().toLowerCase()??"";if(zQ(Q))return!$||H6.has($)?"image":void 0;if($)return $==="application/pdf"||$==="text/plain"?"document":void 0;return/\.(pdf|txt)$/i.test(Q.name??"")?"document":void 0}function S(Q){return!!Q&&typeof Q==="object"&&!Array.isArray(Q)}function F6(Q){return Array.isArray(Q.tools)}function U6(Q){let $=[];for(let J of Q??[])for(let Z of F6(J)?J.tools:[J])$.push({name:Z.name,description:Z.description,input_schema:Z.parameters,eager_input_streaming:!0});return $}async function*$5(Q,$={}){let J=new Map,Z=[],X,Y={},G,F,j=!1,K=(B)=>({type:"finish",reason:B,usage:C6(Y),...X?{model:X}:{}});for await(let B of HQ(Q)){let V;try{V=JSON.parse(B.data)}catch{continue}switch(typeof V.type==="string"?V.type:B.event){case"message_start":{let H=V.message??{};if(typeof H.model==="string"&&H.model)X=H.model;Y=Q5(Y,H.usage);break}case"content_block_start":{let H=Number(V.index),U=V.content_block??{},L={type:String(U.type??""),id:typeof U.id==="string"?U.id:void 0,name:typeof U.name==="string"?U.name:void 0,args:"",signature:typeof U.signature==="string"?U.signature:""};if(J.set(H,L),L.type==="redacted_thinking")yield{type:"reasoning-delta",delta:"",providerMetadata:{anthropic:{type:"redacted_thinking",data:String(U.data??"")}}};if(L.type==="text"&&typeof U.text==="string"&&U.text)yield eQ(U.text,$);break}case"content_block_delta":{let H=J.get(Number(V.index)),U=V.delta??{};if(!H)break;if(U.type==="text_delta"){let L=String(U.text??"");if(L)yield eQ(L,$)}else if(U.type==="thinking_delta"){let L=String(U.thinking??"");if(L)yield{type:"reasoning-delta",delta:L}}else if(U.type==="signature_delta")H.signature+=String(U.signature??"");else if(U.type==="input_json_delta"&&H.type==="tool_use"){let L=String(U.partial_json??"");if(!L)break;H.args+=L,yield{type:"tool-call-delta",toolCallId:H.id??"",name:H.name??"",argsDelta:L}}break}case"content_block_stop":{let H=Number(V.index),U=J.get(H);if(J.delete(H),U?.type==="thinking")yield{type:"reasoning-delta",delta:"",providerMetadata:{anthropic:{type:"thinking",signature:U.signature}}};if(U?.type==="tool_use")if(U.args||="{}",z6(U.args))yield tQ(U);else Z.push(U);break}case"message_delta":{if(typeof V.delta?.stop_reason==="string")G=V.delta.stop_reason;if(V.delta?.stop_details)F=V.delta.stop_details;Y=Q5(Y,V.usage);break}case"message_stop":{if(j=!0,G==="refusal"){yield{type:"error",error:q6(F)},yield K("error");break}let H=L6(G);if(Z.length>0&&H==="length")yield{type:"tool-call-discard",toolCallIds:Z.map((U)=>U.id??"")};else for(let U of Z)yield tQ(U);yield K(H);break}case"error":{j=!0,yield{type:"error",error:D6(V.error??V)},yield K("error");break}}if(j)return}yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield K("error")}function tQ(Q){return{type:"tool-call",toolCallId:Q.id??"",name:Q.name??"",args:Q.args}}function z6(Q){try{return JSON.parse(Q),!0}catch{return!1}}function eQ(Q,$){return $.structuredOutput?{type:"output-delta",delta:Q}:{type:"text-delta",delta:Q}}function L6(Q){if(Q==="max_tokens"||Q==="model_context_window_exceeded")return"length";return"stop"}function q6(Q){let $=typeof Q?.explanation==="string"?Q.explanation:"",J=typeof Q?.category==="string"?` (${Q.category})`:"";return{code:"content_filtered",message:$||`The model declined to answer${J}.`,retryable:!1}}function D6(Q){let $=String(Q?.type??"").toLowerCase(),J=typeof Q?.message==="string"?Q.message:"The provider stream failed.";if($==="rate_limit_error")return{code:"rate_limited",message:J,retryable:!0};if($==="invalid_request_error"||$==="request_too_large")return{code:/prompt is too long|request_too_large/i.test(`${$} ${J}`)?"context_length_exceeded":"provider_error",message:J,retryable:!1};if($==="authentication_error"||$==="permission_error"||$==="billing_error"||$==="not_found_error")return{code:"provider_error",message:J,retryable:!1};return{code:"provider_error",message:J,retryable:!0}}function Q5(Q,$){if(!$||typeof $!=="object")return Q;let J={...Q};for(let X of["input_tokens","output_tokens","cache_creation_input_tokens","cache_read_input_tokens"])if(typeof $[X]==="number")J[X]=$[X];let Z=$.output_tokens_details?.thinking_tokens;if(typeof Z==="number")J.thinking_tokens=Z;return J}function C6(Q){if(!Q)return x();let{cache_read_input_tokens:$,cache_creation_input_tokens:J}=Q,Z=(Q.input_tokens??0)+($??0)+(J??0),X=Q.output_tokens??0,Y={inputTokens:Z,outputTokens:X,totalTokens:Z+X};if(typeof $==="number")Y.cachedInputTokens=$;if(typeof J==="number")Y.cacheWriteInputTokens=J;if(typeof Q.thinking_tokens==="number")Y.reasoningTokens=Q.thinking_tokens;return Y}function CQ(Q){let $=PQ(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let J=N6($);if(J?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:J.major>1,toolSearch:J5(J)};if(J?.kind==="gpt")return{reasoning:J.major>=5,structuredOutput:J.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:J.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:J5(J)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function J5(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function NQ(Q){let $=PQ(Q),J=/^claude-(?:opus|sonnet|haiku)-4(?:-(\d{1,2}))?(?:-\d{8})?$/.exec($);return{reasoning:!(/^claude-(?:3|2|instant)/.test($)||!!J&&Number(J[1]??0)<=5),structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!1}}function Z5(Q){let $=PQ(Q);return/^claude-(?:3|2|instant)/.test($)||/^claude-(?:opus|sonnet|haiku)-4(?:-|$)/.test($)||/^claude-(?:opus|sonnet|fable|mythos)-5(?:-\d{8})?$/.test($)||/^claude-haiku-5-5(?:-\d{8})?$/.test($)}function PQ(Q){return Q.trim().toLowerCase()}function N6(Q){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(Q);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let J=/^o(\d+)(?:[-.]|$)/.exec(Q);if(J?.[1])return{kind:"o",major:Number(J[1]),minor:0};return null}function N(Q){return typeof process>"u"?void 0:process.env?.[Q]}var P6="preview";function X5(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function M6(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}function MQ(Q,$={}){return{base:(Q.baseURL??N("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=Q.apiKey??N("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,streamIdleTimeoutMs:Q.streamIdleTimeoutMs??120000,streamMaxDurationMs:Q.streamMaxDurationMs??300000,maxToolArgumentChars:Q.maxToolArgumentChars??0,maxRetries:Q.maxRetries??2}}function Y5(Q){let $=Q.baseURL??Q.endpoint??N("AZURE_OPENAI_ENDPOINT");if($)return X5($);let J=Q.resourceName??N("AZURE_OPENAI_RESOURCE_NAME")??N("AZURE_RESOURCE_NAME");return J?X5(`https://${J.trim()}.cognitiveservices.azure.com`):""}function xQ(Q,$={}){let J=Q.apiVersion??N("AZURE_OPENAI_API_VERSION")??P6;return{base:`${Y5(Q)}${M6(J)}`,query:`?api-version=${encodeURIComponent(J)}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let Z=Q.apiKey??N("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,streamIdleTimeoutMs:Q.streamIdleTimeoutMs??120000,streamMaxDurationMs:Q.streamMaxDurationMs??300000,maxToolArgumentChars:Q.maxToolArgumentChars??0,maxRetries:Q.maxRetries??2}}var x6="2026-10-21";function G5(Q,$={}){let J=Q.baseURL??N("ANTHROPIC_BASE_URL")??"https://api.anthropic.com";return V5(J,Q,$,async()=>{let Z=Q.workspaceId??N("ANTHROPIC_WORKSPACE_ID"),X=Z?{"anthropic-workspace-id":Z}:{},Y=Q.apiKey??N("ANTHROPIC_API_KEY");if(Y)return{"x-api-key":Y,...X};let G=N("ANTHROPIC_AUTH_TOKEN");return G?{authorization:`Bearer ${G}`,...X}:X})}function W5(Q,$={}){let J=Q.resourceName??N("ANTHROPIC_FOUNDRY_RESOURCE"),Z=Q.baseURL??Q.endpoint??N("ANTHROPIC_FOUNDRY_BASE_URL")??(J?`https://${J.trim()}.services.ai.azure.com/anthropic`:"");if(!Z.trim())throw Error("AzureAnthropicProvider has no Foundry endpoint. Set `endpoint` (the deployment's Target URI without `/v1/messages`, e.g. `https://<resource>.services.ai.azure.com/anthropic`) or `resourceName`, or the ANTHROPIC_FOUNDRY_BASE_URL or ANTHROPIC_FOUNDRY_RESOURCE environment variable.");return V5(Z,Q,$,async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`};let X=Q.apiKey??N("ANTHROPIC_FOUNDRY_API_KEY");return X?{"api-key":X}:{}})}function V5(Q,$,J,Z){return{base:`${Q.trim().replace(/\/+$/,"").replace(/\/v1$/,"")}/v1`,query:"",headers:async()=>({...await Z(),"anthropic-version":x6,...$.headers}),timeoutMs:$.timeoutMs??J.timeoutMs??120000,streamIdleTimeoutMs:$.streamIdleTimeoutMs??120000,streamMaxDurationMs:$.streamMaxDurationMs??300000,maxToolArgumentChars:$.maxToolArgumentChars??0,maxRetries:$.maxRetries??2}}function K5(Q,$={}){return{...xQ(Q,$),base:`${Y5(Q)}/v1`,query:""}}class QQ{static models(){return[]}normalizeError(Q){return M(Q)}}var B5=["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 H5 extends QQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=CQ(Q),this.config=$}static model(Q,$){return new H5(Q,$)}static models(){return B5}stream(Q){let $=FQ(Q,{model:this.model,capabilities:this.capabilities});return o(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output),files:GQ(Q.messages)})}upload(Q){return t(this.endpoint(),Q)}endpoint(){return s(MQ(this.config))}get realtime(){return new n(MQ(this.config,{timeoutMs:XQ}),{model:this.model})}}var _6=["claude-opus-5-5","claude-sonnet-5-5","claude-haiku-5-5","claude-fable-5-2","claude-fable-5-1","claude-opus-5","claude-sonnet-5","claude-fable-5","claude-opus-4-8","claude-sonnet-4-6","claude-haiku-4-5"];class _Q extends QQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=NQ(Q),this.config=$}static model(Q,$){return new _Q(Q,$)}static models(){return _6}stream(Q){return this.send(Q)}async*send(Q){let $=Q,J=!1,Z=new Set;for(;;){let X=this.request($);if(J)X=sQ(X);let Y,G=!1;for await(let F of o(this.endpointFor(X),X,{signal:Q.signal,structuredOutput:Boolean(Q.output),parse:$5})){if(Y)continue;if(!G&&F.type==="error"&&F.status===400){let j=aQ(F.error.message);if(j&&!Z.has(j)){Z.add(j),Y=j;continue}}if(a(F))G=!0;yield F}if(!Y)return;if(Y==="thinking")J=!0;else if($.output)$={...$,output:{...$.output,strict:!1}}}}request(Q){return rQ(Q,{model:this.deployment(),modelId:this.model,capabilities:this.capabilities,forcedToolChoice:Z5(this.model),blockBinding:this.bindsThinking()})}endpointFor(Q){let $=this.endpoint();if(!(Q.thinking?.type==="adaptive"&&Q.thinking.block_binding))return $;return{...$,headers:async()=>{let Z=await $.headers(),X=Z["anthropic-beta"];return{...Z,"anthropic-beta":X?`${X},${DQ}`:DQ}}}}bindsThinking(){return!0}deployment(){return this.model}upload(Q){return t(this.endpoint(),Q,null)}endpoint(){return j5(G5(this.config))}}function j5(Q){return{...s(Q),responsesUrl:`${Q.base}/messages`}}class F5 extends _Q{constructor(Q,$={}){super(Q,$);this.capabilities={...NQ(Q),fileInput:!1}}static model(Q,$){return new F5(Q,$)}upload(Q){return Promise.reject(Error("AzureAnthropicProvider does not upload files: the Files API is not available on Azure-hosted Foundry deployments. The file is still stored by gemi and named to the model by its attachment id."))}deployment(){return this.config.deployment??this.model}bindsThinking(){return!1}endpoint(){return j5(W5(this.config))}}class U5 extends QQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=CQ(Q),this.config=$}static model(Q,$){return new U5(Q,$)}static models(){return B5}stream(Q){let $=FQ(Q,{model:this.deployment(),capabilities:this.capabilities});return o(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output),files:GQ(Q.messages)})}upload(Q){return t(this.endpoint(),Q,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return s(xQ(this.config))}get realtime(){return new n(K5(this.config,{timeoutMs:XQ}),{model:this.deployment(),callFlow:"ephemeral"})}}
|
|
9
|
-
export{MQ as ca,xQ as da,y as ea,ZQ as fa,P5 as ga,YQ as ha,b as ia,n as ja,S5 as ka,QQ as la,H5 as ma,_Q as na,F5 as oa,U5 as pa};
|
|
10
|
-
|
|
11
|
-
//# debugId=DB3F0DE4EF0A1A8A64756E2164756E21
|
package/dist/chunk-4q59y78y.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Ke as o}from"./chunk-09hzyf9g.js";import{Le as i}from"./chunk-3830ee5d.js";import{Xk as t}from"./chunk-24tj4dzx.js";import{$l as r}from"./chunk-65btke6p.js";class n extends i{register(){this.app.singleton(r,()=>new r(t(o(),this.app.config.get("translation",{}))))}}
|
|
3
|
-
export{n as pb};
|
|
4
|
-
|
|
5
|
-
//# debugId=DA7ED4853CEC931064756E2164756E21
|