gemi 0.236.2 → 0.237.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.map +1 -1
- package/dist/ai/AgentProvider.d.ts +22 -0
- package/dist/ai/AgentProvider.d.ts.map +1 -1
- package/dist/ai/FallbackProvider.d.ts +6 -0
- package/dist/ai/FallbackProvider.d.ts.map +1 -1
- package/dist/ai/ImageModel.d.ts.map +1 -1
- package/dist/ai/contextCompaction.d.ts.map +1 -1
- package/dist/ai/generate.d.ts.map +1 -1
- package/dist/ai/index.d.ts +1 -1
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +40 -40
- package/dist/ai/index.js.map +4 -4
- package/dist/ai/runtime.d.ts +8 -0
- package/dist/ai/runtime.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 +13 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/usageLimits.d.ts +12 -1
- package/dist/ai/usageLimits.d.ts.map +1 -1
- package/dist/ai/usageMeter.d.ts +67 -10
- package/dist/ai/usageMeter.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-gftdag48.js → chunk-07fy1618.js} +2 -2
- package/dist/{chunk-gftdag48.js.map → chunk-07fy1618.js.map} +1 -1
- package/dist/{chunk-ca5kp6cn.js → chunk-0kjcd94c.js} +2 -2
- package/dist/{chunk-ca5kp6cn.js.map → chunk-0kjcd94c.js.map} +1 -1
- package/dist/{chunk-naj8bmj5.js → chunk-0xmk4jyj.js} +2 -2
- package/dist/{chunk-naj8bmj5.js.map → chunk-0xmk4jyj.js.map} +1 -1
- package/dist/{chunk-hprgj13q.js → chunk-185k67yf.js} +2 -2
- package/dist/{chunk-hprgj13q.js.map → chunk-185k67yf.js.map} +1 -1
- package/dist/{chunk-p4p8xy74.js → chunk-2d757e1s.js} +2 -2
- package/dist/{chunk-p4p8xy74.js.map → chunk-2d757e1s.js.map} +1 -1
- package/dist/{chunk-h1wmpa03.js → chunk-2g1h9ktj.js} +2 -2
- package/dist/{chunk-h1wmpa03.js.map → chunk-2g1h9ktj.js.map} +1 -1
- package/dist/{chunk-4vn8gyzy.js → chunk-2gj2nhve.js} +2 -2
- package/dist/{chunk-4vn8gyzy.js.map → chunk-2gj2nhve.js.map} +1 -1
- package/dist/{chunk-x6a5qxpa.js → chunk-2h1ta6cv.js} +2 -2
- package/dist/{chunk-x6a5qxpa.js.map → chunk-2h1ta6cv.js.map} +1 -1
- package/dist/chunk-2mjtssv3.js +5 -0
- package/dist/{chunk-0hy5dsbt.js.map → chunk-2mjtssv3.js.map} +1 -1
- package/dist/{chunk-m3fbewhz.js → chunk-3jr6d0cb.js} +3 -3
- package/dist/{chunk-m3fbewhz.js.map → chunk-3jr6d0cb.js.map} +1 -1
- package/dist/{chunk-17bva6b1.js → chunk-3p4wdpag.js} +2 -2
- package/dist/{chunk-17bva6b1.js.map → chunk-3p4wdpag.js.map} +1 -1
- package/dist/{chunk-gjzwrx5g.js → chunk-5c538k7m.js} +2 -2
- package/dist/{chunk-gjzwrx5g.js.map → chunk-5c538k7m.js.map} +1 -1
- package/dist/{chunk-3y1h3ncf.js → chunk-5fxdjmgd.js} +2 -2
- package/dist/{chunk-3y1h3ncf.js.map → chunk-5fxdjmgd.js.map} +1 -1
- package/dist/{chunk-9sbhqscs.js → chunk-5kjnbmwp.js} +3 -3
- package/dist/{chunk-9sbhqscs.js.map → chunk-5kjnbmwp.js.map} +1 -1
- package/dist/{chunk-sh2bd09k.js → chunk-5nn0pgxg.js} +2 -2
- package/dist/{chunk-sh2bd09k.js.map → chunk-5nn0pgxg.js.map} +1 -1
- package/dist/{chunk-qvn0w2rt.js → chunk-5pbjc6tm.js} +2 -2
- package/dist/{chunk-qvn0w2rt.js.map → chunk-5pbjc6tm.js.map} +1 -1
- package/dist/{chunk-x2dmgge8.js → chunk-6wv3k8ap.js} +2 -2
- package/dist/{chunk-x2dmgge8.js.map → chunk-6wv3k8ap.js.map} +1 -1
- package/dist/{chunk-px9h2qgv.js → chunk-7159w4qq.js} +3 -3
- package/dist/{chunk-px9h2qgv.js.map → chunk-7159w4qq.js.map} +1 -1
- package/dist/{chunk-jssjfvsz.js → chunk-768yza4f.js} +2 -2
- package/dist/{chunk-jssjfvsz.js.map → chunk-768yza4f.js.map} +1 -1
- package/dist/{chunk-fbk79z21.js → chunk-7b4tsj9x.js} +2 -2
- package/dist/{chunk-fbk79z21.js.map → chunk-7b4tsj9x.js.map} +1 -1
- package/dist/{chunk-kak3vc71.js → chunk-8591j0cj.js} +2 -2
- package/dist/{chunk-kak3vc71.js.map → chunk-8591j0cj.js.map} +1 -1
- package/dist/{chunk-1mb7kaxs.js → chunk-89jc9yg9.js} +3 -3
- package/dist/{chunk-1mb7kaxs.js.map → chunk-89jc9yg9.js.map} +1 -1
- package/dist/{chunk-1w6ra6jc.js → chunk-9447c20x.js} +1 -1
- package/dist/{chunk-np6vee9d.js → chunk-96v1bwg4.js} +3 -3
- package/dist/{chunk-np6vee9d.js.map → chunk-96v1bwg4.js.map} +1 -1
- package/dist/{chunk-a119av2z.js → chunk-9a3wbbr6.js} +2 -2
- package/dist/{chunk-a119av2z.js.map → chunk-9a3wbbr6.js.map} +1 -1
- package/dist/{chunk-n4kz9vft.js → chunk-9ey725pw.js} +1 -1
- package/dist/chunk-a3s6cp49.js +48 -0
- package/dist/chunk-a3s6cp49.js.map +26 -0
- package/dist/{chunk-yahabnz4.js → chunk-a9p3djqm.js} +3 -3
- package/dist/{chunk-yahabnz4.js.map → chunk-a9p3djqm.js.map} +1 -1
- package/dist/{chunk-ka8dzc6q.js → chunk-ack021d9.js} +2 -2
- package/dist/{chunk-ka8dzc6q.js.map → chunk-ack021d9.js.map} +1 -1
- package/dist/{chunk-4n3jva4e.js → chunk-b9gf8sqq.js} +2 -2
- package/dist/{chunk-4n3jva4e.js.map → chunk-b9gf8sqq.js.map} +1 -1
- package/dist/{chunk-73541m4t.js → chunk-bcb1dwhb.js} +4 -4
- package/dist/{chunk-73541m4t.js.map → chunk-bcb1dwhb.js.map} +1 -1
- package/dist/{chunk-4800w7qx.js → chunk-bg0da5pd.js} +3 -3
- package/dist/{chunk-4800w7qx.js.map → chunk-bg0da5pd.js.map} +3 -3
- package/dist/{chunk-9kt24ctk.js → chunk-bhycdjcv.js} +2 -2
- package/dist/{chunk-9kt24ctk.js.map → chunk-bhycdjcv.js.map} +1 -1
- package/dist/{chunk-2kzysesp.js → chunk-c3c37k46.js} +3 -3
- package/dist/{chunk-2kzysesp.js.map → chunk-c3c37k46.js.map} +1 -1
- package/dist/{chunk-t6x1r5n6.js → chunk-c6zpn9yp.js} +3 -3
- package/dist/{chunk-t6x1r5n6.js.map → chunk-c6zpn9yp.js.map} +1 -1
- package/dist/{chunk-y2vayxcd.js → chunk-dj5d9wcc.js} +2 -2
- package/dist/{chunk-y2vayxcd.js.map → chunk-dj5d9wcc.js.map} +1 -1
- package/dist/{chunk-5exrgw07.js → chunk-dmzgw2d8.js} +3 -3
- package/dist/{chunk-5exrgw07.js.map → chunk-dmzgw2d8.js.map} +1 -1
- package/dist/chunk-ejf6sz1d.js +5 -0
- package/dist/{chunk-gvr7cwxn.js.map → chunk-ejf6sz1d.js.map} +3 -3
- package/dist/{chunk-74dzzd64.js → chunk-fb0bazw9.js} +2 -2
- package/dist/{chunk-74dzzd64.js.map → chunk-fb0bazw9.js.map} +1 -1
- package/dist/{chunk-8476xvk9.js → chunk-fgnpyj44.js} +2 -2
- package/dist/{chunk-8476xvk9.js.map → chunk-fgnpyj44.js.map} +1 -1
- package/dist/{chunk-1xz206e1.js → chunk-fp31t0ey.js} +3 -3
- package/dist/{chunk-1xz206e1.js.map → chunk-fp31t0ey.js.map} +1 -1
- package/dist/{chunk-8yb9jrj5.js → chunk-fp6mxxkq.js} +2 -2
- package/dist/{chunk-8yb9jrj5.js.map → chunk-fp6mxxkq.js.map} +1 -1
- package/dist/{chunk-hgwkxn0g.js → chunk-fx45rbbn.js} +2 -2
- package/dist/{chunk-hgwkxn0g.js.map → chunk-fx45rbbn.js.map} +1 -1
- package/dist/{chunk-ts75gcfd.js → chunk-g29wz7h7.js} +2 -2
- package/dist/{chunk-k2mpxwh2.js.map → chunk-g29wz7h7.js.map} +1 -1
- package/dist/{chunk-byv7b79h.js → chunk-gakdsme3.js} +2 -2
- package/dist/{chunk-byv7b79h.js.map → chunk-gakdsme3.js.map} +1 -1
- package/dist/{chunk-28yb0q82.js → chunk-gj4hg8xk.js} +2 -2
- package/dist/{chunk-28yb0q82.js.map → chunk-gj4hg8xk.js.map} +1 -1
- package/dist/{chunk-h0dch3vh.js → chunk-h6z5k6yh.js} +2 -2
- package/dist/{chunk-h0dch3vh.js.map → chunk-h6z5k6yh.js.map} +1 -1
- package/dist/{chunk-fqndtpwm.js → chunk-jfqfvx3t.js} +3 -3
- package/dist/{chunk-fqndtpwm.js.map → chunk-jfqfvx3t.js.map} +1 -1
- package/dist/{chunk-at82qczv.js → chunk-jwh7t982.js} +3 -3
- package/dist/{chunk-at82qczv.js.map → chunk-jwh7t982.js.map} +1 -1
- package/dist/{chunk-2ver7cdt.js → chunk-k2jxxdj1.js} +1 -1
- package/dist/{chunk-t2p5n8fe.js → chunk-k9devrb5.js} +2 -2
- package/dist/{chunk-t2p5n8fe.js.map → chunk-k9devrb5.js.map} +1 -1
- package/dist/{chunk-sv2mv2q2.js → chunk-kpbm4mbc.js} +2 -2
- package/dist/{chunk-sv2mv2q2.js.map → chunk-kpbm4mbc.js.map} +1 -1
- package/dist/{chunk-gt9ftnhn.js → chunk-krfz1rzm.js} +2 -2
- package/dist/{chunk-gt9ftnhn.js.map → chunk-krfz1rzm.js.map} +1 -1
- package/dist/{chunk-zt4hybgg.js → chunk-mwe7hpbd.js} +2 -2
- package/dist/{chunk-zt4hybgg.js.map → chunk-mwe7hpbd.js.map} +1 -1
- package/dist/{chunk-x185900b.js → chunk-n78b8pp5.js} +3 -3
- package/dist/{chunk-x185900b.js.map → chunk-n78b8pp5.js.map} +1 -1
- package/dist/{chunk-fs94x6ef.js → chunk-nznkpf8r.js} +3 -3
- package/dist/{chunk-fs94x6ef.js.map → chunk-nznkpf8r.js.map} +1 -1
- package/dist/{chunk-2j45vbs2.js → chunk-p91yn1b8.js} +2 -2
- package/dist/{chunk-2j45vbs2.js.map → chunk-p91yn1b8.js.map} +1 -1
- package/dist/{chunk-h5wjk91m.js → chunk-pqaha4f1.js} +2 -2
- package/dist/{chunk-h5wjk91m.js.map → chunk-pqaha4f1.js.map} +1 -1
- package/dist/{chunk-8gz07168.js → chunk-q4b79hjb.js} +4 -4
- package/dist/{chunk-8gz07168.js.map → chunk-q4b79hjb.js.map} +1 -1
- package/dist/{chunk-ezea9fpd.js → chunk-qj2r0v7w.js} +2 -2
- package/dist/{chunk-ezea9fpd.js.map → chunk-qj2r0v7w.js.map} +1 -1
- package/dist/{chunk-8jc8x9tc.js → chunk-rmwhvgvg.js} +2 -2
- package/dist/{chunk-8jc8x9tc.js.map → chunk-rmwhvgvg.js.map} +1 -1
- package/dist/{chunk-4mha212g.js → chunk-sxtg2qha.js} +1 -1
- package/dist/{chunk-t60krz4g.js → chunk-t4yx1jqb.js} +2 -2
- package/dist/{chunk-t60krz4g.js.map → chunk-t4yx1jqb.js.map} +1 -1
- package/dist/{chunk-yknc5rgh.js → chunk-t6xe3jr4.js} +2 -2
- package/dist/{chunk-yknc5rgh.js.map → chunk-t6xe3jr4.js.map} +1 -1
- package/dist/{chunk-kvtvx64t.js → chunk-tmpfcx0v.js} +2 -2
- package/dist/{chunk-kvtvx64t.js.map → chunk-tmpfcx0v.js.map} +1 -1
- package/dist/{chunk-8n40a2sn.js → chunk-trbwk80g.js} +2 -2
- package/dist/{chunk-8n40a2sn.js.map → chunk-trbwk80g.js.map} +1 -1
- package/dist/{chunk-aj9atkwk.js → chunk-va2p7e59.js} +1 -1
- package/dist/{chunk-17ewxwga.js → chunk-vbmtyxr4.js} +3 -3
- package/dist/{chunk-17ewxwga.js.map → chunk-vbmtyxr4.js.map} +1 -1
- package/dist/{chunk-406ef17s.js → chunk-vc7ny5zs.js} +2 -2
- package/dist/{chunk-406ef17s.js.map → chunk-vc7ny5zs.js.map} +1 -1
- package/dist/{chunk-zm6b938z.js → chunk-vcmwp7pv.js} +3 -3
- package/dist/{chunk-zm6b938z.js.map → chunk-vcmwp7pv.js.map} +1 -1
- package/dist/{chunk-8mpptpn5.js → chunk-vrp3zzz4.js} +3 -3
- package/dist/{chunk-8mpptpn5.js.map → chunk-vrp3zzz4.js.map} +1 -1
- package/dist/{chunk-y56xd7sv.js → chunk-w7rgnjt5.js} +2 -2
- package/dist/{chunk-y56xd7sv.js.map → chunk-w7rgnjt5.js.map} +1 -1
- package/dist/{chunk-g7hz0dmk.js → chunk-w9v8bbp8.js} +2 -2
- package/dist/{chunk-g7hz0dmk.js.map → chunk-w9v8bbp8.js.map} +1 -1
- package/dist/{chunk-k2mpxwh2.js → chunk-x8pk6qqs.js} +2 -2
- package/dist/{chunk-ts75gcfd.js.map → chunk-x8pk6qqs.js.map} +1 -1
- package/dist/{chunk-9jt5qj1b.js → chunk-xj3ebwrj.js} +2 -2
- package/dist/{chunk-9jt5qj1b.js.map → chunk-xj3ebwrj.js.map} +1 -1
- package/dist/{chunk-6v1fbe70.js → chunk-y9efbqmp.js} +2 -2
- package/dist/{chunk-6v1fbe70.js.map → chunk-y9efbqmp.js.map} +1 -1
- package/dist/{chunk-7fbnw7e2.js → chunk-yb7yw0cp.js} +1 -1
- package/dist/{chunk-z3tk66vh.js → chunk-yca8nznt.js} +2 -2
- package/dist/{chunk-z3tk66vh.js.map → chunk-yca8nznt.js.map} +1 -1
- package/dist/{chunk-pfkbhqp7.js → chunk-z0xmyrjb.js} +2 -2
- package/dist/{chunk-pfkbhqp7.js.map → chunk-z0xmyrjb.js.map} +1 -1
- package/dist/{chunk-ehtj7zs2.js → chunk-z55c52fm.js} +2 -2
- package/dist/{chunk-ehtj7zs2.js.map → chunk-z55c52fm.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-0hy5dsbt.js +0 -5
- package/dist/chunk-dav7mv8t.js +0 -48
- package/dist/chunk-dav7mv8t.js.map +0 -26
- package/dist/chunk-gvr7cwxn.js +0 -5
- /package/dist/{chunk-1w6ra6jc.js.map → chunk-9447c20x.js.map} +0 -0
- /package/dist/{chunk-n4kz9vft.js.map → chunk-9ey725pw.js.map} +0 -0
- /package/dist/{chunk-2ver7cdt.js.map → chunk-k2jxxdj1.js.map} +0 -0
- /package/dist/{chunk-4mha212g.js.map → chunk-sxtg2qha.js.map} +0 -0
- /package/dist/{chunk-aj9atkwk.js.map → chunk-va2p7e59.js.map} +0 -0
- /package/dist/{chunk-7fbnw7e2.js.map → chunk-yb7yw0cp.js.map} +0 -0
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Id as IQ,Qd as A,Rd as JQ,Sd as U5,Td as D5,Ud as RQ,Vd as x5,Wd as f,Xd as GQ,Yd as M,sd as VQ,ud as g}from"./chunk-gvr7cwxn.js";import{Fj as B5,Nj as P5}from"./chunk-t6x1r5n6.js";var{fetch:i5,WebSocket:n5}=globalThis;function sQ(Q,$){if(typeof Bun>"u")return Q!==$;return typeof Q!=="function"||!/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(Q))}class qQ extends Error{constructor(Q){super(`A model provider tried to call ${r5(Q)} from a test. Tests under vitest do not reach real model providers: give the agent a scripted or fake provider, or set GEMI_AI_LIVE=1 to make real (billed) calls.`);this.name="LiveModelCallRefusedError"}}function aQ(Q=process.env){return!Q.VITEST||Q.GEMI_AI_LIVE==="1"}function oQ(Q){if(aQ()||sQ(globalThis.fetch,i5)||eQ(Q))return;throw new qQ(Q)}function tQ(Q){let $=globalThis.WebSocket;if(aQ()||sQ($,n5)||eQ(Q))return;throw new qQ(Q)}function eQ(Q){let $;try{$=new URL(Q).hostname}catch{return!1}return $==="localhost"||$.endsWith(".localhost")||$==="[::1]"||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test($)}function r5(Q){try{return new URL(Q).origin}catch{return"a provider"}}function CQ(Q,$,J){let Z=Q.on;if(Z===void 0)return!0;if(typeof Z!=="function")return Z.includes($.code);try{return Z($,J)===!0}catch{return!1}}var s5=4000,a5=60000;function Q5(Q){if(Q===void 0)return;let $=(J,Z)=>typeof J==="number"&&Number.isFinite(J)&&J>=Z;if(!Q||!$(Q.patienceMs,0)||Q.initialWaitMs!==void 0&&!$(Q.initialWaitMs,1)||Q.maxWaitMs!==void 0&&!$(Q.maxWaitMs,1)||Q.on!==void 0&&typeof Q.on!=="function"&&!(Array.isArray(Q.on)&&Q.on.every((J)=>typeof J==="string")))throw Error(`The provider's retry policy ${JSON.stringify(Q)} is not usable: patienceMs has to be a number of milliseconds (0 or more), initialWaitMs and maxWaitMs above 0, and on a list of error codes or a function.`)}function FQ(Q,$,J,Z,Y){let G=Q.patienceMs-Z;if(G<=0)return;let V=Q.maxWaitMs??a5,z=Q.initialWaitMs??s5,H=J!==void 0?Math.min(J,V):Math.round(Math.min(V,z*2**$)*(0.5+Y()*0.5));return Math.min(H,G)}var o5=500,$5=20000;function t5(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 $Q(Q,$){let J=Math.min($5,o5*2**Q);return Math.round(J*(0.5+$()*0.5))}function e5(Q){return Q===429||Q===408||Q===409||Q>=500}function Q6(Q,$){return e5(Q)&&M($).retryable}function J5(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function Z5(Q,$){return new Promise((J,Z)=>{let Y=setTimeout(J,Q);$?.addEventListener("abort",()=>{clearTimeout(Y),Z(J5($))},{once:!0})})}async function NQ(Q,$,J=Z5){if(!$)return await J(Q);$.throwIfAborted();let Z;try{await Promise.race([J(Q,$),new Promise((Y,G)=>{Z=()=>G(J5($)),$.addEventListener("abort",Z,{once:!0})})])}finally{if(Z)$.removeEventListener("abort",Z)}}async function m(Q,$,J){if(!J.fetchImpl)oQ(Q);let Z=J.fetchImpl??((B,W)=>fetch(B,W)),Y=J.sleep??Z5,G=J.random??Math.random,V=J.now??Date.now,z=Math.max(0,J.maxRetries),H=J.startedAt??V(),K=J.retry,X=(B,W,q,F)=>{let x=V()-H;try{J.onRetry?.({attempt:W+1,maxRetries:z,error:M(q),...f(q),timedOut:F,delayMs:B,elapsedMs:x,...K?{remainingMs:Math.max(0,K.patienceMs-x-B)}:{}})}catch{}return NQ(B,J.signal,Y)},j=(B,W,q,F)=>{if(!K)return;let{status:x}=f(q);if(!CQ(K,M(q),{...x?{status:x}:{},timedOut:F}))return;return FQ(K,B-z,W,V()-H,G)};for(let B=0;;B++){J.signal?.throwIfAborted();let W=new AbortController,q=()=>W.abort(J.signal?.reason);J.signal?.addEventListener("abort",q,{once:!0});let F=!1,x=J.timeoutMs>0?setTimeout(()=>{F=!0,W.abort()},J.timeoutMs):void 0,U;try{U=await Z(Q,{...$,signal:W.signal})}catch(o){if(x!==void 0)clearTimeout(x);if(J.signal?.removeEventListener("abort",q),J.signal?.aborted)throw o;let k=F?new JQ(J.timeoutMs):o;if(F&&J.retryTimeouts===!1)throw k;let T=B<z?$Q(B,G):j(B,void 0,k,F);if(T===void 0)throw k;await X(T,B,k,F);continue}if(x!==void 0)clearTimeout(x);if(U.ok)return U;J.signal?.removeEventListener("abort",q);let p=await $6(U),I=new A(U.status,p,U.headers.get("x-request-id")??U.headers.get("request-id")??void 0,t5(U.headers.get("retry-after"),V()));if(!Q6(U.status,I))throw I;let P=I.retryAfter??(U.status===429?M(I).retryAfter:void 0),S=B>=z?j(B,P,I,!1):P===void 0?$Q(B,G):Math.min(P,$5);if(S===void 0)throw I;await X(S,B,I,!1)}}async function $6(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}function Y5(Q,$,J){let Z=$.idleMs>0?$.idleMs:0,Y=$.maxMs>0?$.maxMs:0;if(!Q||!Z&&!Y)return Q;let G=Y?performance.now()+Y:1/0,V=Q.getReader();return new ReadableStream({async pull(z){let H,K,X=Math.max(0,G-performance.now()),j=!Z||X<=Z,B=j?X:Z,W=new Promise((q,F)=>{H=setTimeout(()=>{K=j?J.max():J.idle(),F(K)},B)});try{let q=await Promise.race([V.read(),W]);if(q.done)z.close();else z.enqueue(q.value)}catch(q){let F=K??q;z.error(F),V.cancel(F).catch(()=>{})}finally{clearTimeout(H)}},cancel(z){return V.cancel(z)}},{highWaterMark:0})}var PQ=30000,G5=10,V5=7200,J6=600,Z6="gpt-live-transcribe";function Y6(Q){return Q.type==="transcription"}function G6(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 Y of Q.keywords??[])if(/[<>\r\n]/.test(Y))throw TypeError(`Transcription keywords must be one line without "<" or ">", got ${JSON.stringify(Y)}.`);let $={model:Q.model??Z6};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?K5(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 V6(Q){if(!Q)return{type:"object",properties:{}};return B5(Q)?Q.toJSONSchema():Q}function ZQ(Q,$){if(Y6(Q))return G6(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((V)=>({type:"function",name:V.name,...V.description?{description:V.description}:{},parameters:V6(V.parameters)}));if(Q.toolChoice!==void 0)J.tool_choice=typeof Q.toolChoice==="string"?Q.toolChoice:{type:"function",name:Q.toolChoice.name};let Y={};if(Q.turnDetection!==void 0)Y.turn_detection=Q.turnDetection&&K5(Q.turnDetection);if(Q.transcription!==void 0)Y.transcription=Q.transcription;if(Q.noiseReduction!==void 0)Y.noise_reduction=Q.noiseReduction&&{type:Q.noiseReduction};let G={};if(Q.voice!==void 0)G.voice=Q.voice;if(Q.speed!==void 0)G.speed=Q.speed;if(Object.keys(Y).length||Object.keys(G).length)J.audio={...Object.keys(Y).length?{input:Y}:{},...Object.keys(G).length?{output:G}:{}};return{...J,...Q.vendor}}function K5(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 UQ(Q){let $=Number(Q?.input_tokens??0),J=Number(Q?.output_tokens??0),Z={inputTokens:$,outputTokens:J,totalTokens:Number(Q?.total_tokens??$+J)},Y=Q?.input_token_details??Q?.input_tokens_details,G=Q?.output_token_details??Q?.output_tokens_details;if(typeof Y?.cached_tokens==="number")Z.cachedInputTokens=Y.cached_tokens;if(typeof Y?.audio_tokens==="number")Z.audioInputTokens=Y.audio_tokens;let V=Y?.cached_tokens_details?.audio_tokens;if(typeof V==="number")Z.cachedAudioInputTokens=V;if(typeof Y?.image_tokens==="number"&&Y.image_tokens>0)Z.imageInputTokens=Y.image_tokens;if(typeof G?.audio_tokens==="number")Z.audioOutputTokens=G.audio_tokens;return Z}class i 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 B6=60;class YQ{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,Y)=>`ws${Y}:`),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:B6,signal:Q.signal})).value}`,"content-type":"application/sdp"},Z=Q.sdp;else{let H=new FormData;H.set("sdp",Q.sdp),H.set("session",JSON.stringify(ZQ(Q.session??{},this.model))),J=await this.target.headers(),Z=H}if(Q.safetyIdentifier)J["OpenAI-Safety-Identifier"]=Q.safetyIdentifier;let Y=this.url("/calls"),G=await this.request(Q.webrtcFilter?`${Y}${Y.includes("?")?"&":"?"}webrtcfilter=on`:Y,{method:"POST",headers:J,body:Z},Q.signal),V=await G.text(),z=W6(G);if(!z)throw new i({code:"provider_error",message:"The provider started a realtime call but did not say which one (no Location).",retryable:!1});return{sdpAnswer:V,callId:z}}async clientSecret(Q={}){let $=Q.ttlSeconds??J6;if(!Number.isInteger($)||$<G5||$>V5)throw RangeError(`ttlSeconds must be a whole number from ${G5} to ${V5}, got ${$}.`);let J={...await this.target.headers(),"content-type":"application/json"};if(Q.safetyIdentifier)J["OpenAI-Safety-Identifier"]=Q.safetyIdentifier;let Y=await(await this.request(this.url("/client_secrets"),{method:"POST",headers:J,body:JSON.stringify({expires_after:{anchor:"created_at",seconds:$},session:ZQ(Q.session??{},this.model)})},Q.signal)).json();if(typeof Y?.value!=="string")throw new i({code:"provider_error",message:"The provider answered a client secret request with no secret.",retryable:!1});return{value:Y.value,expiresAt:Number(Y.expires_at??0),session:Y.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(K6(J,Q))return;throw J}}sideband(Q,$={}){return new LQ({...$,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 m(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 i(M(Z),{cause:Z,...Z instanceof A?{status:Z.status}:{}})}}}function K6(Q,$){if(!(Q instanceof i)||Q.status!==404)return!1;let J=Q.cause instanceof A?Q.cause.body:void 0,Z=J?.error??J,Y=String(Z?.code??"").toLowerCase(),G=String(Z?.message??"").toLowerCase();if(Y.includes("call"))return!0;if(G.includes($.toLowerCase()))return!0;return/\bcall\b/.test(G)&&/not (be )?found|does not exist|no longer|ended/.test(G)}function W6(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 X6={"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 H6(Q){if(typeof Q!=="string")return;let $;try{$=JSON.parse(Q)}catch{return}if(!$||typeof $!=="object"||typeof $.type!=="string")return;let J=X6[$.type];if(J)$.type=J;if($.type==="response.done"&&$.response?.usage)$.usage=UQ($.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=UQ($.usage);return $}var W5=1,j6=500;function z6(Q,$){let J=globalThis.WebSocket;if(!J)throw Error("No global WebSocket: the realtime sideband needs Bun or Node 22+.");return tQ(Q),new J(Q,{headers:$.headers})}class LQ{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===W5)this.socket.send($);else this.outbox.push($)}updateSession(Q){this.send({type:"session.update",session:ZQ(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<=W5)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??z6)(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 Y of this.outbox.splice(0))Q.send(Y);if(this.resolveReady(),J)this.emit({type:"sideband.reconnected",attempt:Z})}),Q.addEventListener("message",(J)=>{let Z=H6(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 G=(this.init.reconnect?.delayMs??500)*2**(this.failures-1);setTimeout(()=>void this.open(),G)}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 Y of this.subscribers)Y.done=!0,Y.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>j6)this.backlog.shift()}for(let $ of this.subscribers){if($.done)continue;$.queue.push(Q),$.wake?.()}for(let $ of this.listeners)try{$(Q)}catch{}}}var j5=3;function DQ(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 z5(Q,$,J=new Map){if(!($ instanceof A))return[];if($.status!==400&&$.status!==404)return[];let Z=OQ($.body);if(!Z)return[];let Y=q6(Q.input);if(Y.length===0)return[];let G=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(G){let K=Q.input[Number(G[1])],X=xQ(K)[Number(G[2])],j=X&&typeof X.file_id==="string"?X.file_id:void 0;if(j)return[j]}let V=Z.message??"",z=H5(Y.map((K)=>K.fileId).filter((K)=>C6(V,K)));if(z.length>0)return z;let H=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(V);if(H){let K=H[1].toLowerCase()==="image type"?"input_image":"input_file",X=H[2].toLowerCase(),j=H5(Y.filter((W)=>W.type===K).map((W)=>W.fileId)),B=j.filter((W)=>(J.get(W)?.name??"").trim().toLowerCase().endsWith(`.${X}`));if(B.length===1)return B;if(B.length===0&&j.length===1)return j}return[]}function q5(Q,$,J=new Map){return{...Q,input:Q.input.map((Z)=>{let Y=xQ(Z);if(!Y.some((G)=>X5(G,$)))return Z;return{...Z,content:Y.map((G)=>X5(G,$)?{type:"input_text",text:n(J.get(String(G.file_id))?.name)}:G)}})}}function n(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 X5(Q,$){return typeof Q.file_id==="string"&&$.has(Q.file_id)}function xQ(Q){let $=Q?.content;return Array.isArray($)?$:[]}function q6(Q){let $=[];for(let J of Q)for(let Z of xQ(J))if(typeof Z.file_id==="string"&&Z.file_id)$.push({type:String(Z.type),fileId:Z.file_id});return $}function OQ(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 C6(Q,$){let J=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${J}($|[^A-Za-z0-9_-])`).test(Q)}function H5(Q){return[...new Set(Q)]}function C5(Q,$){if(!($ instanceof A))return null;if($.status!==400&&$.status!==404)return null;let J=Q?.input;if(!Array.isArray(J))return null;let Z=OQ($.body)?.message??"",Y=/Item with id '([^']+)' not found/i.exec(Z)?.[1];if(!Y)return null;let G=(V)=>V?.type==="reasoning";if(!J.some((V)=>G(V)&&V.id===Y))return null;return{...Q,input:J.filter((V)=>!G(V))}}async function*_Q(Q){let $="",J="",Z=[],Y,G=()=>{if(Z.length===0&&!J)return null;let H={event:J,data:Z.join(`
|
|
2
|
+
import{$d as M,Ld as IQ,Td as A,Ud as JQ,Vd as U5,Wd as D5,Xd as RQ,Yd as x5,Zd as f,_d as GQ,td as VQ,vd as g}from"./chunk-ejf6sz1d.js";import{Ij as B5,Qj as P5}from"./chunk-c6zpn9yp.js";var{fetch:i5,WebSocket:n5}=globalThis;function sQ(Q,$){if(typeof Bun>"u")return Q!==$;return typeof Q!=="function"||!/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(Q))}class qQ extends Error{constructor(Q){super(`A model provider tried to call ${r5(Q)} from a test. Tests under vitest do not reach real model providers: give the agent a scripted or fake provider, or set GEMI_AI_LIVE=1 to make real (billed) calls.`);this.name="LiveModelCallRefusedError"}}function aQ(Q=process.env){return!Q.VITEST||Q.GEMI_AI_LIVE==="1"}function oQ(Q){if(aQ()||sQ(globalThis.fetch,i5)||eQ(Q))return;throw new qQ(Q)}function tQ(Q){let $=globalThis.WebSocket;if(aQ()||sQ($,n5)||eQ(Q))return;throw new qQ(Q)}function eQ(Q){let $;try{$=new URL(Q).hostname}catch{return!1}return $==="localhost"||$.endsWith(".localhost")||$==="[::1]"||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test($)}function r5(Q){try{return new URL(Q).origin}catch{return"a provider"}}function CQ(Q,$,J){let Z=Q.on;if(Z===void 0)return!0;if(typeof Z!=="function")return Z.includes($.code);try{return Z($,J)===!0}catch{return!1}}var s5=4000,a5=60000;function Q5(Q){if(Q===void 0)return;let $=(J,Z)=>typeof J==="number"&&Number.isFinite(J)&&J>=Z;if(!Q||!$(Q.patienceMs,0)||Q.initialWaitMs!==void 0&&!$(Q.initialWaitMs,1)||Q.maxWaitMs!==void 0&&!$(Q.maxWaitMs,1)||Q.on!==void 0&&typeof Q.on!=="function"&&!(Array.isArray(Q.on)&&Q.on.every((J)=>typeof J==="string")))throw Error(`The provider's retry policy ${JSON.stringify(Q)} is not usable: patienceMs has to be a number of milliseconds (0 or more), initialWaitMs and maxWaitMs above 0, and on a list of error codes or a function.`)}function FQ(Q,$,J,Z,Y){let G=Q.patienceMs-Z;if(G<=0)return;let V=Q.maxWaitMs??a5,z=Q.initialWaitMs??s5,H=J!==void 0?Math.min(J,V):Math.round(Math.min(V,z*2**$)*(0.5+Y()*0.5));return Math.min(H,G)}var o5=500,$5=20000;function t5(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 $Q(Q,$){let J=Math.min($5,o5*2**Q);return Math.round(J*(0.5+$()*0.5))}function e5(Q){return Q===429||Q===408||Q===409||Q>=500}function Q6(Q,$){return e5(Q)&&M($).retryable}function J5(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function Z5(Q,$){return new Promise((J,Z)=>{let Y=setTimeout(J,Q);$?.addEventListener("abort",()=>{clearTimeout(Y),Z(J5($))},{once:!0})})}async function NQ(Q,$,J=Z5){if(!$)return await J(Q);$.throwIfAborted();let Z;try{await Promise.race([J(Q,$),new Promise((Y,G)=>{Z=()=>G(J5($)),$.addEventListener("abort",Z,{once:!0})})])}finally{if(Z)$.removeEventListener("abort",Z)}}async function m(Q,$,J){if(!J.fetchImpl)oQ(Q);let Z=J.fetchImpl??((B,W)=>fetch(B,W)),Y=J.sleep??Z5,G=J.random??Math.random,V=J.now??Date.now,z=Math.max(0,J.maxRetries),H=J.startedAt??V(),K=J.retry,X=(B,W,q,F)=>{let x=V()-H;try{J.onRetry?.({attempt:W+1,maxRetries:z,error:M(q),...f(q),timedOut:F,delayMs:B,elapsedMs:x,...K?{remainingMs:Math.max(0,K.patienceMs-x-B)}:{}})}catch{}return NQ(B,J.signal,Y)},j=(B,W,q,F)=>{if(!K)return;let{status:x}=f(q);if(!CQ(K,M(q),{...x?{status:x}:{},timedOut:F}))return;return FQ(K,B-z,W,V()-H,G)};for(let B=0;;B++){J.signal?.throwIfAborted();let W=new AbortController,q=()=>W.abort(J.signal?.reason);J.signal?.addEventListener("abort",q,{once:!0});let F=!1,x=J.timeoutMs>0?setTimeout(()=>{F=!0,W.abort()},J.timeoutMs):void 0,U;try{U=await Z(Q,{...$,signal:W.signal})}catch(o){if(x!==void 0)clearTimeout(x);if(J.signal?.removeEventListener("abort",q),J.signal?.aborted)throw o;let k=F?new JQ(J.timeoutMs):o;if(F&&J.retryTimeouts===!1)throw k;let T=B<z?$Q(B,G):j(B,void 0,k,F);if(T===void 0)throw k;await X(T,B,k,F);continue}if(x!==void 0)clearTimeout(x);if(U.ok)return U;J.signal?.removeEventListener("abort",q);let p=await $6(U),I=new A(U.status,p,U.headers.get("x-request-id")??U.headers.get("request-id")??void 0,t5(U.headers.get("retry-after"),V()));if(!Q6(U.status,I))throw I;let P=I.retryAfter??(U.status===429?M(I).retryAfter:void 0),S=B>=z?j(B,P,I,!1):P===void 0?$Q(B,G):Math.min(P,$5);if(S===void 0)throw I;await X(S,B,I,!1)}}async function $6(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}function Y5(Q,$,J){let Z=$.idleMs>0?$.idleMs:0,Y=$.maxMs>0?$.maxMs:0;if(!Q||!Z&&!Y)return Q;let G=Y?performance.now()+Y:1/0,V=Q.getReader();return new ReadableStream({async pull(z){let H,K,X=Math.max(0,G-performance.now()),j=!Z||X<=Z,B=j?X:Z,W=new Promise((q,F)=>{H=setTimeout(()=>{K=j?J.max():J.idle(),F(K)},B)});try{let q=await Promise.race([V.read(),W]);if(q.done)z.close();else z.enqueue(q.value)}catch(q){let F=K??q;z.error(F),V.cancel(F).catch(()=>{})}finally{clearTimeout(H)}},cancel(z){return V.cancel(z)}},{highWaterMark:0})}var PQ=30000,G5=10,V5=7200,J6=600,Z6="gpt-live-transcribe";function Y6(Q){return Q.type==="transcription"}function G6(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 Y of Q.keywords??[])if(/[<>\r\n]/.test(Y))throw TypeError(`Transcription keywords must be one line without "<" or ">", got ${JSON.stringify(Y)}.`);let $={model:Q.model??Z6};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?K5(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 V6(Q){if(!Q)return{type:"object",properties:{}};return B5(Q)?Q.toJSONSchema():Q}function ZQ(Q,$){if(Y6(Q))return G6(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((V)=>({type:"function",name:V.name,...V.description?{description:V.description}:{},parameters:V6(V.parameters)}));if(Q.toolChoice!==void 0)J.tool_choice=typeof Q.toolChoice==="string"?Q.toolChoice:{type:"function",name:Q.toolChoice.name};let Y={};if(Q.turnDetection!==void 0)Y.turn_detection=Q.turnDetection&&K5(Q.turnDetection);if(Q.transcription!==void 0)Y.transcription=Q.transcription;if(Q.noiseReduction!==void 0)Y.noise_reduction=Q.noiseReduction&&{type:Q.noiseReduction};let G={};if(Q.voice!==void 0)G.voice=Q.voice;if(Q.speed!==void 0)G.speed=Q.speed;if(Object.keys(Y).length||Object.keys(G).length)J.audio={...Object.keys(Y).length?{input:Y}:{},...Object.keys(G).length?{output:G}:{}};return{...J,...Q.vendor}}function K5(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 UQ(Q){let $=Number(Q?.input_tokens??0),J=Number(Q?.output_tokens??0),Z={inputTokens:$,outputTokens:J,totalTokens:Number(Q?.total_tokens??$+J)},Y=Q?.input_token_details??Q?.input_tokens_details,G=Q?.output_token_details??Q?.output_tokens_details;if(typeof Y?.cached_tokens==="number")Z.cachedInputTokens=Y.cached_tokens;if(typeof Y?.audio_tokens==="number")Z.audioInputTokens=Y.audio_tokens;let V=Y?.cached_tokens_details?.audio_tokens;if(typeof V==="number")Z.cachedAudioInputTokens=V;if(typeof Y?.image_tokens==="number"&&Y.image_tokens>0)Z.imageInputTokens=Y.image_tokens;if(typeof G?.audio_tokens==="number")Z.audioOutputTokens=G.audio_tokens;return Z}class i 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 B6=60;class YQ{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,Y)=>`ws${Y}:`),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:B6,signal:Q.signal})).value}`,"content-type":"application/sdp"},Z=Q.sdp;else{let H=new FormData;H.set("sdp",Q.sdp),H.set("session",JSON.stringify(ZQ(Q.session??{},this.model))),J=await this.target.headers(),Z=H}if(Q.safetyIdentifier)J["OpenAI-Safety-Identifier"]=Q.safetyIdentifier;let Y=this.url("/calls"),G=await this.request(Q.webrtcFilter?`${Y}${Y.includes("?")?"&":"?"}webrtcfilter=on`:Y,{method:"POST",headers:J,body:Z},Q.signal),V=await G.text(),z=W6(G);if(!z)throw new i({code:"provider_error",message:"The provider started a realtime call but did not say which one (no Location).",retryable:!1});return{sdpAnswer:V,callId:z}}async clientSecret(Q={}){let $=Q.ttlSeconds??J6;if(!Number.isInteger($)||$<G5||$>V5)throw RangeError(`ttlSeconds must be a whole number from ${G5} to ${V5}, got ${$}.`);let J={...await this.target.headers(),"content-type":"application/json"};if(Q.safetyIdentifier)J["OpenAI-Safety-Identifier"]=Q.safetyIdentifier;let Y=await(await this.request(this.url("/client_secrets"),{method:"POST",headers:J,body:JSON.stringify({expires_after:{anchor:"created_at",seconds:$},session:ZQ(Q.session??{},this.model)})},Q.signal)).json();if(typeof Y?.value!=="string")throw new i({code:"provider_error",message:"The provider answered a client secret request with no secret.",retryable:!1});return{value:Y.value,expiresAt:Number(Y.expires_at??0),session:Y.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(K6(J,Q))return;throw J}}sideband(Q,$={}){return new LQ({...$,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 m(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 i(M(Z),{cause:Z,...Z instanceof A?{status:Z.status}:{}})}}}function K6(Q,$){if(!(Q instanceof i)||Q.status!==404)return!1;let J=Q.cause instanceof A?Q.cause.body:void 0,Z=J?.error??J,Y=String(Z?.code??"").toLowerCase(),G=String(Z?.message??"").toLowerCase();if(Y.includes("call"))return!0;if(G.includes($.toLowerCase()))return!0;return/\bcall\b/.test(G)&&/not (be )?found|does not exist|no longer|ended/.test(G)}function W6(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 X6={"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 H6(Q){if(typeof Q!=="string")return;let $;try{$=JSON.parse(Q)}catch{return}if(!$||typeof $!=="object"||typeof $.type!=="string")return;let J=X6[$.type];if(J)$.type=J;if($.type==="response.done"&&$.response?.usage)$.usage=UQ($.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=UQ($.usage);return $}var W5=1,j6=500;function z6(Q,$){let J=globalThis.WebSocket;if(!J)throw Error("No global WebSocket: the realtime sideband needs Bun or Node 22+.");return tQ(Q),new J(Q,{headers:$.headers})}class LQ{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===W5)this.socket.send($);else this.outbox.push($)}updateSession(Q){this.send({type:"session.update",session:ZQ(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<=W5)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??z6)(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 Y of this.outbox.splice(0))Q.send(Y);if(this.resolveReady(),J)this.emit({type:"sideband.reconnected",attempt:Z})}),Q.addEventListener("message",(J)=>{let Z=H6(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 G=(this.init.reconnect?.delayMs??500)*2**(this.failures-1);setTimeout(()=>void this.open(),G)}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 Y of this.subscribers)Y.done=!0,Y.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>j6)this.backlog.shift()}for(let $ of this.subscribers){if($.done)continue;$.queue.push(Q),$.wake?.()}for(let $ of this.listeners)try{$(Q)}catch{}}}var j5=3;function DQ(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 z5(Q,$,J=new Map){if(!($ instanceof A))return[];if($.status!==400&&$.status!==404)return[];let Z=OQ($.body);if(!Z)return[];let Y=q6(Q.input);if(Y.length===0)return[];let G=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(G){let K=Q.input[Number(G[1])],X=xQ(K)[Number(G[2])],j=X&&typeof X.file_id==="string"?X.file_id:void 0;if(j)return[j]}let V=Z.message??"",z=H5(Y.map((K)=>K.fileId).filter((K)=>C6(V,K)));if(z.length>0)return z;let H=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(V);if(H){let K=H[1].toLowerCase()==="image type"?"input_image":"input_file",X=H[2].toLowerCase(),j=H5(Y.filter((W)=>W.type===K).map((W)=>W.fileId)),B=j.filter((W)=>(J.get(W)?.name??"").trim().toLowerCase().endsWith(`.${X}`));if(B.length===1)return B;if(B.length===0&&j.length===1)return j}return[]}function q5(Q,$,J=new Map){return{...Q,input:Q.input.map((Z)=>{let Y=xQ(Z);if(!Y.some((G)=>X5(G,$)))return Z;return{...Z,content:Y.map((G)=>X5(G,$)?{type:"input_text",text:n(J.get(String(G.file_id))?.name)}:G)}})}}function n(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 X5(Q,$){return typeof Q.file_id==="string"&&$.has(Q.file_id)}function xQ(Q){let $=Q?.content;return Array.isArray($)?$:[]}function q6(Q){let $=[];for(let J of Q)for(let Z of xQ(J))if(typeof Z.file_id==="string"&&Z.file_id)$.push({type:String(Z.type),fileId:Z.file_id});return $}function OQ(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 C6(Q,$){let J=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${J}($|[^A-Za-z0-9_-])`).test(Q)}function H5(Q){return[...new Set(Q)]}function C5(Q,$){if(!($ instanceof A))return null;if($.status!==400&&$.status!==404)return null;let J=Q?.input;if(!Array.isArray(J))return null;let Z=OQ($.body)?.message??"",Y=/Item with id '([^']+)' not found/i.exec(Z)?.[1];if(!Y)return null;let G=(V)=>V?.type==="reasoning";if(!J.some((V)=>G(V)&&V.id===Y))return null;return{...Q,input:J.filter((V)=>!G(V))}}async function*_Q(Q){let $="",J="",Z=[],Y,G=()=>{if(Z.length===0&&!J)return null;let H={event:J,data:Z.join(`
|
|
3
3
|
`),id:Y};return J="",Z=[],Y=void 0,H.data?H:null},V=(H)=>{let K=H.endsWith("\r")?H.slice(0,-1):H;if(K==="")return G();if(K.startsWith(":"))return null;let X=K.indexOf(":"),j=X===-1?K:K.slice(0,X),B=X===-1?"":K.slice(X+1);if(B.startsWith(" "))B=B.slice(1);if(j==="event")J=B;else if(j==="data")Z.push(B);else if(j==="id")Y=B;return null};for await(let H of Q){$+=H;let K=$.indexOf(`
|
|
4
4
|
`);while(K!==-1){let X=$.slice(0,K);$=$.slice(K+1);let j=V(X);if(j)yield j;K=$.indexOf(`
|
|
5
5
|
`)}}if($.length>0){let H=V($);if(H)yield H}let z=G();if(z)yield z}async function*F5(Q,$={}){let J=new Map,Z=new Set,Y,G=!1,V,z=(H,K)=>({type:"finish",reason:H,usage:K,...V?{model:V}:{}});for await(let H of _Q(Q)){if(H.data==="[DONE]")break;let K;try{K=JSON.parse(H.data)}catch{continue}let X=typeof K.type==="string"?K.type:H.event,j=K.response?.model;if(typeof j==="string"&&j)V=j;switch(X){case"response.output_text.delta":{let B=String(K.delta??"");if(!B)break;yield $.structuredOutput?{type:"output-delta",delta:B}:{type:"text-delta",delta:B};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let B=String(K.delta??"");if(!B)break;yield{type:"reasoning-delta",delta:B,id:K.item_id};break}case"response.output_item.added":{let B=K.item;if(!B)break;if(B.type==="function_call"){let W=String(B.id??K.item_id??B.call_id??"");J.set(W,{callId:String(B.call_id??W),name:String(B.name??""),namespace:typeof B.namespace==="string"&&B.namespace?B.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let B=J.get(String(K.item_id??""));if(!B)break;let W=String(K.delta??"");if(!W)break;yield{type:"tool-call-delta",toolCallId:B.callId,name:B.name,argsDelta:W,...B.namespace?{namespace:B.namespace}:{}};break}case"response.function_call_arguments.done":{let B=String(K.item_id??""),W=J.get(B);if(!W)break;W.done=!0,yield{type:"tool-call",toolCallId:W.callId,name:W.name,args:String(K.arguments??""),...W.namespace?{namespace:W.namespace}:{}};break}case"response.output_item.done":{let B=K.item;if(!B)break;if(B.type==="function_call"){let W=String(B.id??K.item_id??B.call_id??""),q=J.get(W);if(q?.done)break;let F=(typeof B.namespace==="string"?B.namespace:"")||q?.namespace;if(yield{type:"tool-call",toolCallId:String(B.call_id??W),name:String(B.name??q?.name??""),args:String(B.arguments??""),...F?{namespace:F}:{}},q)q.done=!0;break}if(B.type==="tool_search_call"||B.type==="tool_search_output"){if(B.type==="tool_search_call"&&B.arguments!==void 0)Y=B.arguments;let W=F6(B);if(W.loaded.length===0&&W.namespaces.length===0)break;let q=String(B.tool_search_call_id??B.id??"");if(Z.has(q))break;Z.add(q);let F=Y;Y=void 0,yield{type:"tool-search",...W,...F!==void 0&&F!==null?{arguments:F}:{}}}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":{G=!0,yield z("stop",MQ(K.response?.usage));break}case"response.incomplete":{G=!0;let B=MQ(K.response?.usage),W=K.response?.incomplete_details?.reason;if(W==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:N6(K.response?.content_filters),retryable:!1}},yield z("error",B);break}yield z(W==="max_output_tokens"?"length":"stop",B);break}case"response.failed":case"error":{G=!0;let B=K.response?.error??K.error??K;yield{type:"error",error:L6(B),...GQ(B)},yield z("error",MQ(K.response?.usage));break}}if(G)return}if(!G)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield z("error",D())}function F6(Q){let $=[],J=[];return N5(Q.results??Q.tools??Q.loaded??Q.output,$,J,0),{loaded:SQ($),namespaces:SQ(J)}}function N5(Q,$,J,Z){if(!Array.isArray(Q)||Z>4)return;for(let Y of Q){if(typeof Y==="string"){$.push(Y);continue}if(!Y||typeof Y!=="object")continue;let G=Y,V=typeof G.name==="string"?G.name:typeof G.tool_name==="string"?G.tool_name:"",z=G.tools??G.functions;if(Array.isArray(z)){if(V)J.push(V);N5(z,$,J,Z+1);continue}if(V)$.push(V)}}function SQ(Q){return Q.filter(($,J)=>Q.indexOf($)===J)}function N6(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 Y=Z,G=Y.content_filter_results;if(!G||typeof G!=="object")continue;for(let[V,z]of Object.entries(G))if(z&&typeof z==="object"&&z.filtered===!0)J.push(`${V} (${String(Y.source_type??"unknown")})`)}return J.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${SQ(J).join(", ")}.`}function L6(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 D(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function MQ(Q){if(!Q)return D();let $=Number(Q.input_tokens??0),J=Number(Q.output_tokens??0),Z={inputTokens:$,outputTokens:J,totalTokens:Number(Q.total_tokens??$+J)},Y=Q.output_tokens_details?.reasoning_tokens;if(typeof Y==="number")Z.reasoningTokens=Y;let G=Q.input_tokens_details?.cached_tokens;if(typeof G==="number")Z.cachedInputTokens=G;return Z}async function*L5(Q){if(!Q)return;let $=Q.getReader(),J=new TextDecoder;try{while(!0){let{done:Y,value:G}=await $.read();if(Y)break;if(G)yield J.decode(G,{stream:!0})}let Z=J.decode();if(Z)yield Z}finally{$.releaseLock()}}function BQ(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,maxToolArgumentWhitespace:Q.maxToolArgumentWhitespace,maxRetries:Q.maxRetries,...Q.retry?{retry:Q.retry}:{}}}async function*KQ(Q,$,J){let Z=J.parse??F5,Y=$,G=new Set,V=0,z=!1,H=Math.max(0,Q.maxRetries),K=Q.random??Math.random,X,j=(P)=>{if(!X)return P;let S=g(g(D(),X),P.usage);return X=void 0,{...P,usage:S}},B=(P)=>j({type:"finish",reason:"aborted",usage:P??D()}),W=(P)=>g(g(D(),X??D()),P),q=Q.streamIdleTimeoutMs??0,F=Q.streamMaxDurationMs??0,x=Q.maxToolArgumentChars??0,U=Q.maxToolArgumentWhitespace??0,p=Q.now??Date.now,I=p();for(let P=0;;P++){let S=new AbortController,o=J.signal?AbortSignal.any([J.signal,S.signal]):S.signal,k;while(k===void 0)try{let N=[],C=()=>{},L=m(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify(Y)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:o,fetchImpl:Q.fetchImpl,sleep:Q.sleep,random:Q.random,now:Q.now,startedAt:I,...Q.retry?{retry:Q.retry}:{},onRetry:(R)=>{N.push({type:"retry",...R,phase:"request"}),C()}}),_=L.then(()=>!0,()=>!0);for(;;){let R=new Promise((y)=>C=()=>y(!1)),b=await Promise.race([_,R]);if(yield*N.splice(0),b)break}k=await L}catch(N){let C=Y,L=J.files&&V<j5?z5(C,N,J.files).filter((b)=>!G.has(b)):[];if(L.length>0){V++;let b=M(N).message;for(let y of L)G.add(y),yield{type:"file-rejected",fileId:y,message:b,...f(N)};Y=q5(C,new Set(L),J.files);continue}let _=z?null:C5(Y,N);if(_){z=!0,Y=_;continue}let R=M(N);if(R.code==="aborted"){yield B();return}yield{type:"error",error:R,...f(N)},yield j({type:"finish",reason:"error",usage:D()});return}let T=[],l=!1,u,zQ=!1,E,w=new Map,v,rQ=()=>v?{usage:W(v)}:{},t;try{let N=Y5(k.body,{idleMs:q,maxMs:F},{idle:()=>{let C=new U5(q);return S.abort(C),C},max:()=>{let C=new D5(F);return S.abort(C),C}});for await(let C of Z(L5(N),{structuredOutput:J.structuredOutput,onUsage:(L)=>v=L})){if(C.type==="usage"){v=C.usage,yield{type:"usage",usage:W(C.usage)};continue}if(C.type==="tool-call-delta"){let L=w.get(C.toolCallId);if(!L)w.set(C.toolCallId,L=P6());U6(L,C.argsDelta,U>0);let _=L.chars;if(U>0&&L.space>U){let R=L.text.trimEnd(),b=D6(R);if(x6(C.name,C.toolCallId,_,L.space,U,b),!b){let y=new x5(U,C.name,C.toolCallId,_,L.space);throw S.abort(y),y}w.delete(C.toolCallId),t={type:"tool-call",toolCallId:C.toolCallId,name:C.name,args:R,...C.namespace?{namespace:C.namespace}:{}};break}if(x>0&&_>x){let R=new RQ(x,C.name,C.toolCallId,_);throw S.abort(R),R}yield C;continue}if(C.type==="tool-call")w.delete(C.toolCallId);if(l){yield C.type==="finish"?j(C):C;continue}if(VQ(C)){l=!0,yield*T.splice(0),yield C;continue}if(C.type==="error")u=C.error;T.push(C)}if(t)await N?.cancel().catch(()=>{})}catch(N){zQ=N instanceof JQ;let C=M(N);if(C.code==="aborted"||J.signal?.aborted){yield B(v);return}if(N instanceof RQ)E=N.detail;if(l){yield{type:"error",error:C,...E?{toolArgumentsTooLong:E}:{},...rQ()},yield j({type:"finish",reason:"error",usage:v??D()});return}u=C,T.push({type:"error",error:C,...E?{toolArgumentsTooLong:E}:{},...rQ()},{type:"finish",reason:"error",usage:v??D()})}if(t){if(S.abort(),!l)yield*T.splice(0);if(yield t,w.size>0)yield{type:"tool-call-discard",toolCallIds:[...w.keys()]};yield j({type:"finish",reason:"stop",usage:v??D()});return}if(l)return;let e={};for(let N of T)if(N.type==="error")e=f(N);let QQ=!u?.retryable||J.signal?.aborted||E&&J.retryToolArgumentsTooLong===!1?void 0:P<H?$Q(P,K):Q.retry&&CQ(Q.retry,u,{...e.status!==void 0?{status:e.status}:{},timedOut:zQ,...E?{toolArgumentsTooLong:E}:{}})?FQ(Q.retry,P-H,u.retryAfter,p()-I,K):void 0;if(QQ!==void 0){let N;for(let _ of T)if(_.type==="finish")N=g(N??D(),_.usage);if(N)X=g(X??D(),N);let C=N&&N.totalTokens>0?{usage:N}:{};if(w.size>0)yield{type:"tool-call-discard",toolCallIds:[...w.keys()]};let L=p()-I;if(yield{type:"retry",attempt:P+1,maxRetries:H,error:u,...e,...C,phase:"stream",timedOut:zQ,...E?{toolArgumentsTooLong:E}:{},delayMs:QQ,elapsedMs:L,...Q.retry?{remainingMs:Math.max(0,Q.retry.patienceMs-L-QQ)}:{}},X&&X.totalTokens>0)yield{type:"usage",usage:W(D())};try{await NQ(QQ,J.signal,Q.sleep)}catch{yield B();return}continue}for(let N of T)yield N.type==="finish"?j(N):N;return}}function P6(){return{chars:0,text:"",inString:!1,escaped:!1,space:0}}function U6(Q,$,J){if(Q.chars+=$.length,!J)return;Q.text+=$;for(let Z of $){if(Q.inString){if(Q.escaped)Q.escaped=!1;else if(Z==="\\")Q.escaped=!0;else if(Z==='"')Q.inString=!1}else if(Z===" "||Z===`
|
|
6
6
|
`||Z==="\r"||Z==="\t"){Q.space++;continue}else if(Z==='"')Q.inString=!0;Q.space=0}}function D6(Q){try{return JSON.parse(Q),!0}catch{return!1}}function x6(Q,$,J,Z,Y,G){let V=`[gemi/ai] tool call "${Q}" ran away in white space (more than ${Y} characters, maxToolArgumentWhitespace); ${G?"its arguments were whole JSON, so it was finished as written":"its arguments were not whole JSON, so it was cut"}`,z={tool:Q,toolCallId:$,chars:J,whitespace:Z,limit:Y,whole:G},H=!1;try{P5.warning(V,z),H=!0}catch{}if(!H||Bun.env.NODE_ENV==="development")console.warn(V,z)}async function WQ(Q,$,J="user_data"){let Z=new FormData;if(J)Z.set("purpose",J);Z.set("file",$);let G=await(await m(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:Z},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl})).json();if(!G?.id)throw Error("The provider accepted the upload but returned no file id.");return G.id}async function XQ(Q,$){let J=Q.filesUrl.indexOf("?"),Z=J===-1?Q.filesUrl:Q.filesUrl.slice(0,J),Y=J===-1?"":Q.filesUrl.slice(J);try{await(await m(`${Z}/${encodeURIComponent($)}${Y}`,{method:"DELETE",headers:await Q.headers()},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl,...Q.sleep?{sleep:Q.sleep}:{},...Q.random?{random:Q.random}:{}})).body?.cancel()}catch(G){if(G instanceof A&&G.status===404)return;throw G}}function AQ(Q,$){let{capabilities:J}=$,Z={model:$.model,input:O6(Q.messages,J,Q.tools),stream:!0};if(Q.trailingContext)Z.input.push({role:"developer",content:[{type:"input_text",text:Q.trailingContext}]});if(Q.systemPrompt)Z.instructions=Q.systemPrompt;let Y=M5(Q.tools,J),G;if(Q.allowedTools)if(Y.every((V)=>V.type==="function"))G=Q.allowedTools;else Y=M5(k6(Q.tools??[],Q.allowedTools),J);if(Y.length>0){if(Z.tools=Y,!J.parallelToolCalls)Z.parallel_tool_calls=!1;let V=Q.toolChoice;if(G&&V!=="none"&&typeof V!=="object")Z.tool_choice={type:"allowed_tools",mode:V==="required"?"required":"auto",tools:G.map((z)=>({type:"function",name:z}))};else if(V!==void 0)Z.tool_choice=typeof V==="string"?V:{type:"function",name:V.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 O6(Q,$,J){let Z=[],Y=new Map;if($.toolSearch){for(let G of J??[])if(s(G))Y.set(G.name,G)}for(let G of Q){let V=G.role,z=!A6.has(G.finishReason),H=[],K=()=>{if(H.length===0)return;Z.push({type:"message",role:V,content:H}),H=[]};for(let X of G.content??[])switch(X.type){case"text":{if(!X.text)break;H.push(c(V,X.text));break}case"output":{if(X.partial)break;H.push(c(V,JSON.stringify(X.value)));break}case"file":{if(V==="assistant")break;let j=TQ(X);if(!$.fileInput){if(j)H.push(c(V,r(X,!1)));break}if(kQ(X,j),X.providerRejected){if(j)H.push(c(V,r(X,!1)));H.push(c(V,n(X.name)));break}if(j)H.push(c(V,r(X,!!X.fileId)));if(X.fileId)H.push(_6(X));break}case"reasoning":{if(K(),!z)break;let j=T6(X);if(j)Z.push(j);break}case"tool-call":{if(X.partial)break;if(K(),$.toolSearch&&Array.isArray(X.toolSearches))for(let B of X.toolSearches)Z.push(...E6(B,J??[]));let j={type:"function_call",call_id:X.toolCallId,name:String(X.name),arguments:JSON.stringify(X.input??{})};if(X.namespace&&Y.has(X.namespace))j.namespace=X.namespace;Z.push(j);break}case"tool-result":{K(),Z.push({type:"function_call_output",call_id:X.toolCallId,output:wQ(X)});break}}K()}return S6(Z)}var M6="No result was recorded for this tool call. Assume it did not complete.";function S6(Q){let $=new Set,J=new Set,Z=[];for(let G of Q){if(G.type==="function_call"){let V=String(G.call_id);if($.has(V))continue;$.add(V)}else if(G.type==="function_call_output"){let V=String(G.call_id);if(!$.has(V)||J.has(V))continue;J.add(V)}Z.push(G)}if(J.size===$.size)return Z;let Y=[];for(let G of Z){if(Y.push(G),G.type!=="function_call")continue;let V=String(G.call_id);if(J.has(V))continue;J.add(V),Y.push({type:"function_call_output",call_id:V,output:M6})}return Y}function c(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function TQ(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(IQ)?$:void 0}function r(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 _6(Q){return{type:EQ(Q)?"input_image":"input_file",file_id:Q.fileId}}function EQ(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return $?$.startsWith("image/")&&$!=="image/svg+xml":R6(Q.name)}function kQ(Q,$){if(Q.fileId?.startsWith(IQ))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 R6(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&I6.has($[1])}var I6=new Set(["jpeg","jpg","png","gif","webp"]),A6=new Set(["error","aborted","interrupted"]);function T6(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function wQ(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.${$}`;if(Q.cause==="denied-earlier")return`The user already declined this tool call earlier in this conversation, so it did not run and they were not asked again. Do not ask for it again; carry on without 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 E6(Q,$){let J=new Set(O5(Q?.loaded)),Z=O5(Q?.namespaces),Y=new Set(Z),G=[];for(let z of $)if(s(z)){if(!Y.has(z.name))continue;let H=z.tools.filter((K)=>J.size===0||J.has(K.name));if(H.length===0)continue;G.push({type:"namespace",name:z.name,description:z.description,tools:H.map((K)=>d(K,!0))})}else if(z.deferred&&J.has(z.name))G.push(d(z,!0));if(G.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:Q.arguments&&typeof Q.arguments==="object"?Q.arguments:{paths:Z.length>0?Z:[...J]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:G}]}function O5(Q){return Array.isArray(Q)?Q.filter(($)=>typeof $==="string"):[]}function s(Q){return Array.isArray(Q.tools)}function M5(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let Y=[];for(let G of Q)if(s(G))for(let V of G.tools)Y.push(d(V,!1));else Y.push(d(G,!1));return Y}let J=[],Z=!1;for(let Y of Q)if(s(Y)){let G=Y.tools.map((V)=>{if(V.deferred)Z=!0;return d(V,!0)});J.push({type:"namespace",name:Y.name,description:Y.description,tools:G})}else{if(Y.deferred)Z=!0;J.push(d(Y,!0))}if(Z)J.push({type:"tool_search"});return J}function k6(Q,$){let J=new Set($);return Q.flatMap((Z)=>{if(!s(Z))return J.has(Z.name)?[Z]:[];let Y=Z.tools.filter((G)=>J.has(G.name));return Y.length>0?[{...Z,tools:Y}]:[]})}function d(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 w6=64000;function S5(Q,$){let J={model:$.model,max_tokens:Q.maxOutputTokens??w6,messages:l6(Q.messages,$.capabilities),stream:!0},Z=Q.output,Y=!!Z?.strict&&!c6(Z.schema),G=Z&&!Y?d6(Z.schema):void 0,V=[Q.systemPrompt,G].filter(Boolean);if(V.length>0)J.system=[{type:"text",text:V.join(`
|
|
7
7
|
|
|
8
8
|
`)}];let z=$.capabilities.reasoning?Q.reasoning:void 0;if(z==="none"){if(/^claude-sonnet-5-5(?:-\d{8})?$/.test($.modelId))J.thinking={type:"between_tools"};J.output_config={effort:"low"}}else if(z)J.thinking={type:"adaptive",display:"summarized"},J.output_config={effort:h6(z,$.modelId)};else if($.capabilities.reasoning&&b6(J.messages))J.thinking={type:"adaptive"};if(J.thinking?.type==="adaptive"&&$.blockBinding)J.thinking.block_binding={prefix_mismatch_behavior:"drop_block"};if(Z&&Y)J.output_config={...J.output_config,format:{type:"json_schema",schema:m6(Z.schema)}};let H=$7(Q.tools);if(H.length>0){J.tools=H;let K=p6(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 v6(y6(J),Q.trailingContext)}function v6(Q,$){if(!$)return Q;let J={type:"text",text:$},Z=Q.messages.at(-1);if(Z?.role==="user")Z.content=[...Z.content,J];else Q.messages.push({role:"user",content:[J]});return Q}function b6(Q){return Q.some(($)=>$.content.some((J)=>J.type==="thinking"||J.type==="redacted_thinking"))}var vQ="thinking-binding-controls-2026-08-01";function _5(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 R5(Q){let $=[];for(let J of Q.messages){let Z=J.content.filter((G)=>G.type!=="thinking"&&G.type!=="redacted_thinking");if(Z.length===0)continue;let Y=$.at(-1);if(Y?.role===J.role)Y.content.push(...Z);else $.push({role:J.role,content:Z})}return{...Q,messages:$}}function h6(Q,$){if(Q==="none"||Q==="minimal")return"low";if(Q==="xhigh"&&/^claude-(?:opus|sonnet)-4-6(?:-|$)/.test($))return"high";return Q}function y6(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 f6=new Set(["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","maxItems","uniqueItems"]),g6=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),u6=/\\[1-9]|\(\?<?[=!]|\\[bB]/,I5=new Set(["properties","patternProperties","$defs","definitions"]);function m6(Q){let $=(J)=>{if(Array.isArray(J))return J.map($);if(!h(J))return J;let Z={},Y=[];for(let[G,V]of Object.entries(J)){if(f6.has(G)||G==="minItems"&&typeof V==="number"&&V>1||G==="format"&&typeof V==="string"&&!g6.has(V)||G==="pattern"&&typeof V==="string"&&u6.test(V)){Y.push(`${G}: ${JSON.stringify(V)}`);continue}Z[G]=I5.has(G)&&h(V)?Object.fromEntries(Object.entries(V).map(([H,K])=>[H,$(K)])):$(V)}if(Y.length>0){let G=`{${Y.join(", ")}}`;Z.description=typeof Z.description==="string"?`${Z.description} ${G}`:G}if(Z.type==="object"||h(Z.properties))Z.additionalProperties=!1;return Z};return $(Q)}function c6(Q){let $=0,J=0,Z=(Y)=>{if(Array.isArray(Y))return Y.forEach(Z);if(!h(Y))return;if(Array.isArray(Y.anyOf)||Array.isArray(Y.type))J++;if(h(Y.properties)){let G=new Set(Array.isArray(Y.required)?Y.required:[]);$+=Object.keys(Y.properties).filter((V)=>!G.has(V)).length}for(let[G,V]of Object.entries(Y))if(I5.has(G)&&h(V))Object.values(V).forEach(Z);else Z(V)};return Z(Q),$>24||J>16}function d6(Q){return`Answer with only a JSON value (no prose, no code fence) that matches this JSON schema:
|
|
9
|
-
${JSON.stringify(Q)}`}function p6(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 l6(Q,$){let J=[],Z=new Map;for(let X of Q){let j=X.role==="assistant"?"assistant":"user";J.push("step-end");for(let B of X.content??[])switch(B.type){case"text":{if(j==="assistant"?!!B.text:!!B.text?.trim())J.push({role:j,block:{type:"text",text:B.text}});break}case"output":{if(B.partial)break;let W=B.text??JSON.stringify(B.value);J.push({role:j,block:{type:"text",text:W}});break}case"file":{if(j==="assistant")break;for(let W of o6(B,$))J.push({role:j,block:W});break}case"reasoning":{let W=j==="assistant"?a6(B):void 0;if(W)J.push({role:j,block:W});break}case"tool-call":{if(B.partial)break;J.push({role:"assistant",block:{type:"tool_use",id:B.toolCallId,name:String(B.name),input:h(B.input)?B.input:{}}});break}case"tool-result":{if(J.push("step-end"),Z.has(B.toolCallId))break;Z.set(B.toolCallId,{type:"tool_result",tool_use_id:B.toolCallId,content:wQ(B),...B.status==="error"?{is_error:!0}:{}});break}}}let Y=[],G=(X,j)=>{let B=Y[Y.length-1];if(B&&B.role===X)B.content.push(j);else Y.push({role:X,content:[j]})},V=new Set,z=[],H=!1,K=()=>{for(let X of z)G("user",Z.get(X)??s6(X));z=[],H=!1};for(let X of J){if(X==="step-end"){H=!0;continue}let{role:j,block:B}=X;if(H||j==="user")K();if(B.type==="tool_use"){let W=String(B.id);if(V.has(W))continue;V.add(W),z.push(W)}G(j,B)}if(K(),Y[0]?.role==="assistant")Y.unshift({role:"user",content:[{type:"text",text:i6}]});if(Y.at(-1)?.role==="assistant")Y.push({role:"user",content:[{type:"text",text:n6}]});return Y}var i6="(The conversation continues from an earlier point.)",n6="Continue.",r6="No result was recorded for this tool call. Assume it did not complete.";function s6(Q){return{type:"tool_result",tool_use_id:Q,content:r6}}function a6(Q){let $=Q.providerMetadata?.anthropic;if(!h($))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 o6(Q,$){let J=TQ(Q),Z=(G)=>J?[{type:"text",text:r(Q,G)}]:[];if(!$.fileInput)return Z(!1);if(kQ(Q,J),!Q.fileId)return Z(!1);let Y=Q.providerRejected?void 0:e6(Q);if(!Y)return[...Z(!1),{type:"text",text:n(Q.name)}];return[...Z(!0),{type:Y,source:{type:"file",file_id:Q.fileId}}]}var t6=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function e6(Q){let $=Q.mimeType?.trim().toLowerCase()??"";if(EQ(Q))return!$||t6.has($)?"image":void 0;if($)return $==="application/pdf"||$==="text/plain"?"document":void 0;return/\.(pdf|txt)$/i.test(Q.name??"")?"document":void 0}function h(Q){return!!Q&&typeof Q==="object"&&!Array.isArray(Q)}function Q7(Q){return Array.isArray(Q.tools)}function $7(Q){let $=[];for(let J of Q??[])for(let Z of Q7(J)?J.tools:[J])$.push({name:Z.name,description:Z.description,input_schema:Z.parameters,eager_input_streaming:!0});return $}async function*k5(Q,$={}){let J=new Map,Z=[],Y,G={},V,z,H=!1,K=(X)=>({type:"finish",reason:X,usage:a(G),...Y?{model:Y}:{}});for await(let X of _Q(Q)){let j;try{j=JSON.parse(X.data)}catch{continue}switch(typeof j.type==="string"?j.type:X.event){case"message_start":{let W=j.message??{};if(typeof W.model==="string"&&W.model)Y=W.model;G=E5(G,W.usage),$.onUsage?.(a(G)),yield{type:"usage",usage:a(G)};break}case"content_block_start":{let W=Number(j.index),q=j.content_block??{},F={type:String(q.type??""),id:typeof q.id==="string"?q.id:void 0,name:typeof q.name==="string"?q.name:void 0,args:"",signature:typeof q.signature==="string"?q.signature:""};if(J.set(W,F),F.type==="redacted_thinking")yield{type:"reasoning-delta",delta:"",providerMetadata:{anthropic:{type:"redacted_thinking",data:String(q.data??"")}}};if(F.type==="text"&&typeof q.text==="string"&&q.text)yield T5(q.text,$);break}case"content_block_delta":{let W=J.get(Number(j.index)),q=j.delta??{};if(!W)break;if(q.type==="text_delta"){let F=String(q.text??"");if(F)yield T5(F,$)}else if(q.type==="thinking_delta"){let F=String(q.thinking??"");if(F)yield{type:"reasoning-delta",delta:F}}else if(q.type==="signature_delta")W.signature+=String(q.signature??"");else if(q.type==="input_json_delta"&&W.type==="tool_use"){let F=String(q.partial_json??"");if(!F)break;W.args+=F,yield{type:"tool-call-delta",toolCallId:W.id??"",name:W.name??"",argsDelta:F}}break}case"content_block_stop":{let W=Number(j.index),q=J.get(W);if(J.delete(W),q?.type==="thinking")yield{type:"reasoning-delta",delta:"",providerMetadata:{anthropic:{type:"thinking",signature:q.signature}}};if(q?.type==="tool_use")if(q.args||="{}",J7(q.args))yield A5(q);else Z.push(q);break}case"message_delta":{if(typeof j.delta?.stop_reason==="string")V=j.delta.stop_reason;if(j.delta?.stop_details)z=j.delta.stop_details;G=E5(G,j.usage),$.onUsage?.(a(G)),yield{type:"usage",usage:a(G)};break}case"message_stop":{if(H=!0,V==="refusal"){yield{type:"error",error:Y7(z)},yield K("error");break}let W=Z7(V);if(Z.length>0&&W==="length")yield{type:"tool-call-discard",toolCallIds:Z.map((q)=>q.id??"")};else for(let q of Z)yield A5(q);yield K(W);break}case"error":{H=!0;let W=j.error??j;yield{type:"error",error:G7(W),...GQ(W)},yield K("error");break}}if(H)return}yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield K("error")}function A5(Q){return{type:"tool-call",toolCallId:Q.id??"",name:Q.name??"",args:Q.args}}function J7(Q){try{return JSON.parse(Q),!0}catch{return!1}}function T5(Q,$){return $.structuredOutput?{type:"output-delta",delta:Q}:{type:"text-delta",delta:Q}}function Z7(Q){if(Q==="max_tokens"||Q==="model_context_window_exceeded")return"length";return"stop"}function Y7(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 G7(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 E5(Q,$){if(!$||typeof $!=="object")return Q;let J={...Q};for(let Y of["input_tokens","output_tokens","cache_creation_input_tokens","cache_read_input_tokens"])if(typeof $[Y]==="number")J[Y]=$[Y];let Z=$.output_tokens_details?.thinking_tokens;if(typeof Z==="number")J.thinking_tokens=Z;return J}function a(Q){if(!Q)return D();let{cache_read_input_tokens:$,cache_creation_input_tokens:J}=Q,Z=(Q.input_tokens??0)+($??0)+(J??0),Y=Q.output_tokens??0,G={inputTokens:Z,outputTokens:Y,totalTokens:Z+Y};if(typeof $==="number")G.cachedInputTokens=$;if(typeof J==="number")G.cacheWriteInputTokens=J;if(typeof Q.thinking_tokens==="number")G.reasoningTokens=Q.thinking_tokens;return G}function bQ(Q){let $=HQ(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1,supportsForcedToolChoice:!0};let J=v5($);if(J?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:J.major>1,toolSearch:w5(J),supportsForcedToolChoice:!0};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:w5(J),supportsForcedToolChoice:!0};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0,supportsForcedToolChoice:!0}}function w5(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function hQ(Q){let $=v5(HQ(Q));return{trailingContext:!0,allowedTools:!$||$.kind==="gpt"&&$.major>=5}}function yQ(){return{trailingContext:!0}}function fQ(Q){let $=HQ(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,supportsForcedToolChoice:V7(Q)}}function V7(Q){let $=HQ(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 HQ(Q){return Q.trim().toLowerCase()}function v5(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}var gQ=120000,uQ=2,mQ=120000,cQ=300000,dQ=1000;function O(Q){return typeof process>"u"?void 0:process.env?.[Q]}var B7="preview";function b5(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function K7(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}function pQ(Q,$={}){return{base:(Q.baseURL??O("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=Q.apiKey??O("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??gQ,streamIdleTimeoutMs:Q.streamIdleTimeoutMs??mQ,streamMaxDurationMs:Q.streamMaxDurationMs??cQ,maxToolArgumentChars:Q.maxToolArgumentChars??0,maxToolArgumentWhitespace:Q.maxToolArgumentWhitespace??dQ,maxRetries:Q.maxRetries??uQ,...iQ(Q)}}function h5(Q){let $=Q.baseURL??Q.endpoint??O("AZURE_OPENAI_ENDPOINT");if($)return b5($);let J=Q.resourceName??O("AZURE_OPENAI_RESOURCE_NAME")??O("AZURE_RESOURCE_NAME");return J?b5(`https://${J.trim()}.cognitiveservices.azure.com`):""}function lQ(Q,$={}){let J=Q.apiVersion??O("AZURE_OPENAI_API_VERSION")??B7;return{base:`${h5(Q)}${K7(J)}`,query:`?api-version=${encodeURIComponent(J)}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let Z=Q.apiKey??O("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??gQ,streamIdleTimeoutMs:Q.streamIdleTimeoutMs??mQ,streamMaxDurationMs:Q.streamMaxDurationMs??cQ,maxToolArgumentChars:Q.maxToolArgumentChars??0,maxToolArgumentWhitespace:Q.maxToolArgumentWhitespace??dQ,maxRetries:Q.maxRetries??uQ,...iQ(Q)}}var W7="2026-10-21";function y5(Q,$={}){let J=Q.baseURL??O("ANTHROPIC_BASE_URL")??"https://api.anthropic.com";return g5(J,Q,$,async()=>{let Z=Q.workspaceId??O("ANTHROPIC_WORKSPACE_ID"),Y=Z?{"anthropic-workspace-id":Z}:{},G=Q.apiKey??O("ANTHROPIC_API_KEY");if(G)return{"x-api-key":G,...Y};let V=O("ANTHROPIC_AUTH_TOKEN");return V?{authorization:`Bearer ${V}`,...Y}:Y})}function f5(Q,$={}){let J=Q.resourceName??O("ANTHROPIC_FOUNDRY_RESOURCE"),Z=Q.baseURL??Q.endpoint??O("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 g5(Z,Q,$,async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`};let Y=Q.apiKey??O("ANTHROPIC_FOUNDRY_API_KEY");return Y?{"api-key":Y}:{}})}function g5(Q,$,J,Z){return{base:`${Q.trim().replace(/\/+$/,"").replace(/\/v1$/,"")}/v1`,query:"",headers:async()=>({...await Z(),"anthropic-version":W7,...$.headers}),timeoutMs:$.timeoutMs??J.timeoutMs??gQ,streamIdleTimeoutMs:$.streamIdleTimeoutMs??mQ,streamMaxDurationMs:$.streamMaxDurationMs??cQ,maxToolArgumentChars:$.maxToolArgumentChars??0,maxToolArgumentWhitespace:$.maxToolArgumentWhitespace??dQ,maxRetries:$.maxRetries??uQ,...iQ($)}}function u5(Q,$={}){return{...lQ(Q,$),base:`${h5(Q)}/v1`,query:""}}function iQ(Q){return Q5(Q.retry),Q.retry?{retry:Q.retry}:{}}class jQ{static models(){return[]}normalizeError(Q){return M(Q)}}var m5=["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 c5 extends jQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities={...bQ(Q),...hQ(Q)},this.config=$}static model(Q,$){return new c5(Q,$)}static models(){return m5}stream(Q){let $=AQ(Q,{model:this.model,capabilities:this.capabilities});return KQ(this.endpoint(),$,{signal:Q.signal,retryToolArgumentsTooLong:Q.retryToolArgumentsTooLong,structuredOutput:Boolean(Q.output),files:DQ(Q.messages)})}upload(Q){return WQ(this.endpoint(),Q)}deleteFile(Q){return XQ(this.endpoint(),Q)}endpoint(){return BQ(pQ(this.config))}get realtime(){return new YQ(pQ(this.config,{timeoutMs:PQ}),{model:this.model})}}var X7=["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 nQ extends jQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities={...fQ(Q),...yQ()},this.config=$}static model(Q,$){return new nQ(Q,$)}static models(){return X7}stream(Q){return this.send(Q)}async*send(Q){let $=Q,J=!1,Z=new Set;for(;;){let Y=this.request($);if(J)Y=R5(Y);let G,V=!1;for await(let z of KQ(this.endpointFor(Y),Y,{signal:Q.signal,retryToolArgumentsTooLong:Q.retryToolArgumentsTooLong,structuredOutput:Boolean(Q.output),parse:k5})){if(G)continue;if(!V&&z.type==="error"&&z.status===400){let H=_5(z.error.message);if(H&&!Z.has(H)){Z.add(H),G=H;continue}}if(VQ(z))V=!0;yield z}if(!G)return;if(G==="thinking")J=!0;else if($.output)$={...$,output:{...$.output,strict:!1}}}}request(Q){return S5(Q,{model:this.deployment(),modelId:this.model,capabilities:this.capabilities,forcedToolChoice:this.capabilities.supportsForcedToolChoice!==!1,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(),Y=Z["anthropic-beta"];return{...Z,"anthropic-beta":Y?`${Y},${vQ}`:vQ}}}}bindsThinking(){return!0}deployment(){return this.model}upload(Q){return WQ(this.endpoint(),Q,null)}deleteFile(Q){return XQ(this.endpoint(),Q)}endpoint(){return d5(y5(this.config))}}function d5(Q){return{...BQ(Q),responsesUrl:`${Q.base}/messages`}}class p5 extends nQ{constructor(Q,$={}){super(Q,$);this.capabilities={...fQ(Q),...yQ(),fileInput:!1}}static model(Q,$){return new p5(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."))}deleteFile(Q){return Promise.reject(Error("AzureAnthropicProvider does not delete files: the Files API is not available on Azure-hosted Foundry deployments."))}deployment(){return this.config.deployment??this.model}bindsThinking(){return!1}endpoint(){return d5(f5(this.config))}}class l5 extends jQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities={...bQ(Q),...hQ(Q)},this.config=$}static model(Q,$){return new l5(Q,$)}static models(){return m5}stream(Q){let $=AQ(Q,{model:this.deployment(),capabilities:this.capabilities});return KQ(this.endpoint(),$,{signal:Q.signal,retryToolArgumentsTooLong:Q.retryToolArgumentsTooLong,structuredOutput:Boolean(Q.output),files:DQ(Q.messages)})}upload(Q){return WQ(this.endpoint(),Q,"assistants")}deleteFile(Q){return XQ(this.endpoint(),Q)}deployment(){return this.config.deployment??this.model}endpoint(){return BQ(lQ(this.config))}get realtime(){return new YQ(u5(this.config,{timeoutMs:PQ}),{model:this.deployment(),callFlow:"ephemeral"})}}
|
|
9
|
+
${JSON.stringify(Q)}`}function p6(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 l6(Q,$){let J=[],Z=new Map;for(let X of Q){let j=X.role==="assistant"?"assistant":"user";J.push("step-end");for(let B of X.content??[])switch(B.type){case"text":{if(j==="assistant"?!!B.text:!!B.text?.trim())J.push({role:j,block:{type:"text",text:B.text}});break}case"output":{if(B.partial)break;let W=B.text??JSON.stringify(B.value);J.push({role:j,block:{type:"text",text:W}});break}case"file":{if(j==="assistant")break;for(let W of o6(B,$))J.push({role:j,block:W});break}case"reasoning":{let W=j==="assistant"?a6(B):void 0;if(W)J.push({role:j,block:W});break}case"tool-call":{if(B.partial)break;J.push({role:"assistant",block:{type:"tool_use",id:B.toolCallId,name:String(B.name),input:h(B.input)?B.input:{}}});break}case"tool-result":{if(J.push("step-end"),Z.has(B.toolCallId))break;Z.set(B.toolCallId,{type:"tool_result",tool_use_id:B.toolCallId,content:wQ(B),...B.status==="error"?{is_error:!0}:{}});break}}}let Y=[],G=(X,j)=>{let B=Y[Y.length-1];if(B&&B.role===X)B.content.push(j);else Y.push({role:X,content:[j]})},V=new Set,z=[],H=!1,K=()=>{for(let X of z)G("user",Z.get(X)??s6(X));z=[],H=!1};for(let X of J){if(X==="step-end"){H=!0;continue}let{role:j,block:B}=X;if(H||j==="user")K();if(B.type==="tool_use"){let W=String(B.id);if(V.has(W))continue;V.add(W),z.push(W)}G(j,B)}if(K(),Y[0]?.role==="assistant")Y.unshift({role:"user",content:[{type:"text",text:i6}]});if(Y.at(-1)?.role==="assistant")Y.push({role:"user",content:[{type:"text",text:n6}]});return Y}var i6="(The conversation continues from an earlier point.)",n6="Continue.",r6="No result was recorded for this tool call. Assume it did not complete.";function s6(Q){return{type:"tool_result",tool_use_id:Q,content:r6}}function a6(Q){let $=Q.providerMetadata?.anthropic;if(!h($))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 o6(Q,$){let J=TQ(Q),Z=(G)=>J?[{type:"text",text:r(Q,G)}]:[];if(!$.fileInput)return Z(!1);if(kQ(Q,J),!Q.fileId)return Z(!1);let Y=Q.providerRejected?void 0:e6(Q);if(!Y)return[...Z(!1),{type:"text",text:n(Q.name)}];return[...Z(!0),{type:Y,source:{type:"file",file_id:Q.fileId}}]}var t6=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function e6(Q){let $=Q.mimeType?.trim().toLowerCase()??"";if(EQ(Q))return!$||t6.has($)?"image":void 0;if($)return $==="application/pdf"||$==="text/plain"?"document":void 0;return/\.(pdf|txt)$/i.test(Q.name??"")?"document":void 0}function h(Q){return!!Q&&typeof Q==="object"&&!Array.isArray(Q)}function Q7(Q){return Array.isArray(Q.tools)}function $7(Q){let $=[];for(let J of Q??[])for(let Z of Q7(J)?J.tools:[J])$.push({name:Z.name,description:Z.description,input_schema:Z.parameters,eager_input_streaming:!0});return $}async function*k5(Q,$={}){let J=new Map,Z=[],Y,G={},V,z,H=!1,K=(X)=>({type:"finish",reason:X,usage:a(G),...Y?{model:Y}:{}});for await(let X of _Q(Q)){let j;try{j=JSON.parse(X.data)}catch{continue}switch(typeof j.type==="string"?j.type:X.event){case"message_start":{let W=j.message??{};if(typeof W.model==="string"&&W.model)Y=W.model;G=E5(G,W.usage),$.onUsage?.(a(G)),yield{type:"usage",usage:a(G)};break}case"content_block_start":{let W=Number(j.index),q=j.content_block??{},F={type:String(q.type??""),id:typeof q.id==="string"?q.id:void 0,name:typeof q.name==="string"?q.name:void 0,args:"",signature:typeof q.signature==="string"?q.signature:""};if(J.set(W,F),F.type==="redacted_thinking")yield{type:"reasoning-delta",delta:"",providerMetadata:{anthropic:{type:"redacted_thinking",data:String(q.data??"")}}};if(F.type==="text"&&typeof q.text==="string"&&q.text)yield T5(q.text,$);break}case"content_block_delta":{let W=J.get(Number(j.index)),q=j.delta??{};if(!W)break;if(q.type==="text_delta"){let F=String(q.text??"");if(F)yield T5(F,$)}else if(q.type==="thinking_delta"){let F=String(q.thinking??"");if(F)yield{type:"reasoning-delta",delta:F}}else if(q.type==="signature_delta")W.signature+=String(q.signature??"");else if(q.type==="input_json_delta"&&W.type==="tool_use"){let F=String(q.partial_json??"");if(!F)break;W.args+=F,yield{type:"tool-call-delta",toolCallId:W.id??"",name:W.name??"",argsDelta:F}}break}case"content_block_stop":{let W=Number(j.index),q=J.get(W);if(J.delete(W),q?.type==="thinking")yield{type:"reasoning-delta",delta:"",providerMetadata:{anthropic:{type:"thinking",signature:q.signature}}};if(q?.type==="tool_use")if(q.args||="{}",J7(q.args))yield A5(q);else Z.push(q);break}case"message_delta":{if(typeof j.delta?.stop_reason==="string")V=j.delta.stop_reason;if(j.delta?.stop_details)z=j.delta.stop_details;G=E5(G,j.usage),$.onUsage?.(a(G)),yield{type:"usage",usage:a(G)};break}case"message_stop":{if(H=!0,V==="refusal"){yield{type:"error",error:Y7(z)},yield K("error");break}let W=Z7(V);if(Z.length>0&&W==="length")yield{type:"tool-call-discard",toolCallIds:Z.map((q)=>q.id??"")};else for(let q of Z)yield A5(q);yield K(W);break}case"error":{H=!0;let W=j.error??j;yield{type:"error",error:G7(W),...GQ(W)},yield K("error");break}}if(H)return}yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield K("error")}function A5(Q){return{type:"tool-call",toolCallId:Q.id??"",name:Q.name??"",args:Q.args}}function J7(Q){try{return JSON.parse(Q),!0}catch{return!1}}function T5(Q,$){return $.structuredOutput?{type:"output-delta",delta:Q}:{type:"text-delta",delta:Q}}function Z7(Q){if(Q==="max_tokens"||Q==="model_context_window_exceeded")return"length";return"stop"}function Y7(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 G7(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 E5(Q,$){if(!$||typeof $!=="object")return Q;let J={...Q};for(let Y of["input_tokens","output_tokens","cache_creation_input_tokens","cache_read_input_tokens"])if(typeof $[Y]==="number")J[Y]=$[Y];let Z=$.output_tokens_details?.thinking_tokens;if(typeof Z==="number")J.thinking_tokens=Z;return J}function a(Q){if(!Q)return D();let{cache_read_input_tokens:$,cache_creation_input_tokens:J}=Q,Z=(Q.input_tokens??0)+($??0)+(J??0),Y=Q.output_tokens??0,G={inputTokens:Z,outputTokens:Y,totalTokens:Z+Y};if(typeof $==="number")G.cachedInputTokens=$;if(typeof J==="number")G.cacheWriteInputTokens=J;if(typeof Q.thinking_tokens==="number")G.reasoningTokens=Q.thinking_tokens;return G}function bQ(Q){let $=HQ(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1,supportsForcedToolChoice:!0};let J=v5($);if(J?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:J.major>1,toolSearch:w5(J),supportsForcedToolChoice:!0};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:w5(J),supportsForcedToolChoice:!0};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0,supportsForcedToolChoice:!0}}function w5(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function hQ(Q){let $=v5(HQ(Q));return{trailingContext:!0,allowedTools:!$||$.kind==="gpt"&&$.major>=5}}function yQ(){return{trailingContext:!0}}function fQ(Q){let $=HQ(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,supportsForcedToolChoice:V7(Q)}}function V7(Q){let $=HQ(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 HQ(Q){return Q.trim().toLowerCase()}function v5(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}var gQ=120000,uQ=2,mQ=120000,cQ=300000,dQ=1000;function O(Q){return typeof process>"u"?void 0:process.env?.[Q]}var B7="preview";function b5(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function K7(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}function pQ(Q,$={}){return{base:(Q.baseURL??O("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=Q.apiKey??O("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??gQ,streamIdleTimeoutMs:Q.streamIdleTimeoutMs??mQ,streamMaxDurationMs:Q.streamMaxDurationMs??cQ,maxToolArgumentChars:Q.maxToolArgumentChars??0,maxToolArgumentWhitespace:Q.maxToolArgumentWhitespace??dQ,maxRetries:Q.maxRetries??uQ,...iQ(Q)}}function h5(Q){let $=Q.baseURL??Q.endpoint??O("AZURE_OPENAI_ENDPOINT");if($)return b5($);let J=Q.resourceName??O("AZURE_OPENAI_RESOURCE_NAME")??O("AZURE_RESOURCE_NAME");return J?b5(`https://${J.trim()}.cognitiveservices.azure.com`):""}function lQ(Q,$={}){let J=Q.apiVersion??O("AZURE_OPENAI_API_VERSION")??B7;return{base:`${h5(Q)}${K7(J)}`,query:`?api-version=${encodeURIComponent(J)}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let Z=Q.apiKey??O("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??gQ,streamIdleTimeoutMs:Q.streamIdleTimeoutMs??mQ,streamMaxDurationMs:Q.streamMaxDurationMs??cQ,maxToolArgumentChars:Q.maxToolArgumentChars??0,maxToolArgumentWhitespace:Q.maxToolArgumentWhitespace??dQ,maxRetries:Q.maxRetries??uQ,...iQ(Q)}}var W7="2026-10-21";function y5(Q,$={}){let J=Q.baseURL??O("ANTHROPIC_BASE_URL")??"https://api.anthropic.com";return g5(J,Q,$,async()=>{let Z=Q.workspaceId??O("ANTHROPIC_WORKSPACE_ID"),Y=Z?{"anthropic-workspace-id":Z}:{},G=Q.apiKey??O("ANTHROPIC_API_KEY");if(G)return{"x-api-key":G,...Y};let V=O("ANTHROPIC_AUTH_TOKEN");return V?{authorization:`Bearer ${V}`,...Y}:Y})}function f5(Q,$={}){let J=Q.resourceName??O("ANTHROPIC_FOUNDRY_RESOURCE"),Z=Q.baseURL??Q.endpoint??O("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 g5(Z,Q,$,async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`};let Y=Q.apiKey??O("ANTHROPIC_FOUNDRY_API_KEY");return Y?{"api-key":Y}:{}})}function g5(Q,$,J,Z){return{base:`${Q.trim().replace(/\/+$/,"").replace(/\/v1$/,"")}/v1`,query:"",headers:async()=>({...await Z(),"anthropic-version":W7,...$.headers}),timeoutMs:$.timeoutMs??J.timeoutMs??gQ,streamIdleTimeoutMs:$.streamIdleTimeoutMs??mQ,streamMaxDurationMs:$.streamMaxDurationMs??cQ,maxToolArgumentChars:$.maxToolArgumentChars??0,maxToolArgumentWhitespace:$.maxToolArgumentWhitespace??dQ,maxRetries:$.maxRetries??uQ,...iQ($)}}function u5(Q,$={}){return{...lQ(Q,$),base:`${h5(Q)}/v1`,query:""}}function iQ(Q){return Q5(Q.retry),Q.retry?{retry:Q.retry}:{}}class jQ{static models(){return[]}normalizeError(Q){return M(Q)}}var m5=["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 c5 extends jQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities={...bQ(Q),...hQ(Q)},this.config=$}static model(Q,$){return new c5(Q,$)}static models(){return m5}stream(Q){let $=AQ(Q,{model:this.model,capabilities:this.capabilities});return KQ(this.endpoint(),$,{signal:Q.signal,retryToolArgumentsTooLong:Q.retryToolArgumentsTooLong,structuredOutput:Boolean(Q.output),files:DQ(Q.messages)})}upload(Q){return WQ(this.endpoint(),Q)}deleteFile(Q){return XQ(this.endpoint(),Q)}endpoint(){return BQ(pQ(this.config))}get realtime(){return new YQ(pQ(this.config,{timeoutMs:PQ}),{model:this.model})}}var X7=["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 nQ extends jQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities={...fQ(Q),...yQ()},this.config=$}cacheWriteFactor(Q){return 1.25}static model(Q,$){return new nQ(Q,$)}static models(){return X7}stream(Q){return this.send(Q)}async*send(Q){let $=Q,J=!1,Z=new Set;for(;;){let Y=this.request($);if(J)Y=R5(Y);let G,V=!1;for await(let z of KQ(this.endpointFor(Y),Y,{signal:Q.signal,retryToolArgumentsTooLong:Q.retryToolArgumentsTooLong,structuredOutput:Boolean(Q.output),parse:k5})){if(G)continue;if(!V&&z.type==="error"&&z.status===400){let H=_5(z.error.message);if(H&&!Z.has(H)){Z.add(H),G=H;continue}}if(VQ(z))V=!0;yield z}if(!G)return;if(G==="thinking")J=!0;else if($.output)$={...$,output:{...$.output,strict:!1}}}}request(Q){return S5(Q,{model:this.deployment(),modelId:this.model,capabilities:this.capabilities,forcedToolChoice:this.capabilities.supportsForcedToolChoice!==!1,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(),Y=Z["anthropic-beta"];return{...Z,"anthropic-beta":Y?`${Y},${vQ}`:vQ}}}}bindsThinking(){return!0}deployment(){return this.model}upload(Q){return WQ(this.endpoint(),Q,null)}deleteFile(Q){return XQ(this.endpoint(),Q)}endpoint(){return d5(y5(this.config))}}function d5(Q){return{...BQ(Q),responsesUrl:`${Q.base}/messages`}}class p5 extends nQ{constructor(Q,$={}){super(Q,$);this.capabilities={...fQ(Q),...yQ(),fileInput:!1}}static model(Q,$){return new p5(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."))}deleteFile(Q){return Promise.reject(Error("AzureAnthropicProvider does not delete files: the Files API is not available on Azure-hosted Foundry deployments."))}deployment(){return this.config.deployment??this.model}bindsThinking(){return!1}endpoint(){return d5(f5(this.config))}}class l5 extends jQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities={...bQ(Q),...hQ(Q)},this.config=$}static model(Q,$){return new l5(Q,$)}static models(){return m5}stream(Q){let $=AQ(Q,{model:this.deployment(),capabilities:this.capabilities});return KQ(this.endpoint(),$,{signal:Q.signal,retryToolArgumentsTooLong:Q.retryToolArgumentsTooLong,structuredOutput:Boolean(Q.output),files:DQ(Q.messages)})}upload(Q){return WQ(this.endpoint(),Q,"assistants")}deleteFile(Q){return XQ(this.endpoint(),Q)}deployment(){return this.config.deployment??this.model}endpoint(){return BQ(lQ(this.config))}get realtime(){return new YQ(u5(this.config,{timeoutMs:PQ}),{model:this.deployment(),callFlow:"ephemeral"})}}
|
|
10
10
|
export{m as ca,pQ as da,lQ as ea,LQ as fa,Z6 as ga,UQ as ha,i as ia,YQ as ja,K6 as ka,jQ as la,c5 as ma,nQ as na,p5 as oa,l5 as pa};
|
|
11
11
|
|
|
12
|
-
//# debugId=
|
|
12
|
+
//# debugId=C8C737B1165E48CC64756E2164756E21
|