sliccy 6.78.2 → 6.78.4
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/node-server/cloud-status.d.ts +9 -0
- package/dist/node-server/cloud-status.js +9 -1
- package/dist/ui/.vite/manifest.json +144 -144
- package/dist/ui/assets/{account-store-DmnIQnOq.js → account-store-BGQKuzDl.js} +1 -1
- package/dist/ui/assets/{account-store-BXyAP1jx.js → account-store-pn6zPO8L.js} +1 -1
- package/dist/ui/assets/{adobe-C520oDwm.js → adobe-0b0FyQ4t.js} +1 -1
- package/dist/ui/assets/{adobe-DWPOa_fy.js → adobe-CN5aT0Hm.js} +1 -1
- package/dist/ui/assets/{apply-layout-lsmVXh66.js → apply-layout-HmLIE6Fq.js} +1 -1
- package/dist/ui/assets/{apps-CEpDr1je.js → apps-I_Hftz3u.js} +1 -1
- package/dist/ui/assets/azure-openai-DEv42QV2.js +18 -0
- package/dist/ui/assets/azure-openai-DWBbWCd4.js +18 -0
- package/dist/ui/assets/{browser-BAL8RehA.js → browser-2rCVqcqy.js} +1 -1
- package/dist/ui/assets/{cerebras-Dy_MbrIF.js → cerebras-CDI0WlFj.js} +1 -1
- package/dist/ui/assets/{cerebras-BbhUR95Q.js → cerebras-CFX18XnN.js} +1 -1
- package/dist/ui/assets/{connect-surface-rBqIwDr2.js → connect-surface-rEUllVWn.js} +1 -1
- package/dist/ui/assets/dist-DTAqvnM4.js +18 -0
- package/dist/ui/assets/{ensure-speech-assets-DDGWBTuw.js → ensure-speech-assets-DvFwJX-M.js} +1 -1
- package/dist/ui/assets/es-BDNIRkLU.js +51 -0
- package/dist/ui/assets/esptool-operations-BmdosN6N.js +13 -0
- package/dist/ui/assets/{esptool-operations-CDJhOTdU.js → esptool-operations-CbgLIJzi.js} +4 -4
- package/dist/ui/assets/{fs-adIt_XFC.js → fs-BvmOuuoW.js} +1 -1
- package/dist/ui/assets/{fs-3lYdC1rZ.js → fs-CI_ZlElB.js} +2 -2
- package/dist/ui/assets/{github-CSrB6hbA.js → github-Bo4jDClo.js} +2 -2
- package/dist/ui/assets/{github-Dc5rGVwG.js → github-DNLbMiVA.js} +1 -1
- package/dist/ui/assets/{github-copilot-J_gQzQT9.js → github-copilot-Dx3c4O5S.js} +1 -1
- package/dist/ui/assets/{github-copilot-CgOv9kw0.js → github-copilot-pln7MB1l.js} +1 -1
- package/dist/ui/assets/{github-install-BS41pGSA.js → github-install-C1Vx1uEa.js} +1 -1
- package/dist/ui/assets/{github-zip-Dxpyz8P0.js → github-zip-CyX68PXI.js} +1 -1
- package/dist/ui/assets/icons-ZLR7gmJ4.js +1 -0
- package/dist/ui/assets/{installer-CyaKvN2m.js → installer-DW4F27JY.js} +1 -1
- package/dist/ui/assets/{js-realm-worker-DwpZHmtu.js → js-realm-worker-CpNvOdHA.js} +4 -4
- package/dist/ui/assets/{kernel-worker-Du5lh_0e.js → kernel-worker-DD60flli.js} +33 -33
- package/dist/ui/assets/{local-llm-BplnhsX-.js → local-llm-DY1O3RRo.js} +1 -1
- package/dist/ui/assets/{local-llm-plHVku6d.js → local-llm-ZBxUzjwf.js} +1 -1
- package/dist/ui/assets/{main-BFWKnJJJ.js → main-BLjMDAZ9.js} +3 -3
- package/dist/ui/assets/{mount-D0Vgd-wF.js → mount-C8bUvuZA.js} +1 -1
- package/dist/ui/assets/{mount-C6fmWLuE.js → mount-NNJyHClO.js} +2 -2
- package/dist/ui/assets/{mount-recovery-DmYIAbGj.js → mount-recovery-CI0iiIR0.js} +1 -1
- package/dist/ui/assets/{new-session-BYMjF6Ei.js → new-session-BASFfWQC.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-CQk8eaRB.js → oauth-bootstrap-DMKbXT_F.js} +2 -2
- package/dist/ui/assets/{openai-codex-icr5Ntu8.js → openai-codex-BZa-7DlZ.js} +1 -1
- package/dist/ui/assets/{openai-codex-CU_y4U5i.js → openai-codex-Br1aqoPY.js} +1 -1
- package/dist/ui/assets/{openrouter-BwY6L2_X.js → openrouter-CDG7fyzJ.js} +1 -1
- package/dist/ui/assets/{openrouter-DtEyWQqf.js → openrouter-OT71uTol.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-D8Bppnk_.js → openrouter-oauth-C6zJTCRA.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-CvEqnu4k.js → openrouter-oauth-C95QCeKB.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-Cfz4dn61.js → panel-rpc-handlers-DQeANScD.js} +2 -2
- package/dist/ui/assets/{panelize-shell-BZuH5tPw.js → panelize-shell-BiuM5F3-.js} +1 -1
- package/dist/ui/assets/pdfjs-BspLIDsM.js +100 -0
- package/dist/ui/assets/{provider-wpT11SFh.js → provider-C9IU1SbF.js} +2 -2
- package/dist/ui/assets/{provider-OyNbvROp.js → provider-CXe1BnDL.js} +1 -1
- package/dist/ui/assets/{provider-settings-D0zUY30F.js → provider-settings-99Tri08Y.js} +1 -1
- package/dist/ui/assets/{provider-settings-Cm42H-H2.js → provider-settings-DLvGo5VB.js} +1 -1
- package/dist/ui/assets/{provider-store-access-C6SHregi.js → provider-store-access-D94TwJkZ.js} +2 -2
- package/dist/ui/assets/provider-store-access-DNaFuRvk.js +1 -0
- package/dist/ui/assets/{providers-DNYv_6eS.js → providers-BmGjtX4o.js} +2 -2
- package/dist/ui/assets/{providers-c5mygwUs.js → providers-CaiKfE0x.js} +1 -1
- package/dist/ui/assets/{quick-llm-C7M0ga7E.js → quick-llm-BjCkgpHJ.js} +1 -1
- package/dist/ui/assets/{recovery-screen-IAE-MvUV.js → recovery-screen-C8kmb4Oe.js} +1 -1
- package/dist/ui/assets/{redirect-uri-NVOhGTXE.js → redirect-uri-D-JXog5O.js} +1 -1
- package/dist/ui/assets/{session-freezer-fGtn52OY.js → session-freezer-CxY3xdQv.js} +3 -3
- package/dist/ui/assets/{setup-feature-flags-remote-DWGfRuUu.js → setup-feature-flags-remote-WzuCVuD3.js} +1 -1
- package/dist/ui/assets/{setup-standalone-prelude-CKGx__Cx.js → setup-standalone-prelude-DfSbiyNk.js} +1 -1
- package/dist/ui/assets/{setup-sudo-Dg3vUbkf.js → setup-sudo-BR7SvT6r.js} +2 -2
- package/dist/ui/assets/{skills-5FxoCQJ6.js → skills-Dp0SGPwK.js} +1 -1
- package/dist/ui/assets/slicc-version-CvHoW36c.js +1 -0
- package/dist/ui/assets/{sprinkle-manager-BMj0BniN.js → sprinkle-manager-2UUakPAV.js} +1 -1
- package/dist/ui/assets/src-Cj-AoUM3.js +2 -0
- package/dist/ui/assets/{src-jZxFomYR.js → src-DDn9o2XK.js} +1 -1
- package/dist/ui/assets/{store-DoGFCSZp.js → store-BJu3vCG-.js} +1 -1
- package/dist/ui/assets/{store-DhUl0l62.js → store-BMquWJfv.js} +1 -1
- package/dist/ui/assets/{sudo-CWBR9fWj.js → sudo-22HJuKev.js} +1 -1
- package/dist/ui/assets/{sync-dialog-BXZHMjrc.js → sync-dialog-ACgl0n-p.js} +1 -1
- package/dist/ui/assets/{telemetry-DeLkquP_.js → telemetry-BVzuNdvW.js} +1 -1
- package/dist/ui/assets/{telemetry-BugxTkxX.js → telemetry-BwapcULJ.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-lMNqZP1C.js → upgrade-detection-CQFrSKSr.js} +1 -1
- package/dist/ui/assets/{wc-attach-C4L2GyF0.js → wc-attach-BsqldTbU.js} +2 -2
- package/dist/ui/assets/{wc-extension-De6gkHcE.js → wc-extension-KeHVc-Qf.js} +2 -2
- package/dist/ui/assets/{wc-follower-B1faH8Q0.js → wc-follower-a0UvbkNV.js} +3 -3
- package/dist/ui/assets/{wc-live-f3F9MnLg.js → wc-live-Ca4TSsU-.js} +5 -5
- package/dist/ui/assets/{wc-nav-BTOY5z8O.js → wc-nav-DJXR7yu7.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-BBGyy5eB.js → wc-onboarding-Dr5gwtbv.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-D61OJQeT.js → wc-placeholder-CWmMPVIU.js} +2 -2
- package/dist/ui/assets/{wc-settings-DJKVlhfA.js → wc-settings-D6obaPTW.js} +2 -2
- package/dist/ui/assets/wc-shell-CSYqssCx.js +119 -0
- package/dist/ui/assets/{wc-sprinkles-D5eTbiqv.js → wc-sprinkles-DXnNTQJk.js} +2 -2
- package/dist/ui/assets/{wc-tray-FIF4Qzb3.js → wc-tray-B2Gv2dCO.js} +2 -2
- package/dist/ui/assets/{xai-grok-Dzb_ibzT.js → xai-grok-CHgtXAXT.js} +1 -1
- package/dist/ui/assets/{xai-grok-Bu7EH_7e.js → xai-grok-O05b7Lrc.js} +1 -1
- package/dist/ui/index.html +7 -7
- package/dist/ui/lucide-icons.js +1788 -1707
- package/dist/ui/packages/webapp/index.html +7 -7
- package/package.json +10 -10
- package/dist/ui/assets/azure-openai-CFa7gqVY.js +0 -18
- package/dist/ui/assets/azure-openai-Zl50fQ_S.js +0 -18
- package/dist/ui/assets/dist-CZvQ4trc.js +0 -15
- package/dist/ui/assets/es-D8T2ybXa.js +0 -53
- package/dist/ui/assets/esptool-operations-3FBbK-fD.js +0 -13
- package/dist/ui/assets/icons-DtQGhvkp.js +0 -1
- package/dist/ui/assets/pdfjs-CRuE4vGw.js +0 -54
- package/dist/ui/assets/provider-store-access-BUWYgIzq.js +0 -1
- package/dist/ui/assets/slicc-version-By1hy77P.js +0 -1
- package/dist/ui/assets/src-C9oNvq2b.js +0 -2
- package/dist/ui/assets/wc-shell-CfTIPiAH.js +0 -117
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import{b as e,g as t}from"./account-store-pn6zPO8L.js";import{a as n}from"./diagnostics-DN_idNHx.js";import{i as r,s as i,t as a}from"./transform-messages-N_eMsP2M.js";import{p as o}from"./bedrock-camp-qpZqnqLa.js";function s(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function c(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var l=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return l=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function u(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var d=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)},f=class extends Error{},p=class e extends f{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new h({message:r,cause:d(n)});let a=n?.error;return t===400?new _(t,a,r,i):t===401?new v(t,a,r,i):t===403?new y(t,a,r,i):t===404?new b(t,a,r,i):t===409?new x(t,a,r,i):t===422?new ee(t,a,r,i):t===429?new te(t,a,r,i):t>=500?new ne(t,a,r,i):new e(t,a,r,i)}},m=class extends p{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},h=class extends p{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},g=class extends h{constructor({message:e}={}){super({message:e??`Request timed out.`})}},_=class extends p{},v=class extends p{},y=class extends p{},b=class extends p{},x=class extends p{},ee=class extends p{},te=class extends p{},ne=class extends p{},re=class extends f{constructor(){super(`Could not parse response content as the length limit was reached`)}},ie=class extends f{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},ae=class extends Error{constructor(e){super(e)}},oe=class extends p{constructor(e,t,n){let r=`OAuth2 authentication error`,i;if(t&&typeof t==`object`){let e=t;i=e.error;let n=e.error_description;n&&typeof n==`string`?r=n:i&&(r=i)}super(e,t,r,n),this.error_code=i}},se=class extends f{constructor(e,t,n){super(e),this.provider=t,this.cause=n}},ce=/^[a-z][a-z0-9+.-]*:/i,le=e=>ce.test(e),S=e=>(S=Array.isArray,S(e)),ue=S;function de(e){return typeof e==`object`?e??{}:{}}function fe(e){if(!e)return!0;for(let t in e)return!1;return!0}function pe(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function C(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var me=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new f(`${e} must be an integer`);if(t<0)throw new f(`${e} must be a positive integer`);return t},he=e=>{try{return JSON.parse(e)}catch{return}},ge=e=>new Promise(t=>setTimeout(t,e));function _e(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function ve(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function ye(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ve({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function be(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function xe(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var Se;function w(e){let t;return(Se??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var Ce;function we(e){let t;return(Ce??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var Te,T,E,D,O,Ee,De,Oe=65536,ke=class{constructor(){Te.add(this),T.set(this,void 0),E.set(this,void 0),D.set(this,void 0),O.set(this,void 0),Ee.set(this,void 0),s(this,T,new Uint8Array,`f`),s(this,E,0,`f`),s(this,D,0,`f`),s(this,O,0,`f`),s(this,Ee,!1,`f`)}decode(e){if(e==null)return[];let t;if(t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?w(e):e,t.length===0||c(this,Ee,`f`)&&(s(this,Ee,!1,`f`),t[0]===10&&(t=t.subarray(1)),t.length===0))return[];c(this,Te,`m`,De).call(this,t);let n=[],r;for(;(r=Ae(c(this,T,`f`),c(this,O,`f`),c(this,D,`f`)))!=null;){let e=we(c(this,T,`f`).subarray(c(this,E,`f`),r.preceding));n.push(e),s(this,E,r.index,`f`),r.carriage&&(c(this,E,`f`)<c(this,D,`f`)&&c(this,T,`f`)[c(this,E,`f`)]===10?s(this,E,c(this,E,`f`)+1,`f`):c(this,E,`f`)===c(this,D,`f`)&&s(this,Ee,!0,`f`)),s(this,O,c(this,E,`f`),`f`)}if(s(this,O,c(this,D,`f`),`f`),c(this,E,`f`)===c(this,D,`f`))s(this,E,0,`f`),s(this,D,0,`f`),s(this,O,0,`f`),c(this,T,`f`).length>Oe&&s(this,T,new Uint8Array,`f`);else if(n.length>0&&c(this,T,`f`).length>Oe){let e=c(this,D,`f`)-c(this,E,`f`);if(e<=Oe||c(this,T,`f`).length>e*4){let t=e<=Oe?Math.min(Math.max(e*2,256),Oe):e*2,n=new Uint8Array(t);n.set(c(this,T,`f`).subarray(c(this,E,`f`),c(this,D,`f`))),s(this,T,n,`f`),s(this,E,0,`f`),s(this,D,e,`f`),s(this,O,e,`f`)}}return n}flush(){return s(this,Ee,!1,`f`),c(this,E,`f`)===c(this,D,`f`)?[]:this.decode(`
|
|
2
|
+
`)}};T=new WeakMap,E=new WeakMap,D=new WeakMap,O=new WeakMap,Ee=new WeakMap,Te=new WeakSet,De=function(e){if(c(this,D,`f`)+e.length>c(this,T,`f`).length){let t=c(this,D,`f`)-c(this,E,`f`);if(c(this,E,`f`)>=c(this,T,`f`).length/2&&t+e.length<=c(this,T,`f`).length)c(this,T,`f`).copyWithin(0,c(this,E,`f`),c(this,D,`f`));else{let n=Math.max(c(this,T,`f`).length*2,t+e.length,256),r=new Uint8Array(n);r.set(c(this,T,`f`).subarray(c(this,E,`f`),c(this,D,`f`))),s(this,T,r,`f`)}s(this,O,c(this,O,`f`)-c(this,E,`f`),`f`),s(this,D,t,`f`),s(this,E,0,`f`)}c(this,T,`f`).set(e,c(this,D,`f`)),s(this,D,c(this,D,`f`)+e.length,`f`)},ke.NEWLINE_CHARS=new Set([`
|
|
3
|
+
`,`\r`]),ke.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ae(e,t,n){for(let r=t;r<n;r++){if(e[r]===10)return{preceding:r,index:r+1,carriage:!1};if(e[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function je(e){for(let t=0;t<e.length-1;t++){let n=Me(e,t);if(n>0){let r=t+n,i=Me(e,r);if(i>0)return r+i}}return-1}function Me(e,t){return e[t]===10?1:e[t]===13?e[t+1]===10?2:1:0}var Ne={off:0,error:200,warn:300,info:400,debug:500},Pe=(e,t,n)=>{if(e){if(pe(Ne,e))return e;k(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Ne))}`)}};function Fe(){}function Ie(e,t,n){return!t||Ne[e]>Ne[n]?Fe:t[e].bind(t)}var Le={error:Fe,warn:Fe,info:Fe,debug:Fe},Re=new WeakMap;function k(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Le;let r=Re.get(t);if(r&&r[0]===n)return r[1];let i={error:Ie(`error`,t,n),warn:Ie(`warn`,t,n),info:Ie(`info`,t,n),debug:Ie(`debug`,t,n)};return Re.set(t,[n,i]),i}var ze=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`api-key`||e.toLowerCase()===`x-api-key`||e.toLowerCase()===`x-amz-security-token`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),Be,Ve=class e{constructor(e,t,n){Be.set(this,void 0),this.iterator=e,this.controller=t,s(this,Be,n,`f`)}static fromSSEResponse(t,n,r,i){let a=!1,o=r?k(r):console;async function*s(){if(a)throw new f("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let e=!1,r=!1;try{for await(let e of He(t,n)){if(e.data.startsWith(`[DONE]`)){r=!0;break}if(e.event===null||!e.event.startsWith(`thread.`)){let n;try{n=JSON.parse(e.data)}catch(t){throw o.error(`Could not parse message into JSON:`,e.data),o.error(`From chunk:`,e.raw),t}if(n&&n.error)throw new p(void 0,n.error,void 0,t.headers);yield i?{event:e.event,data:n}:n}else{let t;try{t=JSON.parse(e.data)}catch(t){throw console.error(`Could not parse message into JSON:`,e.data),console.error(`From chunk:`,e.raw),t}if(e.event===`error`)throw new p(void 0,t.error,t.message,void 0);yield{event:e.event,data:t}}}e=!0}catch(e){if(r||u(e)||n.signal.aborted&&e===n.signal.reason)return;throw e}finally{e||n.abort()}}return new e(s,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new ke,r=t.getReader(),i=!1,a,o=()=>{a??=r.cancel(),a.catch(()=>void 0)};n.signal.addEventListener(`abort`,o,{once:!0});try{if(n.signal.aborted){o();return}for(;;){let{value:t,done:a}=await r.read();if(a){i=!0;break}if(n.signal.aborted)return;for(let r of e.decode(t)){if(n.signal.aborted)return;yield r}}if(n.signal.aborted)return;for(let t of e.flush()){if(n.signal.aborted)return;yield t}}finally{n.signal.removeEventListener(`abort`,o),i||o(),r.releaseLock()}}async function*o(){if(i)throw new f("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let t of a())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(n.signal.aborted||u(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(Be=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],r=this.iterator(),i=e=>({next:()=>{if(e.length===0){let e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,c(this,Be,`f`)),new e(()=>i(n),this.controller,c(this,Be,`f`))]}toReadableStream(){let e;return ve({start:async()=>{e=this[Symbol.asyncIterator]()},async pull(t){try{let{value:n,done:r}=await e.next();if(r)return t.close();let i=w(JSON.stringify(n)+`
|
|
4
|
+
`);t.enqueue(i)}catch(e){t.error(e)}},async cancel(){await e.return?.()}})}};async function*He(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new f(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new f(`Attempted to iterate over a response with no body`);let n=new Ge,r=new ke,i=be(e.body);for await(let e of We(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}var Ue=3;async function*We(e){let t=new Uint8Array,n=0,r=0,i=0;for await(let a of e){if(a==null)continue;let e;if(e=a instanceof ArrayBuffer?new Uint8Array(a):typeof a==`string`?w(a):a,r+e.length>t.length){let a=r-n;if(n>=t.length/2&&a+e.length<=t.length)t.copyWithin(0,n,r);else{let i=new Uint8Array(Math.max(t.length*2,a+e.length));i.set(t.subarray(n,r)),t=i}i-=n,n=0,r=a}t.set(e,r),r+=e.length;let o;for(;(o=je(t.subarray(i,r)))!==-1;)o+=i,yield t.slice(n,o),n=o,i=n;i=Math.max(n,r-Ue)}r>n&&(yield t.slice(n,r))}var Ge=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.slice(0,-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
|
|
5
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,,n]=Ke(e,`:`),r=n;return r.startsWith(` `)&&(r=r.slice(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function Ke(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.slice(0,n),t,e.slice(n+t.length)]}async function qe(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return k(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData):Ve.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();if(r?.includes(`application/json`)||r?.endsWith(`+json`)){if(n.headers.get(`content-length`)===`0`)return;let e=await n.text();return e?Ye(JSON.parse(e),n):void 0}return await n.text()})().catch(e=>{throw Je(e,t.controller.signal)});return k(e).debug(`[${r}] response parsed`,ze({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function Je(e,t){if(!t.aborted||e!==t.reason||u(e))return e;let n=`This operation was aborted`,r=globalThis.DOMException;return typeof r==`function`?new r(n,`AbortError`):Object.assign(Error(n),{name:`AbortError`})}function Ye(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get(`x-request-id`),enumerable:!1})}var Xe=`7.5.0`,Ze=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function Qe(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var $e=()=>{let e=Qe();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Xe,"X-Stainless-OS":nt(Deno.build.os),"X-Stainless-Arch":tt(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Xe,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Xe,"X-Stainless-OS":nt(globalThis.process.platform??`unknown`),"X-Stainless-Arch":tt(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=et();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Xe,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Xe,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function et(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var tt=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,nt=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),rt,it=()=>rt??=$e(),at=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),ot=`RFC3986`,st=String,ct={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:st},lt,ut=(e,t)=>{let n=lt??Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty);return lt=n,n(e,t)},A=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),dt=1024,ft=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,e=>`%26%23`+Number.parseInt(e.slice(2),16)+`%3B`);let o=``;for(let e=0;e<a.length;){let t=Math.min((Math.floor(e/dt)+1)*dt,a.length);t<a.length&&a.codePointAt(t-1)>65535&&(t+=1);let n=a.length>=dt?a.slice(e,t):a,r=[];for(let e=0;e<n.length;++e){let t=n.charCodeAt(e);if(t===45||t===46||t===95||t===126||t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||i===`RFC1738`&&(t===40||t===41)){r[r.length]=n.charAt(e);continue}if(t<128){r[r.length]=A[t];continue}if(t<2048){r[r.length]=A[192|t>>6]+A[128|t&63];continue}if(t<55296||t>=57344){r[r.length]=A[224|t>>12]+A[128|t>>6&63]+A[128|t&63];continue}e+=1,t=65536+((t&1023)<<10|n.charCodeAt(e)&1023),r[r.length]=A[240|t>>18]+A[128|t>>12&63]+A[128|t>>6&63]+A[128|t&63]}o+=r.join(``),e=t}return o};function pt(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function mt(e,t){if(S(e)){let n=[];for(let r of e)n.push(t(r));return n}return t(e)}var ht={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},gt=function(e,t){Array.prototype.push.apply(e,S(t)?t:[t])},_t,j={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:ft,encodeValuesOnly:!1,format:ot,formatter:st,indices:!1,serializeDate(e){return(_t??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function vt(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var yt={};function bt(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,x=!1;for(;(y=y.get(yt))!==void 0&&!x;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);x=!0}y.get(yt)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&S(v)&&(v=mt(v,e=>e instanceof Date?f?.(e):e)),v===null){if(a)return c&&!h?c(t,j.encoder,g,`key`,p):t;v=``}if(vt(v)||pt(v)){if(c){let e=h?t:c(t,j.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,j.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let ee=[];if(v===void 0)return ee;let te;if(n===`comma`&&S(v))h&&c&&(v=mt(v,c)),te=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(S(l))te=l;else{let e=Object.keys(v);u&&e.sort(u),te=e}let ne=s?String(t).replace(/\./g,`%2E`):String(t),re=r&&S(v)&&v.length===1?ne+`[]`:ne;if(i&&S(v)&&v.length===0)return re+`[]`;for(let t of te){let y=typeof t==`object`&&t.value!==void 0?t.value:v[t];if(o&&y===null)continue;let x=d&&s?t.replace(/\./g,`%2E`):t,te;te=S(v)?typeof n==`function`?n(re,x):re:re+(d?`.`+x:`[`+x+`]`),_.set(e,b);let ne=new WeakMap([[yt,_]]);gt(ee,bt(y,te,n,r,i,a,o,s,n===`comma`&&h&&S(v)?null:c,l,u,d,f,p,m,h,g,ne))}return ee}function xt(e=j){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||j.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=ot;if(e.format!==void 0){if(!ut(ct,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=ct[n],i=j.filter;(typeof e.filter==`function`||S(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in ht?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:j.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o;return o=e.allowDots===void 0?e.encodeDotInKeys?!0:j.allowDots:!!e.allowDots,{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:j.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:j.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:j.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?j.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:j.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:j.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:j.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:j.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:j.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:j.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:j.strictNullHandling}}function St(e,t={}){let n=e,r=xt(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):S(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=ht[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e of i)r.skipNulls&&n[e]===null||gt(o,bt(n[e],e,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l));let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(d+=r.charset===`iso-8859-1`?`utf8=%26%2310003%3B&`:`utf8=%E2%9C%93&`),u.length>0?d+u:``}function Ct(e){return St(e,{arrayFormat:`brackets`})}var wt,Tt=class e extends Promise{constructor(e,t,n=qe){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,wt.set(this,void 0),s(this,wt,e,`f`)}_thenUnwrap(t){return new e(c(this,wt,`f`),this.responsePromise,async(e,n)=>Ye(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`x-request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(c(this,wt,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};wt=new WeakMap;var Et,Dt=class{constructor(e,t,n,r){Et.set(this,void 0),s(this,Et,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new f("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await c(this,Et,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Et=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Ot=class extends Tt{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await qe(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},kt=class extends Dt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},M=class extends Dt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...de(this.options.query),after:t}}:null}},N=class extends Dt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||``}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...de(this.options.query),after:e}}:null}},At=class extends Dt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...de(this.options.query),after:e}}:null}},jt={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`},Mt=`urn:ietf:params:oauth:grant-type:token-exchange`,Nt=class e{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenGeneration=0,this.tokenExchangeUrl=`https://auth.openai.com/oauth/token`,this.config=e,this.fetch=t??_e()}async getToken(){if(!this.cachedToken||e.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;let e=this.refreshToken(this.tokenGeneration);this.refreshPromise=e;try{return await e}finally{this.refreshPromise===e&&(this.refreshPromise=null)}}if(this.needsRefresh(this.cachedToken)&&!this.refreshPromise){let e=this.refreshToken(this.tokenGeneration).finally(()=>{this.refreshPromise===e&&(this.refreshPromise=null)});this.refreshPromise=e,e.catch(()=>null)}return this.cachedToken.token}async refreshToken(e){let t={grant_type:Mt,subject_token:await this.config.provider.getToken(),subject_token_type:jt[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(t.client_id=this.config.clientId);let n=await this.fetch(this.tokenExchangeUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t),redirect:`manual`});if(!n.ok){let e=await n.text(),t;try{t=JSON.parse(e)}catch{}throw n.status===400||n.status===401||n.status===403?new oe(n.status,t,n.headers):p.generate(n.status,t,`Token exchange failed with status ${n.status}`,n.headers)}let r=await n.json();if(typeof r!=`object`||!r||!(`access_token`in r)||typeof r.access_token!=`string`||r.access_token.trim().length===0)throw new f(`Token exchange response missing 'access_token' field`);let i=r.access_token,a=r.expires_in??3600;if(typeof a!=`number`||!Number.isFinite(a)||a<=0)throw new f(`Token exchange response has invalid 'expires_in' field`);let o=Date.now(),s=o+a*1e3;if(!Number.isSafeInteger(s)||s<=o)throw new f(`Token exchange response has invalid 'expires_in' field`);return this.tokenGeneration===e&&(this.cachedToken={token:i,expiresAt:s}),i}static isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let t=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-t}invalidateToken(){this.tokenGeneration+=1,this.cachedToken=null,this.refreshPromise=null}},Pt=Symbol(`brand.privateNullableHeaders`),Ft=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function*It(e){if(!e)return;if(Pt in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():ue(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=ue(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}var P=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of It(r)){if(!Ft.test(i))throw TypeError(`Header name must be a valid HTTP token ["${i}"]`);let r=i.toLowerCase();e.has(r)||(t.delete(r),e.add(r)),a===null?(t.delete(r),n.add(r)):(t.append(r,a),n.delete(r))}}return{[Pt]:!0,values:t,nulls:n}},Lt=Symbol(`brand.privateStreamingFile`);function Rt(e,t,n){if(typeof t!=`string`||!t)throw TypeError(`toStreamingFile requires a non-empty file name`);let r=n?.type;return r&&cn(r),{[Lt]:!0,data:e,name:t,...r?{type:r}:{}}}var zt=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&Number.parseInt(e.versions.node.split(`.`),10)<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to a supported Node.js LTS release, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function Bt(e,t,n){return zt(),new File(e,t??`unknown_file`,n)}function Vt(e,t){if(typeof e!=`object`||!e)return;let n=`name`in e&&e.name&&String(e.name)||`filename`in e&&e.filename&&String(e.filename);if(n)return t?.stripFilename===!1?Ut(n):Ht(n);let r=`url`in e&&e.url&&String(e.url);if(r)try{return Ht(new URL(r).pathname)}catch{return Ht(r)}let i=`path`in e&&e.path&&String(e.path);return i?Ht(i):void 0}function Ht(e){return e.split(/[\\/]/).pop()||void 0}function Ut(e){return e.replace(/\\/g,`/`)}var Wt=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,Gt=async(e,t,n)=>en(e.body)?$t(e.body)?tn(e,n):{...e,body:await Jt(e.body,t,n)}:e,F=async(e,t,n)=>$t(e.body)?tn(e,n):{...e,body:await Jt(e.body,t,n)},Kt=new WeakMap;function qt(e){let t=typeof e==`function`?e:e.fetch,n=Kt.get(t);if(n)return n;let r=(async()=>{try{let e;if(`Response`in t)e=t.Response;else{let n=await t(`data:,`);await n.arrayBuffer(),e=n.constructor}let n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return Kt.set(t,r),r}var Jt=async(e,t,n={})=>{if(!await qt(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>fn(r,e,t,n))),r},Yt=e=>e instanceof Blob&&`name`in e,Xt=e=>typeof e==`object`&&!!e&&`getReader`in e&&typeof e.getReader==`function`,Zt=e=>typeof e==`object`&&!!e&&Lt in e,Qt=e=>typeof e==`object`&&!!e&&(e instanceof Response||Wt(e)||Xt(e)||Zt(e)||Yt(e)),$t=e=>{if(Zt(e)||Wt(e)||Xt(e))return!0;if(Array.isArray(e))return e.some($t);if(e&&typeof e==`object`&&!Yt(e)&&!(e instanceof Response)){for(let t in e)if($t(e[t]))return!0}return!1},en=e=>{if(Qt(e))return!0;if(Array.isArray(e))return e.some(en);if(e&&typeof e==`object`){for(let t in e)if(en(e[t]))return!0}return!1},tn=(e,t={})=>{let n=`openai-${Math.random().toString(36).slice(2)}`,r=ye(nn(e.body,n,t));return{...e,body:r,headers:P([{"content-type":`multipart/form-data; boundary=${n}`},e.headers])}};async function*nn(e,t,n){for await(let{key:r,value:i}of rn(e)){if(Qt(i)){let e=on(i,n),a=sn(i);yield w(`--${t}\r\n`),yield w(`Content-Disposition: form-data; name="${dn(r)}"; filename="${dn(e)}"\r\nContent-Type: ${a}\r\n\r\n`),yield*un(ln(i))}else yield w(`--${t}\r\n`),yield w(`Content-Disposition: form-data; name="${dn(r)}"\r\n\r\n${String(i)}`);yield w(`\r
|
|
6
|
+
`)}yield w(`--${t}--\r\n`)}async function*rn(e){if(!(!e||typeof e!=`object`))for(let[t,n]of Object.entries(e))yield*an(t,n)}async function*an(e,t){if(t!==void 0){if(t==null)throw TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t==`string`||typeof t==`number`||typeof t==`boolean`||Qt(t))yield{key:e,value:t};else if(Array.isArray(t))for(let n of t)yield*an(e+`[]`,n);else if(typeof t==`object`)for(let[n,r]of Object.entries(t))yield*an(`${e}[${n}]`,r);else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}}function on(e,t){if(Zt(e)){let{name:n}=e;if(typeof n!=`string`||!n)throw TypeError(`Streaming upload file name must be a non-empty string`);return t.stripFilenames===!1?Ut(n):n}return Vt(e,{stripFilename:t.stripFilenames})??`unknown_file`}function sn(e){let t;return Zt(e)||Yt(e)?{type:t}=e:e instanceof Response&&(t=e.headers.get(`content-type`)??void 0),cn(t||`application/octet-stream`)}function cn(e){if(typeof e!=`string`)throw TypeError(`Streaming upload content type must be a string`);for(let t=0;t<e.length;t+=1){let n=e.codePointAt(t)??0;if(n<=31||n===127)throw TypeError(`Streaming upload content type must not contain control characters`)}return e}function ln(e){return Zt(e)?e.data:e}async function*un(e){if(typeof e==`string`)yield w(e);else if(ArrayBuffer.isView(e))yield new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof ArrayBuffer)yield new Uint8Array(e);else if(e instanceof Response)yield*un(e.body||await e.blob());else if(e instanceof Blob)typeof e.stream==`function`?yield*un(e.stream()):yield new Uint8Array(await e.arrayBuffer());else if(Xt(e))for await(let t of be(e))yield*un(t);else if(Wt(e))for await(let t of e)yield*un(t);else throw TypeError(`Invalid streaming file chunk: ${String(e)}`)}function dn(e){return Array.from(e,e=>{let t=e.codePointAt(0)??0;return t<=31||t===127||e===`"`||e===`\\`?encodeURIComponent(e):e}).join(``)}var fn=async(e,t,n,r)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response)e.append(t,Bt([await n.blob()],Vt(n,{stripFilename:r.stripFilenames})));else if(Wt(n))e.append(t,Bt([await new Response(ye(n)).blob()],Vt(n,{stripFilename:r.stripFilenames})));else if(Yt(n))e.append(t,n,Vt(n,{stripFilename:r.stripFilenames}));else if(Array.isArray(n))await Promise.all(n.map(n=>fn(e,t+`[]`,n,r)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,i])=>fn(e,`${t}[${n}]`,i,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},pn=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,mn=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&pn(e),hn=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`,gn=(e,t)=>t?.type!=null&&t.type!==e.type||t?.lastModified!=null&&t.lastModified!==e.lastModified||t?.endings!=null,_n=(e,t,n)=>(t==null||t===e.name)&&!gn(e,n);async function vn(e,t,n){if(zt(),e=await e,mn(e)){let r={...n,type:n?.type??e.type,lastModified:n?.lastModified??e.lastModified};return e instanceof File?_n(e,t,n)?e:Bt([e],t??e.name,r):Bt([await e.arrayBuffer()],t??e.name,r)}if(hn(e)){let r=await e.blob();t||=Vt(e);let i=n?.type===void 0&&r.type?{...n,type:r.type}:n;return Bt(await yn(r),t,i)}let r=await yn(e);if(t||=Vt(e),n?.type===void 0){let e=r.find(e=>typeof e==`object`&&`type`in e&&!!e.type);e&&(n={...n,type:e.type})}return Bt(r,t,n)}async function yn(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(pn(e))t.push(e instanceof Blob?e:new Blob([await e.arrayBuffer()],{type:e.type}));else if(Wt(e))for await(let n of e)t.push(...await yn(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${bn(e)}`)}return t}function bn(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var I=class{constructor(e){this._client=e}};function xn(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Sn=Object.freeze(Object.create(null)),L=((e=xn)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=``;for(let o=0;o<t.length;o+=1)if(o in t){let s=t[o];/[?#]/.test(s)&&(r=!0);let c=n[o],l=(r?encodeURIComponent:e)(``+c);o!==n.length&&(c==null||typeof c==`object`&&c.toString===Object.getPrototypeOf(Object.getPrototypeOf(c.hasOwnProperty??Sn)??Sn)?.toString)&&(l=c+``,i.push({start:a.length+s.length,length:l.length,error:`Value of type ${Object.prototype.toString.call(c).slice(8,-1)} is not a valid path parameter`})),a+=s+(o===n.length?``:l)}let o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=``;for(let n of i){let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);e=n.start+n.length,t+=r+i}throw new f(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
|
|
7
|
+
`)}\n${a}\n${t}`)}return a})(xn),Cn=class extends I{list(e,t={},n){return this._client.getAPIList(L`/chat/completions/${e}/messages`,M,{query:t,...n,__security:{bearerAuth:!0}})}};function wn(e){return e!==void 0&&`function`in e&&e.function!==void 0}function Tn(e){return e?.$brand===`auto-parseable-response-format`}function En(e){return Tn(e)||e?.type===`json_schema`}function Dn(e,t){return En(e)?typeof e==`object`&&e&&`$parseRaw`in e&&typeof e.$parseRaw==`function`?e.$parseRaw(t):JSON.parse(t):null}function On(e){return e?.$brand===`auto-parseable-tool`}function kn(e,t){return!t||!Pn(t)?{...e,choices:e.choices.map(e=>({...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:An(e,t)}function An(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new re;if(e.finish_reason===`content_filter`)throw new ie;return{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>Mn(t,e))??void 0}:void 0,parsed:e.message.content!==null&&e.message.content!==void 0&&!e.message.refusal&&(e.message.content!==``||!e.message.tool_calls?.length&&!e.message.function_call)?jn(t,e.message.content):null}}});return{...e,choices:n}}function jn(e,t){return Dn(e.response_format,t)}function Mn(e,t){if(t.type===`custom`)return t;if(t.type!==`function`){let e=t.type;throw new f(`Currently only \`function\` and \`custom\` tool calls are supported; Received \`${e}\``)}let n=e.tools?.find(e=>wn(e)&&e.function?.name===t.function.name),r=null;return On(n)?r=n.$parseRaw(t.function.arguments):n?.function.strict&&(r=JSON.parse(t.function.arguments)),{...t,function:{...t.function,parsed_arguments:r}}}function Nn(e,t){if(!e||!(`tools`in e)||!e.tools||t.type!==`function`)return!1;let n=e.tools?.find(e=>wn(e)&&e.function?.name===t.function?.name);return wn(n)&&(On(n)||n?.function.strict||!1)}function Pn(e){return En(e.response_format)?!0:e.tools?.some(e=>On(e)||e.type===`function`&&e.function.strict===!0)??!1}function Fn(e){for(let t of e??[])if(t.type!==`custom`){if(t.type!==`function`){let e=t.type;throw new f(`Currently only \`function\` and \`custom\` tool types are supported; Received \`${e}\``)}if(t.function.strict!==!0)throw new f(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var In=e=>e?.role===`assistant`,Ln=e=>e?.role===`tool`,Rn,zn,Bn,Vn,Hn,Un,Wn,Gn,Kn,qn,Jn,Yn,Xn,Zn,Qn;function $n(){let e=[],t=0;return{get length(){return e.length-t},enqueue(t){e.push(t)},dequeue(){if(t===e.length)return;let n=e[t];return e[t]=void 0,t+=1,t===e.length?(e=[],t=0):t>=1024&&t*2>=e.length&&(e=e.slice(t),t=0),n},clear(){e=[],t=0}}}var er=class{constructor(){Rn.add(this),this.controller=new AbortController,zn.set(this,void 0),Bn.set(this,()=>void 0),Vn.set(this,()=>void 0),Hn.set(this,void 0),Un.set(this,()=>void 0),Wn.set(this,()=>void 0),Gn.set(this,Object.create(null)),Kn.set(this,[]),qn.set(this,!1),Jn.set(this,!1),Yn.set(this,!1),Xn.set(this,!1),s(this,zn,new Promise((e,t)=>{s(this,Bn,e,`f`),s(this,Vn,t,`f`)}),`f`),s(this,Hn,new Promise((e,t)=>{s(this,Un,e,`f`),s(this,Wn,t,`f`)}),`f`),c(this,zn,`f`).catch(()=>void 0),c(this,Hn,`f`).catch(()=>void 0)}_run(e){setTimeout(()=>{let t=!1;Promise.resolve().then(e).catch(e=>{t=!0,c(this,Rn,`m`,Qn).call(this,e)}).then(()=>{if(!t){try{this._emitFinal()}catch(e){c(this,Rn,`m`,Qn).call(this,e);return}this._emit(`end`)}})},0)}_connected(){this.ended||(c(this,Bn,`f`).call(this),this._emit(`connect`))}get ended(){return c(this,qn,`f`)}get errored(){return c(this,Jn,`f`)}get aborted(){return c(this,Yn,`f`)}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let t=()=>this.controller.abort();e.addEventListener(`abort`,t,{once:!0}),c(this,Kn,`f`).push({signal:e,listener:t})}on(e,t){var n;return((n=c(this,Gn,`f`))[e]||(n[e]=[])).push({listener:t}),this}off(e,t){let n=c(this,Gn,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r!==-1&&n.splice(r,1),this}once(e,t){var n;return((n=c(this,Gn,`f`))[e]||(n[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{s(this,Xn,!0,`f`);let r=t=>{this.off(e,i),n(t)},i=(...n)=>{e!==`error`&&this.off(`error`,r),t(n.length>1?n:n[0])};e!==`error`&&this.once(`error`,r),this.once(e,i)})}events(e){return this._createIterator(t=>{let n=(...e)=>t(e);return this.on(e,n),()=>this.off(e,n)},{rejectOnError:e!==`error`,rejectOnAbort:e!==`abort`})}_createIterator(e,{rejectOnError:t=!0,rejectOnAbort:n=!0,onReturn:r}={}){let i=$n(),a=$n(),o=this.ended,s,c=!1,l=()=>void 0,u=()=>({value:void 0,done:!0}),d=()=>{for(;a.length;)a.dequeue().resolve(u())},f=()=>{!s||c||!a.length||(c=!0,a.dequeue().reject(s))},p=()=>{l(),this.off(`end`,g),t&&this.off(`error`,h),n&&this.off(`abort`,h)},m=e=>{if(o)return;let t=a.dequeue();t?t.resolve({value:e,done:!1}):i.enqueue(e)},h=e=>{s=e,i.length||f()},g=()=>{o=!0,p(),i.length||(f(),d())};return o||(l=e(m),this.on(`end`,g),t&&this.on(`error`,h),n&&this.on(`abort`,h)),{next:()=>i.length?Promise.resolve({value:i.dequeue(),done:!1}):s&&!c?(c=!0,Promise.reject(s)):o?Promise.resolve(u()):new Promise((e,t)=>{a.enqueue({resolve:e,reject:t})}),return:()=>(o=!0,i.clear(),p(),d(),r&&(this.done().catch(()=>void 0),r()),Promise.resolve(u())),[Symbol.asyncIterator](){return this}}}async done(){s(this,Xn,!0,`f`),await c(this,Hn,`f`)}_hasListeners(e){return!!c(this,Gn,`f`)[e]?.length}_emit(e,...t){if(c(this,qn,`f`))return;e===`end`&&(c(this,Rn,`m`,Zn).call(this),s(this,qn,!0,`f`),c(this,Un,`f`).call(this));let n=c(this,Gn,`f`)[e];if(n){c(this,Gn,`f`)[e]=n.filter(e=>!e.once);for(let{listener:e}of n)e(...t)}if(e===`abort`){let e=t[0];!c(this,Xn,`f`)&&!n?.length&&Promise.reject(e),c(this,Vn,`f`).call(this,e),c(this,Wn,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!c(this,Xn,`f`)&&!n?.length&&Promise.reject(e),c(this,Vn,`f`).call(this,e),c(this,Wn,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};zn=new WeakMap,Bn=new WeakMap,Vn=new WeakMap,Hn=new WeakMap,Un=new WeakMap,Wn=new WeakMap,Gn=new WeakMap,Kn=new WeakMap,qn=new WeakMap,Jn=new WeakMap,Yn=new WeakMap,Xn=new WeakMap,Rn=new WeakSet,Zn=function(){for(let{signal:e,listener:t}of c(this,Kn,`f`).splice(0))e.removeEventListener(`abort`,t)},Qn=function(e){if(s(this,Jn,!0,`f`),e instanceof Error&&e.name===`AbortError`&&(e=new m),e instanceof m)return s(this,Yn,!0,`f`),this._emit(`abort`,e);if(e instanceof f)return this._emit(`error`,e);if(e instanceof Error){let t=new f(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new f(String(e)))};function tr(e){return typeof e.parse==`function`}var R,nr,rr,ir,ar,or,sr,cr,lr,ur=10;function dr(e){for(let t of e.choices)for(let e of t.message.tool_calls??[])e.id||=`call_${l()}`}function fr(e){if(!In(e))return e;let t={role:`assistant`};return e.audio!=null&&(t.audio={id:e.audio.id}),e.content!==void 0&&(t.content=e.content),e.function_call!=null&&(t.function_call=e.function_call),e.name!==void 0&&(t.name=e.name),e.refusal!=null&&(t.refusal=e.refusal),e.tool_calls!==void 0&&(t.tool_calls=e.tool_calls.map(e=>e.type===`custom`?{id:e.id,type:e.type,custom:{input:e.custom.input,name:e.custom.name}}:{id:e.id,type:e.type,function:{arguments:e.function.arguments,name:e.function.name}})),t}var pr=class extends er{constructor(){super(...arguments),R.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){dr(e),this._chatCompletions.push(e),this._emit(`chatCompletion`,e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if(`content`in e||(e.content=null),this.messages.push(e),t){if(this._emit(`message`,e),Ln(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(In(e)&&e.tool_calls)for(let t of e.tool_calls)t.type===`function`&&this._emit(`functionToolCall`,t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new f(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),c(this,R,`m`,rr).call(this)}async finalMessage(){return await this.done(),c(this,R,`m`,ir).call(this)}async finalFunctionToolCall(){return await this.done(),c(this,R,`m`,ar).call(this)}async finalFunctionToolCallResult(){return await this.done(),c(this,R,`m`,or).call(this)}async totalUsage(){return await this.done(),c(this,R,`m`,sr).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let t=c(this,R,`m`,ir).call(this);t&&this._emit(`finalMessage`,t);let n=c(this,R,`m`,rr).call(this);n&&this._emit(`finalContent`,n);let r=c(this,R,`m`,ar).call(this);r&&this._emit(`finalFunctionToolCall`,r);let i=c(this,R,`m`,or).call(this);i!=null&&this._emit(`finalFunctionToolCallResult`,i),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,c(this,R,`m`,sr).call(this))}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal),c(nr,nr,`m`,cr).call(nr,t);let r=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(An(r,t))}async _runChatCompletion(e,t,n){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n,r){let i=`tool`,{tool_choice:a=`auto`,stream:o,toolContext:s,...l}=t,u=s,d=typeof a!=`string`&&a.type===`function`&&a?.function?.name,{maxChatCompletions:p=ur,afterCompletion:m}=r||{},h=t.tools.map(e=>{if(On(e)){if(!e.$callback)throw new f("Tool given to `.runTools()` that does not have an associated function");return{type:`function`,function:{function:e.$callback,name:e.function.name,description:e.function.description||``,parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),g=Object.create(null);for(let e of h)e.type===`function`&&(g[e.function.name||e.function.function.name]=e.function);let _=`tools`in t?h.map(e=>e.type===`function`?{type:`function`,function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of t.messages)this._addMessage(e,!1);let v=async e=>{if(e.type!==`function`)return{message:void 0,functionCalled:!1};let t=e.id,{name:r,arguments:a}=e.function,o=g[r];if(!o){let e=`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(g).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;return{message:{role:i,tool_call_id:t,content:e},functionCalled:!1}}if(d&&d!==r){let e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(d)} requested. Please try again`;return{message:{role:i,tool_call_id:t,content:e},functionCalled:!1}}let s;if(tr(o)){let e;try{e=await o.parse(a)}catch(e){let n=e instanceof Error?e.message:String(e);return{message:{role:i,tool_call_id:t,content:n},functionCalled:!1}}s=await o.function(e,n,u)}else s=await o.function(a,n,u);let l=c(nr,nr,`m`,lr).call(nr,s);return{message:{role:i,tool_call_id:t,content:l},functionCalled:!0}};for(let i=0;i<p;++i){let i=await this._createChatCompletion(e,{...l,tool_choice:a,tools:_,messages:this.messages.map(fr)},r),o=i.choices[0]?.message;if(!o)throw new f(`missing message in ChatCompletion response`);if(!o.tool_calls?.length){await m?.(i,n);return}if(d||t.parallel_tool_calls===!1)for(let e of o.tool_calls){let t=await v(e);if(t.message&&this._addMessage(t.message),d&&t.functionCalled){await m?.(i,n);return}}else{let e=await Promise.allSettled(o.tool_calls.map(v));for(let t of e)if(t.status===`rejected`)throw t.reason;for(let t of e)t.status===`fulfilled`&&t.value.message&&this._addMessage(t.value.message)}await m?.(i,n)}}};nr=pr,R=new WeakSet,rr=function(){return c(this,R,`m`,ir).call(this).content??null},ir=function(){let e=this.messages.length;for(;e-->0;){let t=this.messages[e];if(In(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new f(`stream ended without producing a ChatCompletionMessage with role=assistant`)},ar=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(In(t)&&t?.tool_calls?.length)for(let e=t.tool_calls.length-1;e>=0;e--){let n=t.tool_calls[e];if(n?.type===`function`)return n.function}}},or=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Ln(t)&&t.content!=null&&typeof t.content==`string`&&this.messages.some(e=>e.role===`assistant`&&e.tool_calls?.some(e=>e.type===`function`&&e.id===t.tool_call_id)))return t.content}},sr=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},cr=function(e){if(e.n!=null&&e.n>1)throw new f(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},lr=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var mr=class e extends pr{static runTools(t,n,r){let i=new e,a={...r,__metadata:{...r?.__metadata,helperMethod:`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),In(e)&&e.content&&this._emit(`content`,e.content)}},z={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},hr=class extends Error{},gr=class extends Error{};function _r(e,t=z.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return vr(e.trim(),t)}var vr=(e,t)=>{let n=e.length,r=0,i=e=>{throw new hr(`${e} at position ${r}`)},a=e=>{throw new gr(`${e} at position ${r}`)},o=()=>(d(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?s():e[r]===`{`?c():e[r]===`[`?l():e.substring(r,r+4)===`null`||z.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||z.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||z.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||z.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||z.MINUS_INFINITY&t&&n-r>1&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||z.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):u()),s=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`&&!s,r++;if(e.charAt(r)===`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(z.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},c=()=>{r++,d();let a={};try{for(;e[r]!==`}`;){if(d(),r>=n&&z.OBJ&t)return a;let i=s();d(),r++;try{let e=o();Object.defineProperty(a,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(z.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(z.OBJ&t)return a;i(`Expected '}' at end of object`)}return r++,a},l=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(o()),d(),e[r]===`,`&&r++}catch{if(z.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&z.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(z.NUM&t)try{return e[e.length-1]===`.`?JSON.parse(e.substring(0,e.lastIndexOf(`.`))):JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}a(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&!`,]}`.includes(e[r]);)r++;r===n&&!(z.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&z.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e.substring(o,e.lastIndexOf(`e`)))}catch(e){a(String(e))}}},d=()=>{for(;r<n&&`
|
|
8
|
+
\r `.includes(e[r]);)r++};return o()},yr=e=>_r(e,z.ALL^z.NUM),B,V,br,xr,H,Sr,Cr,wr,Tr,Er,Dr,Or,kr=`chat.completion.chunk.message:`;function Ar(e,t,n){let r={type:`message`,message:t,...n?{tool_call_ids:n}:{}};return{id:e.id,choices:[],created:e.created,model:e.model,object:`${kr}${JSON.stringify(r)}`}}function jr(e){return`type`in e&&e.type===`message`&&`message`in e||`object`in e&&typeof e.object==`string`&&e.object.startsWith(kr)}function Mr(e){return`type`in e?e:JSON.parse(e.object.slice(30))}var Nr=128,Pr=128;function Fr(e,t){return Object.prototype.propertyIsEnumerable.call(t,`__proto__`)&&!pe(e,`__proto__`)&&Object.defineProperty(e,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0}),Object.assign(e,t)}var Ir=class e extends pr{constructor(e){super(),B.add(this),V.set(this,void 0),br.set(this,void 0),xr.set(this,void 0),H.set(this,void 0),s(this,V,e,`f`),s(this,br,new Set,`f`),s(this,xr,[],`f`)}get currentChatCompletionSnapshot(){return c(this,H,`f`)}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createChatCompletion(t,n,r){let i=new e(n);return i._run(()=>i._runChatCompletion(t,{...n,stream:!0},{...r,__metadata:{...r?.__metadata,helperMethod:`stream`}})),i}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal),c(this,B,`m`,Sr).call(this);let r=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let e of r)c(this,B,`m`,wr).call(this,e);if(r.controller.signal?.aborted)throw new m;return this._addChatCompletion(c(this,B,`m`,Dr).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),c(this,B,`m`,Sr).call(this),this._connected();let n=Ve.fromReadableStream(e,this.controller),r;for await(let e of n){if(jr(e)){let t=Mr(e);if(c(this,H,`f`)){let e=c(this,H,`f`).choices[0]?.message.tool_calls;for(let[n,r]of t.tool_call_ids?.entries()??[]){let t=e?.[n];t&&r&&(t.id=r)}this._addChatCompletion(c(this,B,`m`,Dr).call(this)),r=void 0}this._addMessage(t.message);continue}let t=e;r&&t.id&&r!==t.id&&this._addChatCompletion(c(this,B,`m`,Dr).call(this)),c(this,B,`m`,wr).call(this,t),t.id&&(r=t.id)}if(n.controller.signal?.aborted)throw new m;if(c(this,H,`f`))return this._addChatCompletion(c(this,B,`m`,Dr).call(this));let i=this._chatCompletions[this._chatCompletions.length-1];if(i)return i;throw new f(`request ended without sending any chunks`)}[(V=new WeakMap,br=new WeakMap,xr=new WeakMap,H=new WeakMap,B=new WeakSet,Sr=function(){this.ended||(s(this,br,new Set,`f`),s(this,H,void 0,`f`))},Cr=function(e){let t=c(this,xr,`f`)[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},c(this,xr,`f`)[e.index]=t,t)},wr=function(e){if(this.ended)return;let t=c(this,B,`m`,Or).call(this,e);this._emit(`chunk`,e,t);for(let n of e.choices){let e=t.choices[n.index],{delta:r}=n;r?.content!=null&&e.message?.role===`assistant`&&e.message?.content&&(this._emit(`content`,r.content,e.message.content),this._emit(`content.delta`,{delta:r.content,snapshot:e.message.content,parsed:e.message.parsed})),r?.refusal!=null&&e.message?.role===`assistant`&&e.message?.refusal&&this._emit(`refusal.delta`,{delta:r.refusal,snapshot:e.message.refusal}),n.logprobs?.content!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.content.delta`,{content:n.logprobs?.content,snapshot:e.logprobs?.content??[]}),n.logprobs?.refusal!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.refusal.delta`,{refusal:n.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let i=c(this,B,`m`,Cr).call(this,e);e.finish_reason&&(c(this,B,`m`,Er).call(this,e),i.current_tool_call_index!=null&&c(this,B,`m`,Tr).call(this,e,i.current_tool_call_index));for(let t of r?.tool_calls??[])i.current_tool_call_index!==t.index&&(c(this,B,`m`,Er).call(this,e),i.current_tool_call_index!=null&&c(this,B,`m`,Tr).call(this,e,i.current_tool_call_index)),i.current_tool_call_index=t.index;for(let t of r?.tool_calls??[]){let n=e.message.tool_calls?.[t.index];n?.type&&(n.type===`function`?this._emit(`tool_calls.function.arguments.delta`,{name:n.function.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??``}):n.type)}}},Tr=function(e,t){if(c(this,B,`m`,Cr).call(this,e).done_tool_calls.has(t))return;let n=e.message.tool_calls?.[t];if(!n)throw Error(`no tool call snapshot`);if(!n.type)throw Error("tool call snapshot missing `type`");if(n.type===`function`){let e=c(this,V,`f`)?.tools?.find(e=>wn(e)&&e.function.name===n.function.name),r=null;On(e)?r=e.$parseRaw(n.function.arguments):e?.function.strict&&(r=JSON.parse(n.function.arguments)),this._emit(`tool_calls.function.arguments.done`,{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:r})}else n.type},Er=function(e){let t=c(this,B,`m`,Cr).call(this,e);e.message.content!=null&&(e.message.content!==``||!e.message.refusal&&!e.message.tool_calls?.length&&!e.message.function_call)&&!t.content_done&&(t.content_done=!0,this._emit(`content.done`,{content:e.message.content,parsed:e.message.refusal?null:Dn(c(this,V,`f`)?.response_format,e.message.content)})),e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit(`refusal.done`,{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit(`logprobs.content.done`,{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit(`logprobs.refusal.done`,{refusal:e.logprobs.refusal}))},Dr=function(){if(this.ended)throw new f(`stream has ended, this shouldn't happen`);let e=c(this,H,`f`);if(!e)throw new f(`request ended without sending any chunks`);let t=c(this,br,`f`);return s(this,br,new Set,`f`),s(this,H,void 0,`f`),s(this,xr,[],`f`),Lr(e,c(this,V,`f`),t)},Or=function(e){var t,n,r,i,a;let o=c(this,H,`f`),{choices:l,...u}=e;if(o)e.id&&Fr(o,u);else{let e={...u,choices:[]};s(this,H,e,`f`),o=e}let d=c(this,V,`f`)?.n,p=typeof d==`number`&&Number.isSafeInteger(d)&&d>0?Math.min(d,Nr):Nr;for(let{delta:s,finish_reason:l,index:u,logprobs:d=null,...m}of e.choices){if(!Number.isSafeInteger(u)||u<0||u>=p)throw new f(`Chat completion stream contains an invalid choice index: ${u}`);let e=o.choices[u];if(!e){let t={finish_reason:l,index:u,message:{},logprobs:d,...m};o.choices[u]=t,e=t}if(d)if(e.logprobs){let{content:r,refusal:i,...a}=d;Fr(e.logprobs,a),r&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...r)),i&&((n=e.logprobs).refusal??(n.refusal=[]),e.logprobs.refusal.push(...i))}else e.logprobs={...d};if(l&&(e.finish_reason=l,c(this,V,`f`)&&Pn(c(this,V,`f`)))){if(l===`length`)throw new re;if(l===`content_filter`)throw new ie}if(Fr(e,m),!s)continue;c(this,br,`f`).delete(u);let{audio:h,content:g,refusal:_,function_call:v,role:y,tool_calls:b,...x}=s;if(Fr(e.message,x),h?.expires_at!=null&&h.id==null&&h.data==null&&h.transcript==null&&g==null&&_==null&&v==null&&y==null&&b==null&&Object.keys(x).length===0&&c(this,br,`f`).add(u),_&&(e.message.refusal=(e.message.refusal||``)+_),y&&(e.message.role=y),h){let t=(r=e.message).audio??(r.audio={});h.id!=null&&(t.id=h.id),h.data!=null&&(t.data=(t.data??``)+h.data),h.transcript!=null&&(t.transcript=(t.transcript??``)+h.transcript),h.expires_at!=null&&(t.expires_at=h.expires_at)}if(v&&(e.message.function_call?(v.name&&(e.message.function_call.name=v.name),v.arguments&&((i=e.message.function_call).arguments??(i.arguments=``),e.message.function_call.arguments+=v.arguments)):e.message.function_call=v),g!=null&&(e.message.content=(e.message.content||``)+g,!e.message.refusal&&En(c(this,V,`f`)?.response_format)&&(e.message.parsed=e.message.content.trim()?yr(e.message.content):null)),b){let t=(a=e.message).tool_calls??(a.tool_calls=[]);for(let{index:e,id:n,type:r,function:i,custom:a,...o}of b){if(!Number.isSafeInteger(e)||e<0||e>=Pr)throw new f(`Chat completion stream contains an invalid tool call index: ${e}`);let s=t[e]??(t[e]={});if(Fr(s,o),n&&(s.id=n),r&&(s.type=r),a){let e=s.custom??={name:a.name??``,input:``};a.name&&(e.name=a.name),a.input&&(e.input+=a.input)}if(i){let e=s.function??={name:i.name??``,arguments:``};i.name&&(e.name=i.name),i.arguments&&(e.arguments+=i.arguments,Nn(c(this,V,`f`),s)&&(e.parsed_arguments=yr(e.arguments)))}}}}return o},Symbol.asyncIterator)](){return this._createIterator(e=>{let t=t=>e(t);return this.on(`chunk`,t),()=>this.off(`chunk`,t)},{onReturn:()=>this.abort()})}toReadableStream(){return new Ve(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Lr(e,t,n){let{id:r,choices:i,created:a,model:o,system_fingerprint:s,...c}=e;return kn({...c,id:r,choices:i.map(({message:t,finish_reason:r,index:i,logprobs:a,...o})=>{let{content:s=null,function_call:c,tool_calls:u,audio:d,...p}=t,m=r??(n.has(i)&&Rr(d)?`stop`:null);if(!m)throw new f(`missing finish_reason for choice ${i}`);let h=d?{audio:d}:{},g=t.role;if(!g)throw new f(`missing role for choice ${i}`);if(c){let{arguments:e,name:n}=c;if(e==null)throw new f(`missing function_call.arguments for choice ${i}`);if(!n)throw new f(`missing function_call.name for choice ${i}`);return{...o,message:{...h,content:s,function_call:{arguments:e,name:n},role:g,refusal:t.refusal??null},finish_reason:m,index:i,logprobs:a}}return u?{...o,index:i,finish_reason:m,logprobs:a,message:{...p,...h,role:g,content:s,refusal:t.refusal??null,tool_calls:u.map((t,n)=>{if(t.type==null)throw new f(`missing choices[${i}].tool_calls[${n}].type\n${zr(e)}`);if(t.type===`custom`){let{custom:r,type:a,id:o,...s}=t,{input:c=``,name:u,...d}=r||{};if(u==null)throw new f(`missing choices[${i}].tool_calls[${n}].custom.name\n${zr(e)}`);return{...s,id:o||`call_${l()}`,type:a,custom:{...d,name:u,input:c}}}let{function:r,type:a,id:o,...s}=t,{arguments:c,name:u,...d}=r||{};if(u==null)throw new f(`missing choices[${i}].tool_calls[${n}].function.name\n${zr(e)}`);if(c==null)throw new f(`missing choices[${i}].tool_calls[${n}].function.arguments\n${zr(e)}`);return{...s,id:o||`call_${l()}`,type:a,function:{...d,name:u,arguments:c}}})}}:{...o,message:{...p,...h,content:s,role:g,refusal:t.refusal??null},finish_reason:m,index:i,logprobs:a}}),created:a,model:o,object:`chat.completion`,...s?{system_fingerprint:s}:{}},t)}function Rr(e){return e?.id!=null&&e.data!=null&&e.transcript!=null&&e.expires_at!=null}function zr(e){return JSON.stringify(e)}var Br=class e extends Ir{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}toReadableStream(){let e,t,n=this._createIterator(n=>{let r=t=>{e=t,n(t)},i=r=>{if(In(r)){t=r.tool_calls?.map(e=>e.id);return}if(Ln(r)){if(!e)throw new f(`cannot serialize a tool message before receiving any chunks`);n(Ar(e,r,t))}};return this.on(`chunk`,r),this.on(`message`,i),()=>{this.off(`chunk`,r),this.off(`message`,i)}},{onReturn:()=>this.abort()});return new Ve(()=>n,this.controller).toReadableStream()}static runTools(t,n,r){let i=new e(n),a={...r,__metadata:{...r?.__metadata,helperMethod:`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}},Vr=class extends I{constructor(){super(...arguments),this.messages=new Cn(this._client)}create(e,t){return this._client.post(`/chat/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(L`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(L`/chat/completions/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chat/completions`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return Fn(e.tools),this._client.chat.completions.create(e,{...t,__metadata:{...t?.__metadata,helperMethod:`chat.completions.parse`}})._thenUnwrap(t=>An(t,e))}runTools(e,t){return e.stream?Br.runTools(this._client,e,t):mr.runTools(this._client,e,t)}stream(e,t){return Ir.createChatCompletion(this._client,e,t)}};Vr.Messages=Cn;var Hr=class extends I{constructor(){super(...arguments),this.completions=new Vr(this._client)}};Hr.Completions=Vr;var Ur=class extends I{create(e,t){return this._client.post(`/organization/admin_api_keys`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(L`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/admin_api_keys`,M,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Wr=class extends I{list(e={},t){return this._client.getAPIList(`/organization/audit_logs`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},Gr=class extends I{create(e,t){return this._client.post(`/organization/certificates`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(L`/organization/certificates/${e}`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(L`/organization/certificates/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/certificates`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList(`/organization/certificates/activate`,kt,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList(`/organization/certificates/deactivate`,kt,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}},Kr=class extends I{retrieve(e){return this._client.get(`/organization/data_retention`,{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post(`/organization/data_retention`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}},qr=class extends I{create(e,t){return this._client.post(`/organization/invites`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(L`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/invites`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Jr=class extends I{create(e,t){return this._client.post(`/organization/roles`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(L`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(L`/organization/roles/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/roles`,At,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Yr=class extends I{create(e,t){return this._client.post(`/organization/spend_alerts`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(L`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(L`/organization/spend_alerts/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/spend_alerts`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Xr=class extends I{retrieve(e){return this._client.get(`/organization/spend_limit`,{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post(`/organization/spend_limit`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e){return this._client.delete(`/organization/spend_limit`,{...e,__security:{adminAPIKeyAuth:!0}})}},Zr=class extends I{audioSpeeches(e,t){return this._client.get(`/organization/usage/audio_speeches`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,t){return this._client.get(`/organization/usage/audio_transcriptions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,t){return this._client.get(`/organization/usage/code_interpreter_sessions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}completions(e,t){return this._client.get(`/organization/usage/completions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}costs(e,t){return this._client.get(`/organization/costs`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}embeddings(e,t){return this._client.get(`/organization/usage/embeddings`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,t){return this._client.get(`/organization/usage/file_search_calls`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}images(e,t){return this._client.get(`/organization/usage/images`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}moderations(e,t){return this._client.get(`/organization/usage/moderations`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,t){return this._client.get(`/organization/usage/vector_stores`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,t){return this._client.get(`/organization/usage/web_search_calls`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},Qr=class extends I{create(e,t,n){return this._client.post(L`/organization/groups/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(L`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/groups/${e}/roles`,At,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(L`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},$r=class extends I{create(e,t,n){return this._client.post(L`/organization/groups/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(L`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/groups/${e}/users`,At,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(L`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},ei=class extends I{constructor(){super(...arguments),this.users=new $r(this._client),this.roles=new Qr(this._client)}create(e,t){return this._client.post(`/organization/groups`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(L`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(L`/organization/groups/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/groups`,At,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};ei.Users=$r,ei.Roles=Qr;var ti=class extends I{retrieve(e,t,n){let{project_id:r}=t;return this._client.get(L`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/api_keys`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(L`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},ni=class extends I{list(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/certificates`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,t,n){return this._client.getAPIList(L`/organization/projects/${e}/certificates/activate`,kt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,n){return this._client.getAPIList(L`/organization/projects/${e}/certificates/deactivate`,kt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}},ri=class extends I{retrieve(e,t){return this._client.get(L`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(L`/organization/projects/${e}/data_retention`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}},ii=class extends I{retrieve(e,t){return this._client.get(L`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(L`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}},ai=class extends I{retrieve(e,t){return this._client.get(L`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(L`/organization/projects/${e}/model_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}},oi=class extends I{listRateLimits(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/rate_limits`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/organization/projects/${r}/rate_limits/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}},si=class extends I{create(e,t,n){return this._client.post(L`/projects/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(L`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/projects/${r}/roles/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/projects/${e}/roles`,At,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(L`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},ci=class extends I{create(e,t,n){return this._client.post(L`/organization/projects/${e}/spend_alerts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(L`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/organization/projects/${r}/spend_alerts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/spend_alerts`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(L`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},li=class extends I{retrieve(e,t){return this._client.get(L`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(L`/organization/projects/${e}/spend_limit`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}},ui=class extends I{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/projects/${r}/groups/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,group_id:i}=t;return this._client.get(L`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(L`/projects/${r}/groups/${e}/roles`,At,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,group_id:i}=t;return this._client.delete(L`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},di=class extends I{constructor(){super(...arguments),this.roles=new ui(this._client)}create(e,t,n){return this._client.post(L`/organization/projects/${e}/groups`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,...i}=t;return this._client.get(L`/organization/projects/${r}/groups/${e}`,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/groups`,At,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(L`/organization/projects/${r}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};di.Roles=ui;var fi=class extends I{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/organization/projects/${r}/service_accounts/${e}/api_keys`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}},pi=class extends I{constructor(){super(...arguments),this.apiKeys=new fi(this._client)}create(e,t,n){return this._client.post(L`/organization/projects/${e}/service_accounts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(L`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/organization/projects/${r}/service_accounts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/service_accounts`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(L`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};pi.APIKeys=fi;var mi=class extends I{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/projects/${r}/users/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,user_id:i}=t;return this._client.get(L`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(L`/projects/${r}/users/${e}/roles`,At,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,user_id:i}=t;return this._client.delete(L`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},hi=class extends I{constructor(){super(...arguments),this.roles=new mi(this._client)}create(e,t,n){return this._client.post(L`/organization/projects/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(L`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/organization/projects/${r}/users/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/users`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(L`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};hi.Roles=mi;var U=class extends I{constructor(){super(...arguments),this.users=new hi(this._client),this.serviceAccounts=new pi(this._client),this.apiKeys=new ti(this._client),this.rateLimits=new oi(this._client),this.modelPermissions=new ai(this._client),this.hostedToolPermissions=new ii(this._client),this.groups=new di(this._client),this.roles=new si(this._client),this.dataRetention=new ri(this._client),this.spendLimit=new li(this._client),this.spendAlerts=new ci(this._client),this.certificates=new ni(this._client)}create(e,t){return this._client.post(`/organization/projects`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(L`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(L`/organization/projects/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/projects`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(L`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};U.Users=hi,U.ServiceAccounts=pi,U.APIKeys=ti,U.RateLimits=oi,U.ModelPermissions=ai,U.HostedToolPermissions=ii,U.Groups=di,U.Roles=si,U.DataRetention=ri,U.SpendLimit=li,U.SpendAlerts=ci,U.Certificates=ni;var gi=class extends I{create(e,t,n){return this._client.post(L`/organization/users/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{user_id:r}=t;return this._client.get(L`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/users/${e}/roles`,At,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{user_id:r}=t;return this._client.delete(L`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},_i=class extends I{constructor(){super(...arguments),this.roles=new gi(this._client)}retrieve(e,t){return this._client.get(L`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(L`/organization/users/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/users`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};_i.Roles=gi;var W=class extends I{constructor(){super(...arguments),this.auditLogs=new Wr(this._client),this.adminAPIKeys=new Ur(this._client),this.usage=new Zr(this._client),this.invites=new qr(this._client),this.users=new _i(this._client),this.groups=new ei(this._client),this.roles=new Jr(this._client),this.dataRetention=new Kr(this._client),this.spendLimit=new Xr(this._client),this.spendAlerts=new Yr(this._client),this.certificates=new Gr(this._client),this.projects=new U(this._client)}};W.AuditLogs=Wr,W.AdminAPIKeys=Ur,W.Usage=Zr,W.Invites=qr,W.Users=_i,W.Groups=ei,W.Roles=Jr,W.DataRetention=Kr,W.SpendLimit=Xr,W.SpendAlerts=Yr,W.Certificates=Gr,W.Projects=U;var vi=class extends I{constructor(){super(...arguments),this.organization=new W(this._client)}};vi.Organization=W;var yi=class extends I{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:P([{Accept:`application/octet-stream`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},bi=class extends I{create(e,t){return this._client.post(`/audio/transcriptions`,F({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},xi=class extends I{create(e,t){return this._client.post(`/audio/translations`,F({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},Si=class extends I{constructor(){super(...arguments),this.transcriptions=new bi(this._client),this.translations=new xi(this._client),this.speech=new yi(this._client)}};Si.Transcriptions=bi,Si.Translations=xi,Si.Speech=yi;var Ci=class extends I{create(e,t){return this._client.post(`/batches`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(L`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/batches`,M,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(L`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}},wi=class extends I{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(L`/assistants/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(L`/assistants/${e}`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/assistants`,M,{query:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/assistants/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},Ti=class extends I{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},Ei=class extends I{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},Di=class extends I{constructor(){super(...arguments),this.sessions=new Ti(this._client),this.transcriptionSessions=new Ei(this._client)}};Di.Sessions=Ti,Di.TranscriptionSessions=Ei;var Oi=class extends I{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(L`/chatkit/sessions/${e}/cancel`,{...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}},ki=class extends I{retrieve(e,t){return this._client.get(L`/chatkit/threads/${e}`,{...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,N,{query:e,...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/chatkit/threads/${e}`,{...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},n){return this._client.getAPIList(L`/chatkit/threads/${e}/items`,N,{query:t,...n,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers]),__security:{bearerAuth:!0}})}},Ai=class extends I{constructor(){super(...arguments),this.sessions=new Oi(this._client),this.threads=new ki(this._client)}};Ai.Sessions=Oi,Ai.Threads=ki;var ji=class extends I{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(L`/responses/${e}/input_items?beta=true`,M,{query:i,...n,headers:P([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}},Mi=class extends I{count(e={},t){let{betas:n,...r}=e??{};return this._client.post(`/responses/input_tokens?beta=true`,{body:r,...t,headers:P([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),__security:{bearerAuth:!0}})}},Ni=class extends I{constructor(){super(...arguments),this.inputItems=new ji(this._client),this.inputTokens=new Mi(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/responses?beta=true`,{body:r,...t,headers:P([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t={},n){let{betas:r,...i}=t??{};return this._client.get(L`/responses/${e}?beta=true`,{query:i,...n,headers:P([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(L`/responses/${e}?beta=true`,{...n,headers:P([{Accept:`*/*`,...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t={},n){let{betas:r}=t??{};return this._client.post(L`/responses/${e}/cancel?beta=true`,{...n,headers:P([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}compact(e,t){let{betas:n,...r}=e;return this._client.post(`/responses/compact?beta=true`,{body:r,...t,headers:P([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),__security:{bearerAuth:!0}})}};Ni.InputItems=ji,Ni.InputTokens=Mi;var Pi=class extends I{create(e,t,n){return this._client.post(L`/threads/${e}/messages`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(L`/threads/${r}/messages/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(L`/threads/${r}/messages/${e}`,{body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/threads/${e}/messages`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(L`/threads/${r}/messages/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},Fi=class extends I{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(L`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(L`/threads/${r}/runs/${e}/steps`,M,{query:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},Ii=e=>{if(globalThis.Buffer!==void 0){let t=globalThis.Buffer.from(e,`base64`);return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}if(typeof atob<`u`){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}throw new f("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")},Li=e=>{if(typeof Buffer<`u`){let t=Buffer.from(e,`base64`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}},G=e=>{if(globalThis.process!==void 0)return{}[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0},Ri=1024,zi=65536,Bi=new WeakMap,Vi=new WeakSet;function Hi(e){return{arrays:new Map,cacheArrays:e,records:new WeakMap}}function Ui(e){for(let[t,n]of e.arrays)n.cacheable&&!Vi.has(t)?Bi.set(t,{length:n.length,ownEntryCount:n.ownEntryCount}):Bi.delete(t)}function Wi(e){return typeof e==`string`||typeof e==`number`}function Gi(e,t){return t.every(Wi)&&e.every(Wi)}function Ki(e){let t=0;for(let n of Object.keys(e)){let r=Number(n);Number.isSafeInteger(r)&&r>=0&&r<e.length&&String(r)===n&&(t+=1)}return t}function qi(e,t,n){return t?n?.length===e.length?n.ownEntryCount:Ki(e):0}function Ji(e,t,n){let{index:r}=e;if(t===`array`&&r==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(t===`array`&&typeof r!=`number`)throw TypeError(`Expected array delta entry \`index\` property to be a number but got ${r}`);if(!Number.isSafeInteger(r)||r<0||r>=n+Ri||r>=zi)throw new f(`Assistant stream delta contains an invalid ${t} index: ${r}`);return r}function Yi(e,t,n,r,i){let a=r.arrays.get(e);if(!a){let t=r.cacheArrays&&!Vi.has(e),n=t?Bi.get(e):void 0;a={baselineLength:e.length,cacheable:t,enforceSparseHoleBudget:t,entries:new Map,length:e.length,ownEntryCount:qi(e,t,n)},r.arrays.set(e,a)}for(let o of t){if(!C(o))throw Error(`Expected array delta entry to be an object but got: ${o}`);let t=Ji(o,n,a.baselineLength),s;a.entries.has(t)?s=a.entries.get(t):pe(e,t)?(s=e[t],s??a.entries.set(t,o)):(a.entries.set(t,o),a.ownEntryCount+=1);let c=Math.max(a.length,t+1);if(a.enforceSparseHoleBudget&&c-a.ownEntryCount>Ri)throw new f(`Assistant stream delta contains an invalid ${n} index: ${t}`);C(s)&&i(s,o,r),a.length=c}}function Xi(e,t,n){let r=n.records.get(e);for(let[i,a]of Object.entries(t)){if(i===`index`||i===`type`)continue;let t;if(r?.has(i)?t=r.get(i):pe(e,i)&&(t=e[i]),t==null){r||(r=new Map,n.records.set(e,r)),r.set(i,a);continue}C(t)&&C(a)?Xi(t,a,n):Array.isArray(t)&&Array.isArray(a)&&!Gi(t,a)&&Yi(t,a,`array`,n,Xi)}}function Zi(e){return(C(e)||Array.isArray(e))&&Vi.has(e)}function K(e){if(!(!C(e)&&!Array.isArray(e)||Vi.has(e))){Vi.add(e),Array.isArray(e)&&Bi.delete(e);for(let t of Reflect.ownKeys(e)){let n=Object.getOwnPropertyDescriptor(e,t);n&&`value`in n&&K(n.value)}}}function Qi(e,t,n){Vi.has(e)&&K(n),Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}function $i(e){let{index:t}=e;if(t==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(typeof t!=`number`)throw TypeError(`Expected array delta entry \`index\` property to be a number but got ${t}`);return t}function ea(e,t,n){if(Gi(e,t)){e.push(...t),Bi.delete(e);return}for(let r of t){if(!C(r))throw Error(`Expected array delta entry to be an object but got: ${r}`);let t=$i(r);if(pe(e,t)){let i=e[t];i==null?(Vi.has(e)&&K(r),e[t]=r):e[t]=n(i,r)}else Qi(e,t,r)}}function ta(e,t){let n=Vi.has(e);for(let[r,i]of Object.entries(t)){if(r===`__proto__`||r===`constructor`||r===`prototype`)throw new f(`Assistant stream delta contains an unsafe property: ${r}`);if(!pe(e,r)){n&&K(i),e[r]=i;continue}let t=e[r];if(t==null){n&&K(i),e[r]=i;continue}if(r===`index`||r===`type`){e[r]=i;continue}if(typeof t==`string`&&typeof i==`string`)t+=i;else if(typeof t==`number`&&typeof i==`number`)t+=i;else if(C(t)&&C(i))t=ta(t,i);else if(Array.isArray(t)&&Array.isArray(i)){ea(t,i,ta);continue}else throw TypeError(`Unhandled record type: ${r}, deltaValue: ${i}, accValue: ${t}`);e[r]=t}return e}function na(e){if(!(!C(e)&&!Array.isArray(e)))for(let[t,n]of Object.entries(e)){if(t===`__proto__`||t===`constructor`||t===`prototype`)throw new f(`Assistant stream delta contains an unsafe property: ${t}`);na(n)}}function ra(e,t,n=!1){na(t);let r=e,i=t,a=Hi(n&&!Zi(e));return Xi(r,i,a),ta(r,i),Ui(a),e}function ia(e,t,n,r=!0){na(t);let i=Hi(r&&!Zi(e));return Yi(e,t,n,i,Xi),()=>Ui(i)}var q,aa,oa,sa,J,ca,la,ua,da,Y,fa,pa,ma,ha,ga,_a,va,X,ya,ba,xa,Sa,Ca,wa=class e extends er{constructor(){super(...arguments),q.add(this),aa.set(this,[]),oa.set(this,Object.create(null)),sa.set(this,Object.create(null)),J.set(this,void 0),ca.set(this,void 0),la.set(this,void 0),ua.set(this,void 0),da.set(this,void 0),Y.set(this,void 0),fa.set(this,void 0),pa.set(this,void 0),ma.set(this,void 0)}[(aa=new WeakMap,oa=new WeakMap,sa=new WeakMap,J=new WeakMap,ca=new WeakMap,la=new WeakMap,ua=new WeakMap,da=new WeakMap,Y=new WeakMap,fa=new WeakMap,pa=new WeakMap,ma=new WeakMap,q=new WeakSet,Symbol.asyncIterator)](){return this._createIterator(e=>{let t=t=>e(structuredClone(t));return this.on(`event`,t),()=>this.off(`event`,t)},{onReturn:()=>this.abort()})}static fromReadableStream(t){let n=new e;return n._run(()=>n._fromReadableStream(t)),n}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let n=Ve.fromReadableStream(e,this.controller);for await(let e of n)c(this,q,`m`,ha).call(this,e);if(n.controller.signal?.aborted)throw new m;return this._addRun(c(this,q,`m`,ga).call(this))}toReadableStream(){return new Ve(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,n,r,i){let a=new e;return a._run(()=>a._runToolAssistantStream(t,n,r,{...i,__metadata:{...i?.__metadata,helperMethod:`stream`}})),a}async _createToolAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},a=await e.submitToolOutputs(t,i,{...r,signal:this.controller.signal});this._connected();for await(let e of a)c(this,q,`m`,ha).call(this,e);if(a.controller.signal?.aborted)throw new m;return this._addRun(c(this,q,`m`,ga).call(this))}static createThreadAssistantStream(t,n,r){let i=new e;return i._run(()=>i._threadAssistantStream(t,n,{...r,__metadata:{...r?.__metadata,helperMethod:`stream`}})),i}static createAssistantStream(t,n,r,i){let a=new e;return a._run(()=>a._runAssistantStream(t,n,r,{...i,__metadata:{...i?.__metadata,helperMethod:`stream`}})),a}currentEvent(){return K(c(this,fa,`f`)),c(this,fa,`f`)}currentRun(){return K(c(this,pa,`f`)),c(this,pa,`f`)}currentMessageSnapshot(){return K(c(this,J,`f`)),c(this,J,`f`)}currentRunStepSnapshot(){return K(c(this,ma,`f`)),c(this,ma,`f`)}async finalRunSteps(){return await this.done(),Object.values(c(this,oa,`f`))}async finalMessages(){return await this.done(),Object.values(c(this,sa,`f`))}async finalRun(){if(await this.done(),!c(this,ca,`f`))throw Error(`Final run was not received.`);return c(this,ca,`f`)}async _createThreadAssistantStream(e,t,n){this._listenForAbort(n?.signal);let r={...t,stream:!0},i=await e.createAndRun(r,{...n,signal:this.controller.signal});this._connected();for await(let e of i)c(this,q,`m`,ha).call(this,e);if(i.controller.signal?.aborted)throw new m;return this._addRun(c(this,q,`m`,ga).call(this))}async _createAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},a=await e.create(t,i,{...r,signal:this.controller.signal});this._connected();for await(let e of a)c(this,q,`m`,ha).call(this,e);if(a.controller.signal?.aborted)throw new m;return this._addRun(c(this,q,`m`,ga).call(this))}static accumulateDelta(e,t){return ra(e,t)}_addRun(e){return c(this,q,`m`,X).call(this,`run`,e),e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}};ha=function(e){if(!this.ended)switch(s(this,fa,e,`f`),c(this,q,`m`,ya).call(this,e),e.event){case`thread.created`:break;case`thread.run.created`:case`thread.run.queued`:case`thread.run.in_progress`:case`thread.run.requires_action`:case`thread.run.completed`:case`thread.run.incomplete`:case`thread.run.failed`:case`thread.run.cancelling`:case`thread.run.cancelled`:case`thread.run.expired`:c(this,q,`m`,Ca).call(this,e);break;case`thread.run.step.created`:case`thread.run.step.in_progress`:case`thread.run.step.delta`:case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:c(this,q,`m`,va).call(this,e);break;case`thread.message.created`:case`thread.message.in_progress`:case`thread.message.delta`:case`thread.message.completed`:case`thread.message.incomplete`:c(this,q,`m`,_a).call(this,e);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`)}},ga=function(){if(this.ended)throw new f(`stream has ended, this shouldn't happen`);if(!c(this,ca,`f`))throw Error(`Final run has not been received`);return c(this,ca,`f`)},_a=function(e){let[t,n]=c(this,q,`m`,xa).call(this,e,c(this,J,`f`));s(this,J,t,`f`),c(this,sa,`f`)[t.id]=t;for(let e of n){let n=t.content[e.index];n?.type===`text`&&c(this,q,`m`,X).call(this,`textCreated`,n.text)}switch(e.event){case`thread.message.created`:s(this,la,void 0,`f`),s(this,ua,void 0,`f`),c(this,q,`m`,X).call(this,`messageCreated`,e.data);break;case`thread.message.in_progress`:break;case`thread.message.delta`:if(c(this,q,`m`,X).call(this,`messageDelta`,e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type===`text`&&n.text){let e=n.text,r=t.content[n.index];if(r&&r.type===`text`)c(this,q,`m`,X).call(this,`textDelta`,e,r.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(n.index!==c(this,la,`f`)){if(c(this,ua,`f`))switch(c(this,ua,`f`).type){case`text`:c(this,q,`m`,X).call(this,`textDone`,c(this,ua,`f`).text,c(this,J,`f`));break;case`image_file`:c(this,q,`m`,X).call(this,`imageFileDone`,c(this,ua,`f`).image_file,c(this,J,`f`))}s(this,la,n.index,`f`)}s(this,ua,t.content[n.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(c(this,la,`f`)!==void 0){let t=e.data.content[c(this,la,`f`)];if(t)switch(t.type){case`image_file`:c(this,q,`m`,X).call(this,`imageFileDone`,t.image_file,c(this,J,`f`));break;case`text`:c(this,q,`m`,X).call(this,`textDone`,t.text,c(this,J,`f`))}}c(this,J,`f`)&&c(this,q,`m`,X).call(this,`messageDone`,e.data),s(this,la,void 0,`f`),s(this,ua,void 0,`f`),s(this,J,void 0,`f`)}},va=function(e){let t=c(this,q,`m`,ba).call(this,e);switch(s(this,ma,t,`f`),e.event){case`thread.run.step.created`:s(this,da,void 0,`f`),s(this,Y,void 0,`f`),c(this,q,`m`,X).call(this,`runStepCreated`,e.data);break;case`thread.run.step.delta`:{let n=e.data.delta;if(n.step_details&&n.step_details.type===`tool_calls`&&n.step_details.tool_calls&&t.step_details.type===`tool_calls`)for(let e of n.step_details.tool_calls)e.index===c(this,da,`f`)?c(this,q,`m`,X).call(this,`toolCallDelta`,e,t.step_details.tool_calls[e.index]):(c(this,Y,`f`)&&c(this,q,`m`,X).call(this,`toolCallDone`,c(this,Y,`f`)),s(this,da,e.index,`f`),s(this,Y,t.step_details.tool_calls[e.index],`f`),c(this,Y,`f`)&&c(this,q,`m`,X).call(this,`toolCallCreated`,c(this,Y,`f`)));c(this,q,`m`,X).call(this,`runStepDelta`,e.data.delta,t);break}case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:s(this,ma,void 0,`f`),e.data.step_details.type===`tool_calls`&&c(this,Y,`f`)&&c(this,q,`m`,X).call(this,`toolCallDone`,c(this,Y,`f`)),c(this,q,`m`,X).call(this,`runStepDone`,e.data,t),s(this,da,void 0,`f`),s(this,Y,void 0,`f`)}},X=function(e,...t){if(this._hasListeners(e))for(let e of t)K(e);this._emit(e,...t)},ya=function(e){c(this,aa,`f`).push(e),c(this,q,`m`,X).call(this,`event`,e)},ba=function(e){switch(e.event){case`thread.run.step.created`:return c(this,oa,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:{let t=c(this,oa,`f`)[e.data.id];if(!t)throw Error(`Received a RunStepDelta before creation of a snapshot`);let n=e.data;if(n.delta){let r=ra(t,n.delta,!0);c(this,oa,`f`)[e.data.id]=r}return c(this,oa,`f`)[e.data.id]}case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:case`thread.run.step.in_progress`:c(this,oa,`f`)[e.data.id]=e.data}if(c(this,oa,`f`)[e.data.id])return c(this,oa,`f`)[e.data.id];throw Error(`No snapshot available`)},xa=function(e,t){let n=[];switch(e.event){case`thread.message.created`:return[e.data,n];case`thread.message.delta`:{if(!t)throw Error(`Received a delta with no existing snapshot (there should be one from message creation)`);let r=e.data;if(r.delta.content){na(r.delta);let e=!Zi(t),i=ia(t.content,r.delta.content,`content`,e);for(let i of r.delta.content)if(pe(t.content,i.index)){let n=t.content[i.index];t.content[i.index]=c(this,q,`m`,Sa).call(this,i,n,e)}else Qi(t.content,i.index,i),n.push(i);i()}return[t,n]}case`thread.message.in_progress`:case`thread.message.completed`:case`thread.message.incomplete`:if(t)return[t,n];throw Error(`Received thread message event with no existing snapshot`)}throw Error(`Tried to accumulate a non-message event`)},Sa=function(e,t,n){return ra(t,e,n)},Ca=function(e){switch(s(this,pa,e.data,`f`),e.event){case`thread.run.created`:break;case`thread.run.queued`:break;case`thread.run.in_progress`:break;case`thread.run.requires_action`:case`thread.run.cancelled`:case`thread.run.failed`:case`thread.run.completed`:case`thread.run.expired`:case`thread.run.incomplete`:s(this,ca,e.data,`f`),c(this,Y,`f`)&&c(this,q,`m`,X).call(this,`toolCallDone`,c(this,Y,`f`)),s(this,da,void 0,`f`),s(this,Y,void 0,`f`)}};var Ta=class extends I{constructor(){super(...arguments),this.steps=new Fi(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(L`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(L`/threads/${r}/runs/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(L`/threads/${r}/runs/${e}`,{body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/threads/${e}/runs`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(L`/threads/${r}/runs/${e}/cancel`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return wa.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=P([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...r}}).withResponse();switch(i.status){case`queued`:case`in_progress`:case`cancelling`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await ge(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return wa.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(L`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,n){let r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return wa.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};Ta.Steps=Fi;var Ea=class extends I{constructor(){super(...arguments),this.runs=new Ta(this._client),this.messages=new Pi(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(L`/threads/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(L`/threads/${e}`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/threads/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return wa.createThreadAssistantStream(e,this._client.beta.threads,t)}};Ea.Runs=Ta,Ea.Messages=Pi;var Da=class extends I{constructor(){super(...arguments),this.realtime=new Di(this._client),this.responses=new Ni(this._client),this.chatkit=new Ai(this._client),this.assistants=new wi(this._client),this.threads=new Ea(this._client)}};Da.Realtime=Di,Da.Responses=Ni,Da.ChatKit=Ai,Da.Assistants=wi,Da.Threads=Ea;var Oa=class extends I{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},ka=class extends I{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(L`/containers/${r}/files/${e}/content`,{...n,headers:P([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},Aa=class extends I{constructor(){super(...arguments),this.content=new ka(this._client)}create(e,t,n){return this._client.post(L`/containers/${e}/files`,Gt({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(L`/containers/${r}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/containers/${e}/files`,M,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(L`/containers/${r}/files/${e}`,{...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}};Aa.Content=ka;var ja=class extends I{constructor(){super(...arguments),this.files=new Aa(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(L`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/containers`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/containers/${e}`,{...t,headers:P([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}};ja.Files=Aa;var Ma=class extends I{create(e,t){return this._client.post(`/content_provenance_checks`,F({body:e,...t,__security:{bearerAuth:!0}},this._client))}},Na=class extends I{create(e,t,n){let{include:r,...i}=t;return this._client.post(L`/conversations/${e}/items`,{query:{include:r},body:i,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(L`/conversations/${r}/items/${e}`,{query:i,...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/conversations/${e}/items`,N,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(L`/conversations/${r}/items/${e}`,{...n,__security:{bearerAuth:!0}})}},Pa=class extends I{constructor(){super(...arguments),this.items=new Na(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(L`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(L`/conversations/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};Pa.Items=Na;var Fa=class extends I{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&k(this._client).debug(`embeddings/user defined encoding_format:`,e.encoding_format);let i=this._client.post(`/embeddings`,{body:{...e,encoding_format:r},...t,__security:{bearerAuth:!0}});return n?i:(k(this._client).debug(`embeddings/decoding base64 embeddings from base64`),i._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{let t=e.embedding;e.embedding=Li(t)}),e)))}},Ia=class extends I{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(L`/evals/${r}/runs/${i}/output_items/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(L`/evals/${r}/runs/${e}/output_items`,M,{query:i,...n,__security:{bearerAuth:!0}})}},La=class extends I{constructor(){super(...arguments),this.outputItems=new Ia(this._client)}create(e,t,n){return this._client.post(L`/evals/${e}/runs`,{body:t,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(L`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/evals/${e}/runs`,M,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(L`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(L`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};La.OutputItems=Ia;var Ra=class extends I{constructor(){super(...arguments),this.runs=new La(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(L`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(L`/evals/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/evals`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};Ra.Runs=La;var za=class extends I{create(e,t){return this._client.post(`/files`,F({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(L`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/files`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(L`/files/${e}/content`,{...t,headers:P([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=18e5}={}){let r=new Set([`processed`,`error`,`deleted`]),i=Date.now(),a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await ge(t),a=await this.retrieve(e),Date.now()-i>n)throw new g({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}},Ba=class extends I{},Va=class extends I{run(e,t){return this._client.post(`/fine_tuning/alpha/graders/run`,{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post(`/fine_tuning/alpha/graders/validate`,{body:e,...t,__security:{bearerAuth:!0}})}},Ha=class extends I{constructor(){super(...arguments),this.graders=new Va(this._client)}};Ha.Graders=Va;var Ua=class extends I{create(e,t,n){return this._client.getAPIList(L`/fine_tuning/checkpoints/${e}/permissions`,kt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(L`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/fine_tuning/checkpoints/${e}/permissions`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(L`/fine_tuning/checkpoints/${r}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Wa=class extends I{constructor(){super(...arguments),this.permissions=new Ua(this._client)}};Wa.Permissions=Ua;var Ga=class extends I{list(e,t={},n){return this._client.getAPIList(L`/fine_tuning/jobs/${e}/checkpoints`,M,{query:t,...n,__security:{bearerAuth:!0}})}},Ka=class extends I{constructor(){super(...arguments),this.checkpoints=new Ga(this._client)}create(e,t){return this._client.post(`/fine_tuning/jobs`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(L`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,M,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(L`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},n){return this._client.getAPIList(L`/fine_tuning/jobs/${e}/events`,M,{query:t,...n,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(L`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(L`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}};Ka.Checkpoints=Ga;var qa=class extends I{constructor(){super(...arguments),this.methods=new Ba(this._client),this.jobs=new Ka(this._client),this.checkpoints=new Wa(this._client),this.alpha=new Ha(this._client)}};qa.Methods=Ba,qa.Jobs=Ka,qa.Checkpoints=Wa,qa.Alpha=Ha;var Ja=class extends I{},Ya=class extends I{constructor(){super(...arguments),this.graderModels=new Ja(this._client)}};Ya.GraderModels=Ja;var Xa=class extends I{createVariation(e,t){return this._client.post(`/images/variations`,F({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post(`/images/edits`,F({body:e,...t,stream:e.stream??!1,__metadata:{...t?.__metadata,...e.model==null?{}:{model:e.model}},__security:{bearerAuth:!0}},this._client))}generate(e,t){return this._client.post(`/images/generations`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},Za=class extends I{retrieve(e,t){return this._client.get(L`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList(`/models`,kt,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/models/${e}`,{...t,__security:{bearerAuth:!0}})}},Qa=class extends I{create(e,t){return this._client.post(`/moderations`,{body:e,...t,__security:{bearerAuth:!0}})}},$a=class extends I{accept(e,t,n){return this._client.post(L`/realtime/calls/${e}/accept`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(L`/realtime/calls/${e}/hangup`,{...t,headers:P([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(L`/realtime/calls/${e}/refer`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},n){return this._client.post(L`/realtime/calls/${e}/reject`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}},eo=class extends I{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t,__security:{bearerAuth:!0}})}},to=class extends I{constructor(){super(...arguments),this.clientSecrets=new eo(this._client),this.calls=new $a(this._client)}};to.ClientSecrets=eo,to.Calls=$a;function no(e,t){if(!t||!ao(t)){let t={...e,output_parsed:null,output:e.output.map(e=>e.type===`function_call`?{...e,parsed_arguments:null}:e.type===`message`?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)};return lo(e,t)&&uo(t),t}return ro(e,t)}function ro(e,t){let n=!e.status||e.status===`completed`,r=e.output.map(e=>{if(e.type===`function_call`)return n?co(t,e):{...e,parsed_arguments:null};if(e.type===`message`){let r=e.content.map(e=>e.type===`output_text`?{...e,parsed:n?io(t,e.text):null}:e);return{...e,content:r}}return e}),i={...e,output:r};return lo(e,i)&&uo(i),Object.defineProperty(i,"output_parsed",{enumerable:!0,get(){for(let e of i.output)if(e.type===`message`){for(let t of e.content)if(t.type===`output_text`&&t.parsed!==null)return t.parsed}return null}}),i}function io(e,t){return Dn(e.text?.format,t)}function ao(e){return En(e.text?.format)?!0:Array.isArray(e.tools)&&e.tools.some(e=>oo(e)||e.type===`function`&&e.strict===!0)}function oo(e){return e?.$brand===`auto-parseable-tool`}function so(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function co(e,t){let n=so(e.tools??[],t.name),r=null;return oo(n)?r=n.$parseRaw(t.arguments):n?.strict&&(r=JSON.parse(t.arguments)),{...t,parsed_arguments:r}}function lo(e,t){return!Object.getOwnPropertyDescriptor(e,`output_text`)||t.output_text==null}function uo(e){let t=[];for(let n of e.output)if(n.type===`message`)for(let e of n.content)e.type===`output_text`&&t.push(e.text);e.output_text=t.join(``)}var fo=class{constructor(){this.capacity=1,this.values=[0,0],this.size=0}get length(){return this.size}append(e){this.size===this.capacity&&this.grow();let t=this.size;this.size+=1,this.update(t,e)}update(e,t){if(!Number.isSafeInteger(e)||e<0||e>=this.size)throw RangeError(`missing output at index ${e}`);let n=this.capacity+e,r=t-(this.values[n]??0);if(r!==0)for(;n>=1;)this.values[n]=(this.values[n]??0)+r,n=Math.floor(n/2)}prefixSum(e){if(!Number.isSafeInteger(e)||e<0||e>this.size)throw RangeError(`missing output at index ${e}`);let t=this.capacity,n=this.capacity+e,r=0;for(;t<n;)t%2==1&&(r+=this.values[t]??0,t+=1),n%2==1&&(--n,r+=this.values[n]??0),t=Math.floor(t/2),n=Math.floor(n/2);return r}grow(){let e=this.capacity;this.capacity*=2;let t=Array.from({length:this.capacity*2},()=>0);for(let n=0;n<this.size;n+=1)t[this.capacity+n]=this.values[e+n]??0;for(let e=this.capacity-1;e>0;--e)t[e]=(t[e*2]??0)+(t[e*2+1]??0);this.values=t}};function po(){return{canonicalSnapshot:void 0,outputTextLengths:new WeakMap,outputTextIndex:new fo}}function mo(e,t){if(t.type!==`message`)return``;let n=``;for(let e of t.content)e.type===`output_text`&&(n+=e.text);return e.outputTextLengths.set(t,n.length),n}function ho(e,t){if(e.canonicalSnapshot===t)return;let n=new fo,r=``;for(let i of t.output){let t=mo(e,i);r+=t,n.append(t.length)}t.output_text!==r&&(t.output_text=r),e.outputTextIndex=n,e.canonicalSnapshot=t}function go(e,t){e.canonicalSnapshot=void 0,e.outputTextLengths=new WeakMap,e.outputTextIndex=new fo;let n=structuredClone(t);return!Object.getOwnPropertyDescriptor(n,`output_text`)||n.output_text===null||n.output_text===void 0?ho(e,n):n.output.length===0&&n.output_text===``&&(e.canonicalSnapshot=n),n}function _o(e,t,n,r,i){let a=e.outputTextLengths.get(t);if(a!==void 0){let o=a-r.length+i.length;e.outputTextLengths.set(t,o),e.outputTextIndex.update(n,o)}}function vo(e,t,n){if(t.length===0){e.output_text+=n;return}e.output_text=e.output_text.slice(0,e.output_text.length-t.length)+n}function yo(e,t,n,r){if(n===void 0||t?.type!==`message`)return 0;if(n<t.content.length-n-1){let e=0;for(let r=0;r<n;r+=1){let n=t.content[r];n?.type===`output_text`&&(e+=n.text.length)}return e}let i=0;for(let e=n+1;e<t.content.length;e+=1){let n=t.content[e];n?.type===`output_text`&&(i+=n.text.length)}return(e.outputTextLengths.get(t)??mo(e,t).length)-i-r.length}function bo(e,t,n,r,i,a){if(r===i)return;let o=t.output[n];if(n===t.output.length-1&&(a===void 0||o?.type===`message`&&a===o.content.length-1)){vo(t,r,i);return}let s=yo(e,o,a,i),c=e.outputTextIndex.prefixSum(n)+s;if(c+r.length===t.output_text.length){vo(t,r,i);return}t.output_text=t.output_text.slice(0,c)+i+t.output_text.slice(c+r.length)}function xo(e,t,n,r=!1){if(!Number.isSafeInteger(t)||t<0||t>e.length||(t===e.length?!r||t in e:!pe(e,t)))throw new f(`missing ${n} at index ${t}`)}function So(e,t,n){if(t!==e.length)throw new f(`missing ${n} at index ${t}`);xo(e,t,n,!0)}function Z(e,t){xo(e.output,t,`output`);let n=e.output[t];if(!n)throw new f(`missing output at index ${t}`);return n}function Q(e,t){xo(e,t,`content`);let n=e[t];if(!n)throw new f(`missing content at index ${t}`);return n}function Co(e,t,n){let r=e.output.find(e=>e.type===`shell_call`&&e.call_id===t.call_id);for(r?xo(r.action.commands,n,`command`):xo(t.output,n,`content`,!0);t.output.length<=n;)t.output.push({stdout:``,stderr:``,outcome:{type:`exit`,exit_code:0}});return Q(t.output,n)}function wo(e){throw new f(`Unhandled response stream event: ${JSON.stringify(e)}`)}function To(e,t,n){switch(e.type){case`response.output_item.added`:{So(t.output,e.output_index,`output`);let r=structuredClone(e.item);r.type===`message`&&ho(n,t),t.output.push(r);let i=mo(n,r);return n.canonicalSnapshot===t&&n.outputTextIndex.append(i.length),i&&(t.output_text+=i),!0}case`response.output_item.done`:{let r=Z(t,e.output_index),i=mo(n,r),a=structuredClone(e.item);(r.type===`message`||a.type===`message`)&&ho(n,t),t.output[e.output_index]=a;let o=mo(n,a);return n.canonicalSnapshot===t&&n.outputTextIndex.update(e.output_index,o.length),bo(n,t,e.output_index,i,o),!0}default:return!1}}function Eo(e,t,n){switch(e.type){case`response.content_part.added`:{let r=Z(t,e.output_index),{type:i}=r,{part:a}=e;if(i===`message`&&a.type!==`reasoning_text`){So(r.content,e.content_index,`content`);let i=structuredClone(a);i.type===`output_text`&&ho(n,t),r.content.push(i),i.type===`output_text`&&(_o(n,r,e.output_index,``,i.text),bo(n,t,e.output_index,``,i.text,e.content_index))}else if(i===`reasoning`&&a.type===`reasoning_text`){let t=r.content??[];So(t,e.content_index,`content`),r.content||=t,t.push(structuredClone(a))}return!0}default:return!1}}function Do(e,t,n){switch(e.type){case`response.content_part.done`:{let r=Z(t,e.output_index),{part:i}=e;if(r.type===`message`&&i.type!==`reasoning_text`){let a=Q(r.content,e.content_index),o=a.type===`output_text`?a.text:``,s=structuredClone(i);(a.type===`output_text`||s.type===`output_text`)&&ho(n,t),r.content[e.content_index]=s;let c=s.type===`output_text`?s.text:``;_o(n,r,e.output_index,o,c),bo(n,t,e.output_index,o,c,e.content_index)}else if(r.type===`reasoning`&&i.type===`reasoning_text`){let{content:t}=r;if(!t)throw new f(`missing content at index ${e.content_index}`);Q(t,e.content_index),t[e.content_index]=structuredClone(i)}return!0}default:return!1}}function Oo(e,t,n){switch(e.type){case`response.output_text.delta`:{let r=Z(t,e.output_index);if(r.type===`message`){let i=Q(r.content,e.content_index);if(i.type!==`output_text`)throw new f(`expected content to be 'output_text', got ${i.type}`);let a=i.text;ho(n,t),i.text=a+e.delta,_o(n,r,e.output_index,a,i.text),e.output_index===t.output.length-1&&e.content_index===r.content.length-1?t.output_text+=e.delta:bo(n,t,e.output_index,a,i.text,e.content_index)}return!0}case`response.output_text.done`:{let r=Z(t,e.output_index);if(r.type===`message`){let i=Q(r.content,e.content_index);if(i.type!==`output_text`)throw new f(`expected content to be 'output_text', got ${i.type}`);let a=i.text;ho(n,t),i.text=e.text,_o(n,r,e.output_index,a,e.text),bo(n,t,e.output_index,a,e.text,e.content_index)}return!0}case`response.output_text.annotation.added`:{let n=Z(t,e.output_index);if(n.type===`message`){let t=Q(n.content,e.content_index);if(t.type!==`output_text`)throw new f(`expected content to be 'output_text', got ${t.type}`);xo(t.annotations,e.annotation_index,`annotation`,!0),t.annotations[e.annotation_index]=structuredClone(e.annotation)}return!0}default:return!1}}function ko(e,t){switch(e.type){case`response.refusal.delta`:{let n=Z(t,e.output_index);if(n.type===`message`){let t=Q(n.content,e.content_index);if(t.type!==`refusal`)throw new f(`expected content to be 'refusal', got ${t.type}`);t.refusal+=e.delta}return!0}case`response.refusal.done`:{let n=Z(t,e.output_index);if(n.type===`message`){let t=Q(n.content,e.content_index);if(t.type!==`refusal`)throw new f(`expected content to be 'refusal', got ${t.type}`);t.refusal=e.refusal}return!0}case`response.function_call_arguments.delta`:{let n=Z(t,e.output_index);return n.type===`function_call`&&(n.arguments+=e.delta),!0}case`response.function_call_arguments.done`:{let n=Z(t,e.output_index);return n.type===`function_call`&&(n.arguments=e.arguments),!0}case`response.custom_tool_call_input.delta`:{let n=Z(t,e.output_index);return n.type===`custom_tool_call`&&(n.input+=e.delta),!0}case`response.custom_tool_call_input.done`:{let n=Z(t,e.output_index);return n.type===`custom_tool_call`&&(n.input=e.input),!0}case`response.mcp_call_arguments.delta`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.arguments+=e.delta),!0}case`response.mcp_call_arguments.done`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.arguments=e.arguments),!0}default:return!1}}function Ao(e,t){switch(e.type){case`response.shell_call_command.added`:case`response.shell_call_command.done`:{let n=Z(t,e.output_index);if(n.type===`shell_call`){let t=e.type===`response.shell_call_command.added`;xo(n.action.commands,e.command_index,`command`,t),n.action.commands[e.command_index]=e.command}return!0}case`response.shell_call_command.delta`:{let n=Z(t,e.output_index);return n.type===`shell_call`&&(xo(n.action.commands,e.command_index,`command`),n.action.commands[e.command_index]+=e.delta),!0}case`response.shell_call_output_content.delta`:{let n=Z(t,e.output_index);if(n.type===`shell_call_output`){let r=Co(t,n,e.command_index);r.stdout+=e.delta.stdout??``,r.stderr+=e.delta.stderr??``}return!0}case`response.shell_call_output_content.done`:{let n=Z(t,e.output_index);if(n.type===`shell_call_output`){let r=Q(e.output,0);Co(t,n,e.command_index),n.output[e.command_index]=structuredClone(r)}return!0}default:return!1}}function jo(e,t){switch(e.type){case`response.reasoning_text.delta`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new f(`missing content at index ${e.content_index}`);let t=Q(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new f(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}return!0}case`response.reasoning_text.done`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new f(`missing content at index ${e.content_index}`);let t=Q(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new f(`expected content to be 'reasoning_text', got ${t.type}`);t.text=e.text}return!0}case`response.reasoning_summary_part.added`:{let n=Z(t,e.output_index);return n.type===`reasoning`&&(So(n.summary,e.summary_index,`content`),n.summary.push(structuredClone(e.part))),!0}case`response.reasoning_summary_part.done`:{let n=Z(t,e.output_index);return n.type===`reasoning`&&(Q(n.summary,e.summary_index),n.summary[e.summary_index]=structuredClone(e.part)),!0}case`response.reasoning_summary_text.delta`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){let t=Q(n.summary,e.summary_index);t.text+=e.delta}return!0}case`response.reasoning_summary_text.done`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){let t=Q(n.summary,e.summary_index);t.text=e.text}return!0}default:return!1}}function Mo(e,t){switch(e.type){case`response.code_interpreter_call_code.delta`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.code=(n.code??``)+e.delta),!0}case`response.code_interpreter_call_code.done`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.code=e.code),!0}case`response.code_interpreter_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.status=`in_progress`),!0}case`response.code_interpreter_call.interpreting`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.status=`interpreting`),!0}case`response.code_interpreter_call.completed`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.status=`completed`),!0}default:return!1}}function No(e,t){switch(e.type){case`response.file_search_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`file_search_call`&&(n.status=`in_progress`),!0}case`response.file_search_call.searching`:{let n=Z(t,e.output_index);return n.type===`file_search_call`&&(n.status=`searching`),!0}case`response.file_search_call.completed`:{let n=Z(t,e.output_index);return n.type===`file_search_call`&&(n.status=`completed`),!0}case`response.web_search_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`web_search_call`&&(n.status=`in_progress`),!0}case`response.web_search_call.searching`:{let n=Z(t,e.output_index);return n.type===`web_search_call`&&(n.status=`searching`),!0}case`response.web_search_call.completed`:{let n=Z(t,e.output_index);return n.type===`web_search_call`&&(n.status=`completed`),!0}default:return!1}}function Po(e,t){switch(e.type){case`response.image_generation_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`image_generation_call`&&(n.status=`in_progress`),!0}case`response.image_generation_call.generating`:{let n=Z(t,e.output_index);return n.type===`image_generation_call`&&(n.status=`generating`),!0}case`response.image_generation_call.completed`:{let n=Z(t,e.output_index);return n.type===`image_generation_call`&&(n.status=`completed`),!0}case`response.mcp_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.status=`in_progress`),!0}case`response.mcp_call.completed`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.status=`completed`),!0}case`response.mcp_call.failed`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.status=`failed`),!0}default:return!1}}function Fo(e){switch(e.type){case`response.created`:case`response.queued`:case`response.in_progress`:case`response.completed`:case`response.failed`:case`response.incomplete`:return!0;default:return!1}}function Io(e){switch(e.type){case`response.audio.delta`:case`response.audio.done`:case`response.audio.transcript.delta`:case`response.audio.transcript.done`:case`response.image_generation_call.partial_image`:case`response.mcp_list_tools.in_progress`:case`response.mcp_list_tools.completed`:case`response.mcp_list_tools.failed`:case`keepalive`:case`error`:return!0;default:return!1}}function Lo(){return po()}function Ro(e,t,n){if(!t){if(e.type!==`response.created`)throw new f(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return go(n,e.response)}return To(e,t,n)||Eo(e,t,n)||Do(e,t,n)||Oo(e,t,n)||ko(e,t)||Ao(e,t)||jo(e,t)||Mo(e,t)||No(e,t)||Po(e,t)?t:Fo(e)?go(n,e.response):Io(e)?t:wo(e)}var zo,Bo,Vo,Ho,Uo,Wo,Go,Ko,qo=class e extends er{constructor(e){super(),zo.add(this),Bo.set(this,void 0),Vo.set(this,void 0),Ho.set(this,void 0),Uo.set(this,Lo()),s(this,Bo,e,`f`)}static createResponse(t,n,r){let i=new e(n);return i._run(()=>i._createOrRetrieveResponse(t,n,{...r,__metadata:{...r?.__metadata,helperMethod:`stream`}})),i}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}async _createOrRetrieveResponse(e,t,n){this._listenForAbort(n?.signal),c(this,zo,`m`,Wo).call(this);let r,i=null;`response_id`in t?(r=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):r=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let e of r)c(this,zo,`m`,Go).call(this,e,i);if(r.controller.signal?.aborted)throw new m;return c(this,zo,`m`,Ko).call(this)}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),c(this,zo,`m`,Wo).call(this),this._connected();let n=Ve.fromReadableStream(e,this.controller);for await(let e of n)c(this,zo,`m`,Go).call(this,e,null);if(n.controller.signal?.aborted)throw new m;return c(this,zo,`m`,Ko).call(this)}[(Bo=new WeakMap,Vo=new WeakMap,Ho=new WeakMap,Uo=new WeakMap,zo=new WeakSet,Wo=function(){this.ended||(s(this,Vo,void 0,`f`),s(this,Uo,Lo(),`f`))},Go=function(e,t){if(this.ended)return;let n=(e,n)=>{(t==null||n.sequence_number>t)&&this._emit(e,n)};if(e.type===`error`)throw new p(void 0,`error`in e&&typeof e.error==`object`&&e.error!==null?e.error:e,e.message,void 0);let r=Ro(e,c(this,Vo,`f`),c(this,Uo,`f`));switch(s(this,Vo,r,`f`),n(`event`,e),e.type){case`response.output_text.delta`:{let t=r.output[e.output_index];if(!t)throw new f(`missing output at index ${e.output_index}`);if(t.type===`message`){let r=t.content[e.content_index];if(!r)throw new f(`missing content at index ${e.content_index}`);if(r.type!==`output_text`)throw new f(`expected content to be 'output_text', got ${r.type}`);n(`response.output_text.delta`,{...e,snapshot:r.text})}break}case`response.function_call_arguments.delta`:{let t=r.output[e.output_index];if(!t)throw new f(`missing output at index ${e.output_index}`);t.type===`function_call`&&n(`response.function_call_arguments.delta`,{...e,snapshot:t.arguments});break}default:n(e.type,e)}},Ko=function(){if(this.ended)throw new f(`stream has ended, this shouldn't happen`);let e=c(this,Vo,`f`);if(!e)throw new f(`request ended without sending any events`);s(this,Vo,void 0,`f`),s(this,Uo,Lo(),`f`);let t=Jo(e,c(this,Bo,`f`));return s(this,Ho,t,`f`),t},Symbol.asyncIterator)](){return this._createIterator(e=>{let t=t=>e(t);return this.on(`event`,t),()=>this.off(`event`,t)},{onReturn:()=>this.abort()})}async finalResponse(){await this.done();let e=c(this,Ho,`f`);if(!e)throw new f(`stream ended without producing a Response`);return e}};function Jo(e,t){return no(e,t)}var Yo=class extends I{list(e,t={},n){return this._client.getAPIList(L`/responses/${e}/input_items`,M,{query:t,...n,__security:{bearerAuth:!0}})}},Xo=class extends I{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t,__security:{bearerAuth:!0}})}},Zo=class extends I{constructor(){super(...arguments),this.inputItems=new Yo(this._client),this.inputTokens=new Xo(this._client)}create(e,t){return this._client.post(`/responses`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&uo(e),e))}retrieve(e,t={},n){return this._client.get(L`/responses/${e}`,{query:t,...n,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&uo(e),e))}delete(e,t){return this._client.delete(L`/responses/${e}`,{...t,headers:P([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>ro(t,e))}stream(e,t){return qo.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(L`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t,__security:{bearerAuth:!0}})}};Zo.InputItems=Yo,Zo.InputTokens=Xo;var Qo=class extends I{retrieve(e,t){return this._client.get(L`/skills/${e}/content`,{...t,headers:P([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},$o=class extends I{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(L`/skills/${r}/versions/${e}/content`,{...n,headers:P([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},es=class extends I{constructor(){super(...arguments),this.content=new $o(this._client)}create(e,t={},n){return this._client.post(L`/skills/${e}/versions`,Gt({body:t,...n,__security:{bearerAuth:!0}},this._client,{stripFilenames:!1}))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(L`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/skills/${e}/versions`,M,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(L`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};es.Content=$o;var ts=class extends I{constructor(){super(...arguments),this.content=new Qo(this._client),this.versions=new es(this._client)}create(e={},t){return this._client.post(`/skills`,Gt({body:e,...t,__security:{bearerAuth:!0}},this._client,{stripFilenames:!1}))}retrieve(e,t){return this._client.get(L`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(L`/skills/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/skills`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};ts.Content=Qo,ts.Versions=es;var ns=class extends I{create(e,t,n){return this._client.post(L`/uploads/${e}/parts`,F({body:t,...n,__security:{bearerAuth:!0}},this._client))}},rs=class extends I{constructor(){super(...arguments),this.parts=new ns(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(L`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,n){return this._client.post(L`/uploads/${e}/complete`,{body:t,...n,__security:{bearerAuth:!0}})}};rs.Parts=ns;var is=async e=>{let t=await Promise.allSettled(e),n=t.filter(e=>e.status===`rejected`);if(n.length){for(let e of n)console.error(e.reason);throw Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let e of t)e.status===`fulfilled`&&r.push(e.value);return r},as=class extends I{create(e,t,n){return this._client.post(L`/vector_stores/${e}/file_batches`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(L`/vector_stores/${r}/file_batches/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(L`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(L`/vector_stores/${r}/file_batches/${e}/files`,M,{query:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,n){let r=P([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse();switch(i.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await ge(e);break;case`failed`:case`cancelled`:case`completed`:return i}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=r?.maxConcurrency??5,a=Math.min(i,t.length),o=this._client,s=t.values(),c=[...n];async function l(e){for(let t of e){let e=await o.files.create({file:t,purpose:`assistants`},r);c.push(e.id)}}return await is(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c},r)}},os=class extends I{create(e,t,n){return this._client.post(L`/vector_stores/${e}/files`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(L`/vector_stores/${r}/files/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(L`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/vector_stores/${e}/files`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(L`/vector_stores/${r}/files/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){let r=P([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let i=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse(),a=i.data;switch(a.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=i.response.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await ge(e);break;case`failed`:case`completed`:return a}}}async upload(e,t,n){let r=await this._client.files.create({file:t,purpose:`assistants`},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){let r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){let{vector_store_id:r}=t;return this._client.getAPIList(L`/vector_stores/${r}/files/${e}/content`,kt,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},ss=class extends I{constructor(){super(...arguments),this.files=new os(this._client),this.fileBatches=new as(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(L`/vector_stores/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(L`/vector_stores/${e}`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/vector_stores`,M,{query:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/vector_stores/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,n){return this._client.getAPIList(L`/vector_stores/${e}/search`,kt,{body:t,method:`post`,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}};ss.Files=os,ss.FileBatches=as;var cs=class extends I{create(e,t){return this._client.post(`/videos`,F({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(L`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/videos`,N,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post(`/videos/characters`,F({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},n){return this._client.get(L`/videos/${e}/content`,{query:t,...n,headers:P([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post(`/videos/edits`,F({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post(`/videos/extensions`,F({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(L`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,n){return this._client.post(L`/videos/${e}/remix`,Gt({body:t,...n,__security:{bearerAuth:!0}},this._client))}},ls,us,ds,fs=class extends I{constructor(){super(...arguments),ls.add(this)}async unwrap(e,t,n=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,n,r),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,r=300){if(typeof crypto>`u`||typeof crypto.subtle.importKey!=`function`||typeof crypto.subtle.verify!=`function`)throw Error("Webhook signature verification is only supported when the `crypto` global is defined");c(this,ls,`m`,us).call(this,n);let i=P([t]).values,a=c(this,ls,`m`,ds).call(this,i,`webhook-signature`),o=c(this,ls,`m`,ds).call(this,i,`webhook-timestamp`),s=c(this,ls,`m`,ds).call(this,i,`webhook-id`),l=parseInt(o,10);if(isNaN(l))throw new ae(`Invalid webhook timestamp format`);let u=Math.floor(Date.now()/1e3);if(u-l>r)throw new ae(`Webhook timestamp is too old`);if(l>u+r)throw new ae(`Webhook timestamp is too new`);let d=a.split(` `).map(e=>e.startsWith(`v1,`)?e.substring(3):e),f=Uint8Array.from(n.startsWith(`whsec_`)?Ii(n.slice(6)):w(n)),p=s?`${s}.${o}.${e}`:`${o}.${e}`,m=Uint8Array.from(w(p)),h=await crypto.subtle.importKey(`raw`,f,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);for(let e of d)try{let t=Uint8Array.from(Ii(e));if(await crypto.subtle.verify(`HMAC`,h,t,m))return}catch{continue}throw new ae(`The given webhook signature does not match the expected signature`)}};ls=new WeakSet,us=function(e){if(typeof e!=`string`||e.length===0)throw Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`)},ds=function(e,t){if(!e)throw Error(`Headers are required`);let n=e.get(t);if(n==null)throw Error(`Missing required header: ${t}`);return n};var ps=Symbol.for(`openai.node.providerDefinitions.v1`),ms=globalThis,hs=ms[ps],gs=hs??new WeakMap;hs||Object.defineProperty(ms,ps,{value:gs});function _s(e){let t=gs.get(e);if(!t)throw Error(`Invalid provider. Providers must be created with createProvider().`);return t.configure()}var vs,ys,bs,xs,Ss;function Cs(){if(Ze())return!0;let e=globalThis;return typeof e.WorkerGlobalScope==`function`&&e instanceof e.WorkerGlobalScope&&typeof e.WorkerNavigator==`function`&&e.navigator instanceof e.WorkerNavigator&&typeof e.navigator?.userAgent==`string`&&e.navigator.userAgent!==`Cloudflare-Workers`&&e.process?.versions?.node===void 0&&e.Deno===void 0&&e.Bun===void 0&&e.EdgeRuntime===void 0&&e.WebSocketPair===void 0}var ws=`workload-identity-auth`,$=class{constructor(e={}){vs.add(this),bs.set(this,void 0),xs.set(this,new WeakMap),this.completions=new Oa(this),this.chat=new Hr(this),this.embeddings=new Fa(this),this.files=new za(this),this.images=new Xa(this),this.contentProvenanceChecks=new Ma(this),this.audio=new Si(this),this.moderations=new Qa(this),this.models=new Za(this),this.fineTuning=new qa(this),this.graders=new Ya(this),this.vectorStores=new ss(this),this.webhooks=new fs(this),this.beta=new Da(this),this.batches=new Ci(this),this.uploads=new rs(this),this.admin=new vi(this),this.responses=new Zo(this),this.realtime=new to(this),this.conversations=new Pa(this),this.evals=new Ra(this),this.containers=new ja(this),this.skills=new ts(this),this.videos=new cs(this);let t=e.provider;if(t){let t=[`apiKey`,`adminAPIKey`,`workloadIdentity`,`baseURL`].filter(t=>e[t]!=null);if(t.length)throw new f(`The \`provider\` option cannot be used with ${t.map(e=>`\`${e}\``).join(`, `)}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:n=t?null:G(`OPENAI_BASE_URL`),apiKey:r=t?null:G(`OPENAI_API_KEY`)??null,adminAPIKey:i=t?null:G(`OPENAI_ADMIN_KEY`)??null,organization:a=t?null:G(`OPENAI_ORG_ID`)??null,project:o=t?null:G(`OPENAI_PROJECT_ID`)??null,webhookSecret:c=G(`OPENAI_WEBHOOK_SECRET`)??null,workloadIdentity:l,...u}=e,d=t?_s(t):void 0,p={apiKey:r,adminAPIKey:i,organization:a,project:o,webhookSecret:c,workloadIdentity:l,provider:t,...u,baseURL:d?.baseURL??(n||`https://api.openai.com/v1`)};if(r&&l)throw new f("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!d&&!r&&!i&&!l)throw new f("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!p.dangerouslyAllowBrowser&&Cs())throw new f(`It looks like you're running in a browser-like environment.
|
|
9
|
+
|
|
10
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
11
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
12
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
13
|
+
|
|
14
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
15
|
+
|
|
16
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
17
|
+
`);this.baseURL=p.baseURL,this.timeout=p.timeout??ys.DEFAULT_TIMEOUT,this.logger=p.logger??console;let m=`warn`;this.logLevel=m,this.logLevel=Pe(p.logLevel,`ClientOptions.logLevel`,this)??Pe(G(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??m,this.fetchOptions=p.fetchOptions,this.maxRetries=p.maxRetries??2,this.fetch=p.fetch??_e(),s(this,bs,at,`f`);let h=t?void 0:G(`OPENAI_CUSTOM_HEADERS`);if(h){let e={};for(let t of h.split(`
|
|
18
|
+
`)){let n=t.indexOf(`:`);n>=0&&(e[t.substring(0,n).trim()]=t.substring(n+1).trim())}p.defaultHeaders=P([e,p.defaultHeaders])}this._options=p,this._provider=d,l&&(this._workloadIdentityAuth=new Nt(l,this.fetch)),this.apiKey=typeof r==`string`?r:null,this.adminAPIKey=i,this.organization=a,this.project=o,this.webhookSecret=c}withOptions(e){let t=this._options.provider,n=e.provider??t,r={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return n&&(delete r.apiKey,delete r.adminAPIKey,delete r.workloadIdentity,delete r.baseURL,n!==t&&(delete r.organization,delete r.project,delete r.defaultHeaders)),new this.constructor({...r,...e,provider:n})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get(`authorization`)||e.get(`api-key`))&&!(t.has(`authorization`)||t.has(`api-key`))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw Error(`Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted`)}async authHeaders(e,t={bearerAuth:!0,adminAPIKeyAuth:!0}){return P([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return P([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return P([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return P([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Ct(e)}getUserAgent(){return`${this.constructor.name}/JS ${Xe}`}defaultIdempotencyKey(){return`stainless-node-retry-${l()}`}makeStatusError(e,t,n,r){let i=t&&typeof t==`object`&&t.error==null?{error:t}:t;return p.generate(e,i,n,r)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!=`function`)return!1;let t;try{t=await e()}catch(e){throw e instanceof f?e:new f(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof t!=`string`||!t)throw new f(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,n){let r=!c(this,vs,`m`,Ss).call(this)&&n||this.baseURL,i=le(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!fe(a)||!fe(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){this._provider||(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return this.responsePromise(this.makeRequest(e,t,void 0))}responsePromise(e,t=(e,t)=>this.parseResponseWithTimeout(e,t)){let n=new Tt(this,e,t);return n.withResponse=async()=>{let t=await n,{response:r}=await e;return{data:t,response:r,request_id:r.headers.get(`x-request-id`)}},n._thenUnwrap=n=>this.responsePromise(e,async(e,r)=>Ye(n(await t(e,r),r),r.response)),n}async parseResponseWithTimeout(e,t){if(t.options.stream||t.options.__binaryResponse||t.response.status===204||t.response.headers.get(`content-length`)===`0`)return qe(e,t);for(;;){let n=c(this,xs,`f`).get(t.controller),r=n?.timeout??t.options.timeout??this.timeout,i=Math.max(0,t.startTime+r-Date.now()),a=t.options.signal,o,s,l=!1;try{if(a?.aborted&&t.options.__metadata?.helperMethod!==`runTools`)throw new m;let n=new Promise((e,n)=>{o=setTimeout(()=>{l=!0,t.controller.abort(),n(new g)},i),a&&(s=()=>n(new m),a.addEventListener(`abort`,s,{once:!0}))});return await Promise.race([qe(e,t),n])}catch(e){if(a?.aborted)throw new m;if(!l)throw e;let r=n?.retriesRemaining??0;if(!r||t.options.__metadata?.hasStreamingBody||globalThis.ReadableStream&&t.options.body instanceof globalThis.ReadableStream||typeof t.options.body==`object`&&t.options.body!==null&&(Symbol.asyncIterator in t.options.body||Symbol.iterator in t.options.body&&`next`in t.options.body&&typeof t.options.body.next==`function`))throw new g;o!==void 0&&clearTimeout(o),s&&a?.removeEventListener(`abort`,s),s=void 0;let i=await this.retryRequest(t.options,r,t.retryOfRequestLogID??t.requestLogID);Object.assign(t,i)}finally{o!==void 0&&clearTimeout(o),s&&a?.removeEventListener(`abort`,s)}}}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t}),l=r.__metadata?.hasStreamingBody===!0;await this.prepareRequest(a,{url:o,options:r}),await this._provider?.prepareRequest?.(a,{url:o,options:r});let f=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),p=n===void 0?``:`, retryOf: ${n}`,m=Date.now();if(k(this).debug(`[${f}] sending request`,ze({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted||a.signal?.aborted)throw this._makeUserAbortError(r.signal?.aborted?r.signal:a.signal);let _=r.__security??{bearerAuth:!0},v=this.fetchWithTimeout===ys.prototype.fetchWithTimeout?Es(a.signal):new AbortController,y=await this.fetchWithAuth(o,a,s,v,_).catch(d),b=Date.now();if(y instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted||a.signal?.aborted)throw this._makeUserAbortError(r.signal?.aborted?r.signal:a.signal);let i=u(y)||/timed? ?out/i.test(String(y)+(`cause`in y?String(y.cause):``));if(t&&!l)return k(this).info(`[${f}] connection ${i?`timed out`:`failed`} - ${e}`),k(this).debug(`[${f}] connection ${i?`timed out`:`failed`} (${e})`,ze({retryOfRequestLogID:n,url:o,durationMs:b-m,message:y.message})),this.retryRequest(r,t,n??f);let s=l?`error; streaming body cannot be retried`:`error; no more retries left`;if(k(this).info(`[${f}] connection ${i?`timed out`:`failed`} - ${s}`),k(this).debug(`[${f}] connection ${i?`timed out`:`failed`} (${s})`,ze({retryOfRequestLogID:n,url:o,durationMs:b-m,message:y.message})),y instanceof oe||y instanceof se)throw y;if(i){let e=`cause`in y?y.cause:void 0,t=typeof e==`object`&&e&&`code`in e&&e.code===`UND_ERR_HEADERS_TIMEOUT`?new g({message:`Request timed out. Node.js fetch timed out waiting for response headers; configure a matching undici fetch and fetchOptions.dispatcher with an Agent whose headersTimeout is at least the SDK timeout.`}):new g;throw Object.assign(t,{cause:y})}throw new h({message:Ds(y),cause:y})}let x=`[${f}${p}${[...y.headers.entries()].filter(([e])=>e===`x-request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${y.ok?`succeeded`:`failed`} with status ${y.status} in ${b-m}ms`;if(!y.ok){if(y.status===401&&this._workloadIdentityAuth&&_.bearerAuth&&!r.__metadata?.hasStreamingBody&&!r.__metadata?.workloadIdentityTokenRefreshed)return await xe(y.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...r,__metadata:{...r.__metadata,workloadIdentityTokenRefreshed:!0}},t,n??f);let e=await this.shouldRetry(y);if(t&&e&&!l){let e=`retrying, ${t} attempts remaining`;return await xe(y.body),k(this).info(`${x} - ${e}`),k(this).debug(`[${f}] response error (${e})`,ze({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,durationMs:b-m})),this.retryRequest(r,t,n??f,y.headers)}let i=e?l?`error; streaming body cannot be retried`:`error; no more retries left`:`error; not retryable`;k(this).info(`${x} - ${i}`);let a=await y.text().catch(e=>d(e).message),o=he(a),s=o?void 0:a;throw k(this).debug(`[${f}] response error (${i})`,ze({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,message:s,durationMs:Date.now()-m})),this.makeStatusError(y.status,o,s,y.headers)}return k(this).info(x),k(this).debug(`[${f}] response start`,ze({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,durationMs:b-m})),c(this,xs,`f`).set(v,{timeout:s,retriesRemaining:t}),{response:y,options:r,controller:v,requestLogID:f,retryOfRequestLogID:n,startTime:m}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0),r=new Ot(this,n,e),i=this.responsePromise(n,async(t,n)=>{let r=await this.parseResponseWithTimeout(t,n);return new e(t,n.response,r,n.options)});return r.then=i.then.bind(i),r.catch=i.catch.bind(i),r.finally=i.finally.bind(i),r.withResponse=i.withResponse.bind(i),r._thenUnwrap=i._thenUnwrap.bind(i),r}async fetchWithAuth(e,t,n,r,i={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&i.bearerAuth){let e=t.headers,n=e.get(`Authorization`);if(!n||n===`Bearer ${ws}`){let t=await this._workloadIdentityAuth.getToken();e.set(`Authorization`,`Bearer ${t}`)}}return await this.fetchWithTimeout(e,t,n,r)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r),c=!!i&&Ts.get(r)===i;i&&!c&&i.addEventListener(`abort`,s,{once:!0});let l=setTimeout(s,n),u=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,d={signal:r.signal,...u?{duplex:`half`}:{},method:`GET`,...o};a&&(d.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,d)}catch(e){throw i&&!c&&i.removeEventListener(`abort`,s),e}finally{clearTimeout(l)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&i===void 0){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0||!Number.isFinite(i)||i<0||i>6e4){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await ge(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&me(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l,isStreamingBody:u}=this.buildBody({options:n});return u&&(e.__metadata={...e.__metadata,hasStreamingBody:!0}),{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=e.__metadata?.helperMethod,o=P([i,{Accept:`application/json`,...Cs()?void 0:{"User-Agent":this.getUserAgent()},"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...it(),...typeof a==`string`?{"X-Stainless-Helper-Method":a}:{},"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,n,e.headers]);return this._provider||this.validateHeaders(o,e.__security??{bearerAuth:!0}),o.values}_makeAbort(e){return()=>e.abort()}_makeUserAbortError(e){let t=new m;return Object.defineProperty(t,"cause",{value:e.reason,writable:!0,configurable:!0}),t}buildBody({options:e}){let{body:t,headers:n}=e;if(!t)return t===void 0&&`body`in e?{...c(this,bs,`f`).call(this,{body:t,headers:P([n])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let r=P([n]),i=globalThis.ReadableStream!==void 0&&t instanceof globalThis.ReadableStream,a=!i&&(typeof t==`string`||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||globalThis.Blob!==void 0&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t==`string`&&r.values.has(`content-type`)||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||i?{bodyHeaders:void 0,body:t,isStreamingBody:!a}:typeof t==`object`&&(Symbol.asyncIterator in t||Symbol.iterator in t&&`next`in t&&typeof t.next==`function`)?{bodyHeaders:void 0,body:ye(t),isStreamingBody:!0}:typeof t==`object`&&r.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(t),isStreamingBody:!1}:{...c(this,bs,`f`).call(this,{body:t,headers:r}),isStreamingBody:!1}}};ys=$,bs=new WeakMap,xs=new WeakMap,vs=new WeakSet,Ss=function(){return this._provider!==void 0||this.baseURL!==`https://api.openai.com/v1`},$.OpenAI=ys,$.DEFAULT_TIMEOUT=6e5,$.OpenAIError=f,$.APIError=p,$.APIConnectionError=h,$.APIConnectionTimeoutError=g,$.APIUserAbortError=m,$.NotFoundError=b,$.ConflictError=x,$.RateLimitError=te,$.BadRequestError=_,$.AuthenticationError=v,$.InternalServerError=ne,$.PermissionDeniedError=y,$.UnprocessableEntityError=ee,$.InvalidWebhookSignatureError=ae,$.toFile=vn,$.toStreamingFile=Rt,$.Completions=Oa,$.Chat=Hr,$.Embeddings=Fa,$.Files=za,$.Images=Xa,$.ContentProvenanceChecks=Ma,$.Audio=Si,$.Moderations=Qa,$.Models=Za,$.FineTuning=qa,$.Graders=Ya,$.VectorStores=ss,$.Webhooks=fs,$.Beta=Da,$.Batches=Ci,$.Uploads=rs,$.Admin=vi,$.Responses=Zo,$.Realtime=to,$.Conversations=Pa,$.Evals=Ra,$.Containers=ja,$.Skills=ts,$.Videos=cs;var Ts=new WeakMap;function Es(e){let t=new AbortController;if(!e)return t;let n=globalThis.AbortSignal;if(typeof n?.any!=`function`||!(e instanceof n))return t;try{let r=n.any([t.signal,e]);Object.defineProperty(t,"signal",{value:r,configurable:!0}),Ts.set(t,e)}catch{}return t}function Ds(e){if(Os(e))return`Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });`}function Os(e){let t=e;for(let e=0;e<8&&t&&typeof t==`object`;e++){let e=t;if(e.code===`UND_ERR_INVALID_ARG`&&typeof e.message==`string`&&e.message.includes(`invalid onRequestStart method`))return!0;t=e.cause}return!1}var ks=class extends ${constructor({baseURL:e=G(`OPENAI_BASE_URL`),apiKey:t=G(`AZURE_OPENAI_API_KEY`),apiVersion:n=G(`OPENAI_API_VERSION`),endpoint:r,deployment:i,azureADTokenProvider:a,dangerouslyAllowBrowser:o,...s}={}){if(!n)throw new f(`The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).`);if(typeof a==`function`&&(o??=!0),!a&&!t)throw new f("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&t)throw new f("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(s.defaultQuery={...s.defaultQuery,"api-version":n},!e){if(r||={}.AZURE_OPENAI_ENDPOINT,!r)throw new f("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");let t=r.length;for(;t>0&&r[t-1]===`/`;)t--;e=`${r.slice(0,t)}/openai`}else if(r)throw new f(`baseURL and endpoint are mutually exclusive`);super({apiKey:a??t,baseURL:e,...s,...o===void 0?{}:{dangerouslyAllowBrowser:o}}),this.apiVersion=``,this.apiVersion=n,this.deploymentName=i}async buildRequest(e,t={}){if(As.has(e.path)&&e.method===`post`&&e.body!==void 0){if(!C(e.body))throw Error(`Expected request body to be an object`);let t=this.deploymentName||e.body.model||e.__metadata?.model;t!==void 0&&!this.baseURL.includes(`/deployments`)&&(e.path=L`/deployments/${t}`+e.path)}let n=await super.buildRequest(e,t);return n.req.headers.has(`api-key`)&&(n.req.redirect=`manual`),n}async fetchWithAuth(e,t,n,r,i){return new Headers(t.headers).has(`api-key`)&&(t.redirect=`manual`),super.fetchWithAuth(e,t,n,r,i)}async authHeaders(e,t){let n=t??{bearerAuth:!0,adminAPIKeyAuth:!0};return n.bearerAuth&&typeof this._options.apiKey==`string`?P([{"api-key":this.apiKey}]):super.authHeaders(e,n)}},As=new Set([`/completions`,`/chat/completions`,`/embeddings`,`/audio/transcriptions`,`/audio/translations`,`/audio/speech`,`/images/generations`,`/batches`,`/images/edits`]),js=`azure-openai`,Ms=`2024-12-01-preview`,Ns={id:js,name:`Azure OpenAI`,description:`GPT models via Azure AI Foundry`,requiresApiKey:!0,apiKeyPlaceholder:`Azure API key`,apiKeyEnvVar:`AZURE_OPENAI_API_KEY`,requiresBaseUrl:!0,baseUrlPlaceholder:`https://your-resource.cognitiveservices.azure.com/`,baseUrlDescription:`Azure resource endpoint`,requiresDeployment:!0,deploymentPlaceholder:`gpt-4.1-mini, gpt-4o, o4-mini`,deploymentDescription:`Comma-separated deployment names (from Azure Portal → Deployments)`,requiresApiVersion:!0,apiVersionDefault:Ms,apiVersionDescription:`Azure OpenAI API version`,getModelIds:()=>{let t=e(js);if(!t)return[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}];let n=t.split(`,`).map(e=>e.trim()).filter(Boolean);return n.length===0?[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}]:n.map(e=>{let t=e.startsWith(`o1`)||e.startsWith(`o3`)||e.startsWith(`o4`);return{id:e,name:`${e} (Azure)`,reasoning:t,input:[`text`,`image`]}})}};function Ps(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,64)}function Fs(e,t){let n=a(e.messages,t,Ps),r=[];for(let e of n)if(e.role===`user`)if(typeof e.content==`string`)r.push({role:`user`,content:e.content});else{let t=e.content.map(e=>e.type===`text`?{type:`text`,text:e.text??``}:e.type===`image`?{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}:{type:`text`,text:JSON.stringify(e)});r.push({role:`user`,content:t})}else if(e.role===`assistant`){let t=e.content,n=t.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i=t.filter(e=>e.type===`toolCall`).map(e=>({id:e.id??``,type:`function`,function:{name:e.name??``,arguments:JSON.stringify(e.arguments??{})}}));i.length?r.push({role:`assistant`,content:n||null,tool_calls:i}):r.push({role:`assistant`,content:n})}else if(e.role===`toolResult`){let t=e.content;r.push({role:`tool`,tool_call_id:e.toolCallId??``,content:t?.map(e=>e.type===`text`?e.text??``:JSON.stringify(e)).join(``)||``})}return r}function Is(e){if(e?.length)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}function Ls(e){let t=e.content.find(e=>e.type===`text`);if(t)return{block:t,index:e.content.indexOf(t)};let n={type:`text`,text:``};return e.content.push(n),{block:n,index:e.content.length-1}}function Rs(e,t){return e.content.find(e=>e.type===`toolCall`&&e.id===t)}function zs(e){return{role:`assistant`,content:[],api:`azure-openai-anthropic`,provider:js,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()}}function Bs(e,n){let r=n.apiKey;if(!r)throw Error(`Azure API key is required`);let i=e.baseUrl;if(!i)throw Error(`Azure endpoint is required`);let a={};e.headers&&Object.assign(a,e.headers),n.headers&&Object.assign(a,n.headers);let o=t(js)||Ms,s=e.id;return{client:new ks({endpoint:i.replace(/\/+$/,``),apiKey:r,deployment:s,apiVersion:o,dangerouslyAllowBrowser:!0,defaultHeaders:a}),deployment:s}}function Vs(e,t){return[...e.systemPrompt?[{role:`system`,content:e.systemPrompt}]:[],...Fs(e,t)]}function Hs(e,t,n){n&&(e.usage.input=n.prompt_tokens??0,e.usage.output=n.completion_tokens??0,e.usage.totalTokens=n.total_tokens??0,i(t,e.usage))}function Us(e){return e===`tool_calls`?`toolUse`:e===`length`?`length`:`stop`}function Ws(e,t,n){let{block:r,index:i}=Ls(t);r.text===``&&e.push({type:`text_start`,contentIndex:i,partial:t}),r.text+=n,e.push({type:`text_delta`,contentIndex:i,delta:n,partial:t})}function Gs(e,t,n){let r=n.id?Rs(t,n.id):void 0;if(r||!n.id)return r;let i={type:`toolCall`,id:n.id,name:n.function?.name??``,arguments:{},_partialJson:``};return t.content.push(i),e.push({type:`toolcall_start`,contentIndex:t.content.length-1,partial:t}),i}function Ks(e,t,n,r){n._partialJson+=r;try{n.arguments=JSON.parse(n._partialJson)}catch{}e.push({type:`toolcall_delta`,contentIndex:t.content.indexOf(n),delta:r,partial:t})}function qs(e,t,n){for(let r of n){let n=Gs(e,t,r);n&&r.function?.arguments&&Ks(e,t,n,r.function.arguments)}}function Js(e,t,n){let r=n.delta;r&&(r.content&&Ws(e,t,r.content),r.tool_calls&&qs(e,t,r.tool_calls),n.finish_reason&&(t.stopReason=Us(n.finish_reason)))}function Ys(e,t,n,r){try{n.arguments=JSON.parse(n._partialJson||`{}`)}catch{}delete n._partialJson,e.push({type:`toolcall_end`,contentIndex:r,toolCall:n,partial:t})}function Xs(e,t){for(let n=0;n<t.content.length;n+=1){let r=t.content[n];r.type===`toolCall`?Ys(e,t,r,n):r.type===`text`&&e.push({type:`text_end`,contentIndex:n,content:r.text,partial:t})}}async function Zs(e,t,n,r,i){let{client:a,deployment:o}=Bs(n,i),s=Is(r.tools),c=await a.chat.completions.create({model:o,messages:Vs(r,n),stream:!0,stream_options:{include_usage:!0},...i.maxTokens?{max_completion_tokens:i.maxTokens}:{},...i.temperature===void 0?{}:{temperature:i.temperature},...s?{tools:s}:{}});e.push({type:`start`,partial:t});for await(let r of c){Hs(t,n,r.usage);for(let n of r.choices??[])Js(e,t,n)}Xs(e,t),e.push({type:`done`,reason:t.stopReason,message:t}),e.end()}function Qs(e,t,n,r){t.stopReason=r?`aborted`:`error`,t.errorMessage=n instanceof Error?n.message:JSON.stringify(n),e.push({type:`error`,reason:t.stopReason,error:t}),e.end()}var $s=(e,t,r={})=>{let i=n(),a=zs(e);return Zs(i,a,e,t,r).catch(e=>{Qs(i,a,e,!!r.signal?.aborted)}),i},ec=(e,t,n)=>{let i=n?.apiKey;if(!i)throw Error(`Azure API key is required`);return $s(e,t,{...r(e,n,i)})};function tc(){o({api:`azure-openai-anthropic`,stream:$s,streamSimple:ec})}export{Ns as config,tc as register};
|