sliccy 6.78.1 → 6.78.3
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 +215 -227
- package/dist/ui/assets/{account-store-DFPhEmuH.js → account-store-Bwe7JMH-.js} +1 -1
- package/dist/ui/assets/{account-store-CqA9SSU8.js → account-store-Ch65aCFb.js} +1 -1
- package/dist/ui/assets/{adobe-DxnLH0tB.js → adobe-Bz9Td5du.js} +1 -1
- package/dist/ui/assets/{adobe-C9LIkjuB.js → adobe-DsgfMMl7.js} +1 -1
- package/dist/ui/assets/anthropic-messages-BX4DpK10.js +39 -0
- package/dist/ui/assets/anthropic-messages-C-orWG7m.js +39 -0
- package/dist/ui/assets/{apply-layout-Ba_t-LU-.js → apply-layout-CFIXh5fS.js} +1 -1
- package/dist/ui/assets/{apps-yLGS328q.js → apps-Cs8oR4Lg.js} +1 -1
- package/dist/ui/assets/azure-openai-Cm4-SPmb.js +18 -0
- package/dist/ui/assets/azure-openai-V4ydKR70.js +18 -0
- package/dist/ui/assets/{azure-openai-responses-eJTO6o5G.js → azure-openai-responses-C2LleG-4.js} +1 -1
- package/dist/ui/assets/{azure-openai-responses-qqQXNCHy.js → azure-openai-responses-Df9YPxyp.js} +1 -1
- package/dist/ui/assets/bedrock-camp-B0KF_4RS.js +1 -0
- package/dist/ui/assets/bedrock-camp-qpZqnqLa.js +2 -0
- package/dist/ui/assets/{browser-BAL8RehA.js → browser-2rCVqcqy.js} +1 -1
- package/dist/ui/assets/{cerebras-CO_bCsX2.js → cerebras-C51m3zHq.js} +1 -1
- package/dist/ui/assets/{cerebras-Bjmz0nDq.js → cerebras-Cr72hzB7.js} +1 -1
- package/dist/ui/assets/{connect-surface-CKT9YR66.js → connect-surface-BgLFvMBr.js} +1 -1
- package/dist/ui/assets/constrained-sampling-BNmnoM-i.js +1 -0
- package/dist/ui/assets/constrained-sampling-Zzx2ko9x.js +1 -0
- 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-BGYdXvQe.js → fs-CHduR_z-.js} +2 -2
- package/dist/ui/assets/{fs-BgcV7gMH.js → fs-CrXC-O2d.js} +1 -1
- package/dist/ui/assets/{github-CWDyelVA.js → github-BGfSga5-.js} +1 -1
- package/dist/ui/assets/{github-DigiqZkc.js → github-BIU4tpUD.js} +2 -2
- package/dist/ui/assets/{github-copilot-D3QxDFpn.js → github-copilot-D9Lwnwqf.js} +1 -1
- package/dist/ui/assets/{github-copilot-BUvhiBqo.js → github-copilot-DVH5IrYn.js} +1 -1
- package/dist/ui/assets/{github-install-J_iRe0Qn.js → github-install-BdNHZlYI.js} +1 -1
- package/dist/ui/assets/{github-zip-DA7KS0q8.js → github-zip-CpmjWt7A.js} +1 -1
- package/dist/ui/assets/google-generative-ai-C9uw7Zks.js +1 -0
- package/dist/ui/assets/google-generative-ai-DHBc1oKV.js +1 -0
- package/dist/ui/assets/google-shared-BMJ_JErv.js +11 -0
- package/dist/ui/assets/google-shared-YqcyR4cm.js +371 -0
- package/dist/ui/assets/google-vertex-BaT3InWy.js +1 -0
- package/dist/ui/assets/google-vertex-DX8CfGr6.js +1 -0
- 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-BnUM21eR.js → js-realm-worker-MY0pjZ9h.js} +4 -4
- package/dist/ui/assets/{kernel-worker-yw857ueT.js → kernel-worker-BKxUtfmY.js} +300 -300
- package/dist/ui/assets/{legacy-api-aliases-C2CCsk4u.js → legacy-api-aliases-CsTVszvY.js} +1 -1
- package/dist/ui/assets/{legacy-api-aliases-qI5FdR49.js → legacy-api-aliases-nSD9C16V.js} +1 -1
- package/dist/ui/assets/{local-llm-BGW1wtLE.js → local-llm-D1NRQkzz.js} +1 -1
- package/dist/ui/assets/{local-llm-COK65VbN.js → local-llm-HqLsF79p.js} +1 -1
- package/dist/ui/assets/{main-E8Y9fUEO.js → main-BAZcY8aY.js} +3 -3
- package/dist/ui/assets/mistral-conversations-BXo-tb0V.js +4 -0
- package/dist/ui/assets/mistral-conversations-Ck257tvp.js +4 -0
- package/dist/ui/assets/{mount-D8qNPn6f.js → mount-DG1bfETF.js} +2 -2
- package/dist/ui/assets/{mount-BRFa6t-4.js → mount-M6zAHrfJ.js} +1 -1
- package/dist/ui/assets/{mount-recovery-CHVRcxtq.js → mount-recovery-_TjykwtG.js} +1 -1
- package/dist/ui/assets/{new-session-BGczu0FG.js → new-session--SSmR5Ga.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-4fK_96El.js → oauth-bootstrap-BsYaFcYA.js} +2 -2
- package/dist/ui/assets/openai-CjBvzZcB.js +17 -0
- package/dist/ui/assets/openai-ZcrxEOGB.js +17 -0
- package/dist/ui/assets/{openai-codex-C8wVJf5e.js → openai-codex-C5laLxy5.js} +1 -1
- package/dist/ui/assets/{openai-codex-B81Bro8k.js → openai-codex-ChaoxQtS.js} +1 -1
- package/dist/ui/assets/openai-codex-responses-BQzefg3i.js +7 -0
- package/dist/ui/assets/openai-codex-responses-JtcU5b3J.js +7 -0
- package/dist/ui/assets/openai-completions-D-HjYi8x.js +5 -0
- package/dist/ui/assets/openai-completions-QMfwfjiE.js +5 -0
- package/dist/ui/assets/openai-responses-BVHnEPuG.js +1 -0
- package/dist/ui/assets/openai-responses-Ca0oWhbv.js +1 -0
- package/dist/ui/assets/openai-responses-shared-DhnqxYC9.js +10 -0
- package/dist/ui/assets/openai-responses-shared-DxcsuzHF.js +10 -0
- package/dist/ui/assets/{openrouter-DNcyWZsw.js → openrouter-5bo3AK5r.js} +1 -1
- package/dist/ui/assets/{openrouter-BReb0eBy.js → openrouter-BglEF0gx.js} +1 -1
- package/dist/ui/assets/{openrouter-images-CeBDTy7a.js → openrouter-images-C93KT7V_.js} +1 -1
- package/dist/ui/assets/{openrouter-images-JzygwjVz.js → openrouter-images-CiM-JPBO.js} +1 -1
- package/dist/ui/assets/{openrouter-models-BVfLgK5R.js → openrouter-models-BhgPe74G.js} +1 -1
- package/dist/ui/assets/{openrouter-models-Ds9BfRxR.js → openrouter-models-DYeJmDu6.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-CdzR0HLG.js → openrouter-oauth-B_qwkZyM.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-DtQkXo85.js → openrouter-oauth-lWgqXvCt.js} +1 -1
- package/dist/ui/assets/openrouter.models-DEX-YTLI.js +1 -0
- package/dist/ui/assets/openrouter.models-gbjkpjE_.js +1 -0
- package/dist/ui/assets/{panel-rpc-handlers-B6g2obdo.js → panel-rpc-handlers-DOaYtEJ2.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/pi-user-agent-6Rm79QmC.js +1 -0
- package/dist/ui/assets/pi-user-agent-BlGZrXbX.js +1 -0
- package/dist/ui/assets/{provider-BnYcq1I8.js → provider-D5-Ws4A3.js} +1 -1
- package/dist/ui/assets/{provider-O2Fsi2E6.js → provider-DGKy0rlK.js} +2 -2
- package/dist/ui/assets/{provider-settings-CHVLgGD4.js → provider-settings-BkIna1v7.js} +1 -1
- package/dist/ui/assets/{provider-settings-B4ty6gIx.js → provider-settings-DrEGQ7ef.js} +1 -1
- package/dist/ui/assets/provider-store-access-BK4wRKW6.js +1 -0
- package/dist/ui/assets/{provider-store-access-DO8lATOK.js → provider-store-access-Dr5cJrix.js} +2 -2
- package/dist/ui/assets/{providers-UBBok802.js → providers-B9Tcuh9N.js} +1 -1
- package/dist/ui/assets/{providers-DTdEhTSN.js → providers-DiWgfJHV.js} +2 -2
- package/dist/ui/assets/{quick-llm-CmyRUCMf.js → quick-llm-CSEzJrdv.js} +1 -1
- package/dist/ui/assets/{recovery-screen-_f8iC-Fq.js → recovery-screen-BAeZAnd3.js} +1 -1
- package/dist/ui/assets/{redirect-uri-CMVLNgtY.js → redirect-uri-BmNItvHl.js} +1 -1
- package/dist/ui/assets/{session-freezer-CvPl-bDp.js → session-freezer-BU7ggIXE.js} +3 -3
- package/dist/ui/assets/{setup-feature-flags-remote-CHIJc86J.js → setup-feature-flags-remote-B7CMO8xS.js} +1 -1
- package/dist/ui/assets/{setup-standalone-prelude-DUERSTfj.js → setup-standalone-prelude-Dg0BO-ug.js} +1 -1
- package/dist/ui/assets/{setup-sudo-D2RYRZR7.js → setup-sudo-w0slorYi.js} +2 -2
- package/dist/ui/assets/{skills-BFj_C0zu.js → skills-Qu2Xx97d.js} +1 -1
- package/dist/ui/assets/slicc-version-BJsqUhbP.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-PIfsltkW.js → store-BY8jHah-.js} +1 -1
- package/dist/ui/assets/{store-B_azjzWK.js → store-DLe-z7qR.js} +1 -1
- package/dist/ui/assets/{sudo-B_q1NKKG.js → sudo-B-8VnvDn.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-DPiDPtcB.js → upgrade-detection-Bsw9PDXL.js} +1 -1
- package/dist/ui/assets/{wc-attach-C4L2GyF0.js → wc-attach-BsqldTbU.js} +2 -2
- package/dist/ui/assets/{wc-extension-BO9vRQwT.js → wc-extension-DYDuh0JO.js} +2 -2
- package/dist/ui/assets/{wc-follower-CZfJ2TtN.js → wc-follower-ww51bVZi.js} +3 -3
- package/dist/ui/assets/{wc-live-Bs4FhY5U.js → wc-live-B-tu9Zmf.js} +5 -5
- package/dist/ui/assets/{wc-nav-CxJPwpP-.js → wc-nav-DTKff66m.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-Da7hSB-p.js → wc-onboarding-W9IFk-VE.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-Dxzwmbbc.js → wc-placeholder-BHMU_r6O.js} +2 -2
- package/dist/ui/assets/{wc-settings-LBH0HADM.js → wc-settings-DXjEjm0D.js} +2 -2
- package/dist/ui/assets/wc-shell-Csh9APE_.js +119 -0
- package/dist/ui/assets/{wc-sprinkles-kW8sZ7l_.js → wc-sprinkles-DzajqLC2.js} +2 -2
- package/dist/ui/assets/{wc-tray-Z8PDTCsn.js → wc-tray-DNQ32Rxm.js} +2 -2
- package/dist/ui/assets/{xai-grok-Bj6T-qsO.js → xai-grok-Bjjeqaxc.js} +1 -1
- package/dist/ui/assets/{xai-grok-CNmzJXMK.js → xai-grok-D9twjPSS.js} +1 -1
- package/dist/ui/index.html +9 -9
- package/dist/ui/lucide-icons.js +1788 -1707
- package/dist/ui/packages/webapp/index.html +9 -9
- package/package.json +10 -10
- package/dist/ui/assets/anthropic-messages-DzEs7DmW.js +0 -39
- package/dist/ui/assets/anthropic-messages-EYoOyCX6.js +0 -39
- package/dist/ui/assets/azure-openai-BjzhxW0m.js +0 -18
- package/dist/ui/assets/azure-openai-Cv0yG7CG.js +0 -18
- package/dist/ui/assets/bedrock-camp-BfNg24Ce.js +0 -1
- package/dist/ui/assets/bedrock-camp-C8bCNVSq.js +0 -2
- package/dist/ui/assets/completionchunk-CVTjxyMe.js +0 -65
- package/dist/ui/assets/completionchunk-CksvMkXE.js +0 -65
- package/dist/ui/assets/constrained-sampling-DafcjXU6.js +0 -1
- 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/google-generative-ai-C9Is_VVN.js +0 -1
- package/dist/ui/assets/google-generative-ai-u7R_TH9o.js +0 -1
- package/dist/ui/assets/google-shared-BPNUreTT.js +0 -371
- package/dist/ui/assets/google-shared-Cde0njMr.js +0 -11
- package/dist/ui/assets/google-vertex-DzrD0kHC.js +0 -1
- package/dist/ui/assets/google-vertex-bmq-ZPFH.js +0 -1
- package/dist/ui/assets/icons-DtQGhvkp.js +0 -1
- package/dist/ui/assets/mistral-conversations-BKWQGrhA.js +0 -8
- package/dist/ui/assets/mistral-conversations-CunWHeDt.js +0 -7
- package/dist/ui/assets/openai-DQxsE__c.js +0 -16
- package/dist/ui/assets/openai-DehfWK3N.js +0 -16
- package/dist/ui/assets/openai-codex-responses-8wXA5Dto.js +0 -7
- package/dist/ui/assets/openai-codex-responses-CeLTmOkk.js +0 -7
- package/dist/ui/assets/openai-completions-CfjF1o-N.js +0 -5
- package/dist/ui/assets/openai-completions-q2lvopuz.js +0 -5
- package/dist/ui/assets/openai-responses-B7rl8DAX.js +0 -1
- package/dist/ui/assets/openai-responses-Cpj4YO2E.js +0 -1
- package/dist/ui/assets/openai-responses-shared-B_T0yMQn.js +0 -10
- package/dist/ui/assets/openai-responses-shared-iNFeCdoC.js +0 -10
- package/dist/ui/assets/openrouter.models-CrhNqqEN.js +0 -1
- package/dist/ui/assets/openrouter.models-DkPWoMvu.js +0 -1
- package/dist/ui/assets/otel-BVv11zKU.js +0 -3
- package/dist/ui/assets/otel-BZA5WuO2.js +0 -3
- package/dist/ui/assets/pdfjs-CRuE4vGw.js +0 -54
- package/dist/ui/assets/provider-store-access-DojveU92.js +0 -1
- package/dist/ui/assets/slicc-version-C2rv26Z3.js +0 -1
- package/dist/ui/assets/src-C9oNvq2b.js +0 -2
- package/dist/ui/assets/wc-shell-DXji2EMu.js +0 -117
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
function e(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 t(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 n=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return n=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^r()&15>>e/4).toString(16))};function r(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var i=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)},a=class extends Error{},o=class e extends a{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,a){if(!t||!a)return new c({message:r,cause:i(n)});let o=n?.error;return t===400?new u(t,o,r,a):t===401?new d(t,o,r,a):t===403?new f(t,o,r,a):t===404?new p(t,o,r,a):t===409?new m(t,o,r,a):t===422?new h(t,o,r,a):t===429?new g(t,o,r,a):t>=500?new _(t,o,r,a):new e(t,o,r,a)}},s=class extends o{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},c=class extends o{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},l=class extends c{constructor({message:e}={}){super({message:e??`Request timed out.`})}},u=class extends o{},d=class extends o{},f=class extends o{},p=class extends o{},m=class extends o{},h=class extends o{},g=class extends o{},_=class extends o{},v=class extends a{constructor(){super(`Could not parse response content as the length limit was reached`)}},y=class extends a{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},b=class extends Error{constructor(e){super(e)}},ee=class extends o{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}},te=class extends a{constructor(e,t,n){super(e),this.provider=t,this.cause=n}},ne=/^[a-z][a-z0-9+.-]*:/i,re=e=>ne.test(e),x=e=>(x=Array.isArray,x(e)),ie=x;function ae(e){return typeof e==`object`?e??{}:{}}function oe(e){if(!e)return!0;for(let t in e)return!1;return!0}function se(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ce(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var le=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new a(`${e} must be an integer`);if(t<0)throw new a(`${e} must be a positive integer`);return t},ue=e=>{try{return JSON.parse(e)}catch{return}},de=e=>new Promise(t=>setTimeout(t,e)),fe=`6.40.0`,pe=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function me(){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 he=()=>{let e=me();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":fe,"X-Stainless-OS":ve(Deno.build.os),"X-Stainless-Arch":_e(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":fe,"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":fe,"X-Stainless-OS":ve(globalThis.process.platform??`unknown`),"X-Stainless-Arch":_e(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=ge();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":fe,"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":fe,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function ge(){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 _e=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,ve=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`),ye,be=()=>ye??=he();function xe(){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 Se(...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 Ce(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Se({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function we(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 Te(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 Ee=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),De=`RFC3986`,Oe=e=>String(e),ke={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:Oe},Ae=(e,t)=>(Ae=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ae(e,t)),S=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),je=1024,Me=(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,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=je){let t=a.length>=je?a.slice(e,e+je):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=S[r];continue}if(r<2048){n[n.length]=S[192|r>>6]+S[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=S[224|r>>12]+S[128|r>>6&63]+S[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=S[240|r>>18]+S[128|r>>12&63]+S[128|r>>6&63]+S[128|r&63]}o+=n.join(``)}return o};function Ne(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Pe(e,t){if(x(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}var Fe={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},Ie=function(e,t){Array.prototype.push.apply(e,x(t)?t:[t])},Le,C={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:Me,encodeValuesOnly:!1,format:De,formatter:Oe,indices:!1,serializeDate(e){return(Le??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function Re(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var ze={};function Be(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,ee=!1;for(;(y=y.get(ze))!==void 0&&!ee;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);ee=!0}y.get(ze)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&x(v)&&(v=Pe(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,C.encoder,g,`key`,p):t;v=``}if(Re(v)||Ne(v)){if(c){let e=h?t:c(t,C.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,C.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let te=[];if(v===void 0)return te;let ne;if(n===`comma`&&x(v))h&&c&&(v=Pe(v,c)),ne=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(x(l))ne=l;else{let e=Object.keys(v);ne=u?e.sort(u):e}let re=s?String(t).replace(/\./g,`%2E`):String(t),ie=r&&x(v)&&v.length===1?re+`[]`:re;if(i&&x(v)&&v.length===0)return ie+`[]`;for(let t=0;t<ne.length;++t){let y=ne[t],ee=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&ee===null)continue;let re=d&&s?y.replace(/\./g,`%2E`):y,ae=x(v)?typeof n==`function`?n(ie,re):ie:ie+(d?`.`+re:`[`+re+`]`);_.set(e,b);let oe=new WeakMap;oe.set(ze,_),Ie(te,Be(ee,ae,n,r,i,a,o,s,n===`comma`&&h&&x(v)?null:c,l,u,d,f,p,m,h,g,oe))}return te}function Ve(e=C){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||C.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=De;if(e.format!==void 0){if(!Ae(ke,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=ke[n],i=C.filter;(typeof e.filter==`function`||x(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in Fe?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:C.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:C.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:C.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:C.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:C.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?C.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:C.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:C.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:C.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:C.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:C.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:C.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:C.strictNullHandling}}function He(e,t={}){let n=e,r=Ve(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):x(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=Fe[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||Ie(o,Be(n[t],t,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&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function Ue(e){return He(e,{arrayFormat:`brackets`})}function We(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var Ge;function Ke(e){let t;return(Ge??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var qe;function Je(e){let t;return(qe??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var w,T,Ye=class{constructor(){w.set(this,void 0),T.set(this,void 0),e(this,w,new Uint8Array,`f`),e(this,T,null,`f`)}decode(n){if(n==null)return[];let r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?Ke(n):n;e(this,w,We([t(this,w,`f`),r]),`f`);let i=[],a;for(;(a=Xe(t(this,w,`f`),t(this,T,`f`)))!=null;){if(a.carriage&&t(this,T,`f`)==null){e(this,T,a.index,`f`);continue}if(t(this,T,`f`)!=null&&(a.index!==t(this,T,`f`)+1||a.carriage)){i.push(Je(t(this,w,`f`).subarray(0,t(this,T,`f`)-1))),e(this,w,t(this,w,`f`).subarray(t(this,T,`f`)),`f`),e(this,T,null,`f`);continue}let n=t(this,T,`f`)===null?a.preceding:a.preceding-1,r=Je(t(this,w,`f`).subarray(0,n));i.push(r),e(this,w,t(this,w,`f`).subarray(a.index),`f`),e(this,T,null,`f`)}return i}flush(){return t(this,w,`f`).length?this.decode(`
|
|
2
|
+
`):[]}};w=new WeakMap,T=new WeakMap,Ye.NEWLINE_CHARS=new Set([`
|
|
3
|
+
`,`\r`]),Ye.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Xe(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Ze(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}var Qe={off:0,error:200,warn:300,info:400,debug:500},$e=(e,t,n)=>{if(e){if(se(Qe,e))return e;E(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Qe))}`)}};function et(){}function tt(e,t,n){return!t||Qe[e]>Qe[n]?et:t[e].bind(t)}var nt={error:et,warn:et,info:et,debug:et},rt=new WeakMap;function E(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return nt;let r=rt.get(t);if(r&&r[0]===n)return r[1];let i={error:tt(`error`,t,n),warn:tt(`warn`,t,n),info:tt(`info`,t,n),debug:tt(`debug`,t,n)};return rt.set(t,[n,i]),i}var D=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()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),it,at=class n{constructor(t,n,r){this.iterator=t,it.set(this,void 0),this.controller=n,e(this,it,r,`f`)}static fromSSEResponse(e,t,i,s){let c=!1,l=i?E(i):console;async function*u(){if(c)throw new a("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");c=!0;let n=!1;try{for await(let r of ot(e,t))if(!n){if(r.data.startsWith(`[DONE]`)){n=!0;continue}if(r.event===null||!r.event.startsWith(`thread.`)){let t;try{t=JSON.parse(r.data)}catch(e){throw l.error(`Could not parse message into JSON:`,r.data),l.error(`From chunk:`,r.raw),e}if(t&&t.error)throw new o(void 0,t.error,void 0,e.headers);yield s?{event:r.event,data:t}:t}else{let e;try{e=JSON.parse(r.data)}catch(e){throw console.error(`Could not parse message into JSON:`,r.data),console.error(`From chunk:`,r.raw),e}if(r.event==`error`)throw new o(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}n=!0}catch(e){if(r(e))return;throw e}finally{n||t.abort()}}return new n(u,t,i)}static fromReadableStream(e,t,i){let o=!1;async function*s(){let t=new Ye,n=we(e);for await(let e of n)for(let n of t.decode(e))yield n;for(let e of t.flush())yield e}async function*c(){if(o)throw new a("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let e=!1;try{for await(let t of s())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(r(e))return;throw e}finally{e||t.abort()}}return new n(c,t,i)}[(it=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],i=this.iterator(),a=t=>({next:()=>{if(t.length===0){let t=i.next();e.push(t),r.push(t)}return t.shift()}});return[new n(()=>a(e),this.controller,t(this,it,`f`)),new n(()=>a(r),this.controller,t(this,it,`f`))]}toReadableStream(){let e=this,t;return Se({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=Ke(JSON.stringify(n)+`
|
|
4
|
+
`);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*ot(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new a(`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 a(`Attempted to iterate over a response with no body`);let n=new ct,r=new Ye,i=we(e.body);for await(let e of st(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)}}async function*st(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?Ke(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=Ze(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var ct=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-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,r]=lt(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function lt(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function ut(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return E(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):at.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();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:dt(await n.json(),n):await n.text()})();return E(e).debug(`[${r}] response parsed`,D({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function dt(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 ft,pt=class n extends Promise{constructor(t,n,r=ut){super(e=>{e(null)}),this.responsePromise=n,this.parseResponse=r,ft.set(this,void 0),e(this,ft,t,`f`)}_thenUnwrap(e){return new n(t(this,ft,`f`),this.responsePromise,async(t,n)=>dt(e(await this.parseResponse(t,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(t(this,ft,`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)}};ft=new WeakMap;var mt,ht=class{constructor(t,n,r,i){mt.set(this,void 0),e(this,mt,t,`f`),this.options=i,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new a("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await t(this,mt,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(mt=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},gt=class extends pt{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await ut(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},O=class extends ht{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}},k=class extends ht{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:{...ae(this.options.query),after:t}}:null}},A=class extends ht{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:{...ae(this.options.query),after:e}}:null}},j=class extends ht{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:{...ae(this.options.query),after:e}}:null}},_t={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`},vt=`urn:ietf:params:oauth:grant-type:token-exchange`,yt=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl=`https://auth.openai.com/oauth/token`,this.config=e,this.fetch=t??xe()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e={grant_type:vt,subject_token:await this.config.provider.getToken(),subject_token_type:_t[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(e.client_id=this.config.clientId);let t=await this.fetch(this.tokenExchangeUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.text(),n;try{n=JSON.parse(e)}catch{}throw t.status===400||t.status===401||t.status===403?new ee(t.status,n,t.headers):o.generate(t.status,n,`Token exchange failed with status ${t.status}`,t.headers)}let n=await t.json(),r=n.expires_in||3600,i=Date.now()+r*1e3;return this.cachedToken={token:n.access_token,expiresAt:i},n.access_token}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let t=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-t}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}},bt=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function xt(e,t,n){return bt(),new File(e,t??`unknown_file`,n)}function St(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}var Ct=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,wt=async(e,t)=>At(e.body)?{...e,body:await Dt(e.body,t)}:e,M=async(e,t)=>({...e,body:await Dt(e.body,t)}),Tt=new WeakMap;function Et(e){let t=typeof e==`function`?e:e.fetch,n=Tt.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return Tt.set(t,r),r}var Dt=async(e,t)=>{if(!await Et(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let n=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>jt(n,e,t))),n},Ot=e=>e instanceof Blob&&`name`in e,kt=e=>typeof e==`object`&&!!e&&(e instanceof Response||Ct(e)||Ot(e)),At=e=>{if(kt(e))return!0;if(Array.isArray(e))return e.some(At);if(e&&typeof e==`object`){for(let t in e)if(At(e[t]))return!0}return!1},jt=async(e,t,n)=>{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,xt([await n.blob()],St(n)));else if(Ct(n))e.append(t,xt([await new Response(Ce(n)).blob()],St(n)));else if(Ot(n))e.append(t,n,St(n));else if(Array.isArray(n))await Promise.all(n.map(n=>jt(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>jt(e,`${t}[${n}]`,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},Mt=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`,Nt=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&Mt(e),Pt=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function Ft(e,t,n){if(bt(),e=await e,Nt(e))return e instanceof File?e:xt([await e.arrayBuffer()],e.name);if(Pt(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),xt(await It(r),t,n)}let r=await It(e);if(t||=St(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return xt(r,t,n)}async function It(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Mt(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Ct(e))for await(let n of e)t.push(...await It(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${Lt(e)}`)}return t}function Lt(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var N=class{constructor(e){this._client=e}};function Rt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var zt=Object.freeze(Object.create(null)),P=((e=Rt)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],o=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??zt)??zt)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),s=o.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(s))!==null;)i.push({start:l.index,length:l[0].length,error:`Value "${l[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=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new a(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
|
|
6
|
+
`)}\n${o}\n${t}`)}return o})(Rt),Bt=class extends N{list(e,t={},n){return this._client.getAPIList(P`/chat/completions/${e}/messages`,k,{query:t,...n,__security:{bearerAuth:!0}})}};function Vt(e){return e!==void 0&&`function`in e&&e.function!==void 0}function Ht(e){return e?.$brand===`auto-parseable-response-format`}function Ut(e){return e?.$brand===`auto-parseable-tool`}function Wt(e,t){return!t||!Yt(t)?{...e,choices:e.choices.map(e=>(Xt(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:Gt(e,t)}function Gt(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new v;if(e.finish_reason===`content_filter`)throw new y;return Xt(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>qt(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?Kt(t,e.message.content):null}}});return{...e,choices:n}}function Kt(e,t){return e.response_format?.type===`json_schema`&&e.response_format?.type===`json_schema`?`$parseRaw`in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function qt(e,t){let n=e.tools?.find(e=>Vt(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Ut(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function Jt(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>Vt(e)&&e.function?.name===t.function.name);return Vt(n)&&(Ut(n)||n?.function.strict||!1)}function Yt(e){return Ht(e.response_format)?!0:e.tools?.some(e=>Ut(e)||e.type===`function`&&e.function.strict===!0)??!1}function Xt(e){for(let t of e||[])if(t.type!==`function`)throw new a(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function Zt(e){for(let t of e??[]){if(t.type!==`function`)throw new a(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new a(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Qt=e=>e?.role===`assistant`,$t=e=>e?.role===`tool`,en,tn,nn,rn,an,on,sn,F,cn,ln,un,dn,fn,pn=class{constructor(){en.add(this),this.controller=new AbortController,tn.set(this,void 0),nn.set(this,()=>{}),rn.set(this,()=>{}),an.set(this,void 0),on.set(this,()=>{}),sn.set(this,()=>{}),F.set(this,{}),cn.set(this,!1),ln.set(this,!1),un.set(this,!1),dn.set(this,!1),e(this,tn,new Promise((t,n)=>{e(this,nn,t,`f`),e(this,rn,n,`f`)}),`f`),e(this,an,new Promise((t,n)=>{e(this,on,t,`f`),e(this,sn,n,`f`)}),`f`),t(this,tn,`f`).catch(()=>{}),t(this,an,`f`).catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit(`end`)},t(this,en,`m`,fn).bind(this))},0)}_connected(){this.ended||(t(this,nn,`f`).call(this),this._emit(`connect`))}get ended(){return t(this,cn,`f`)}get errored(){return t(this,ln,`f`)}get aborted(){return t(this,un,`f`)}abort(){this.controller.abort()}on(e,n){return(t(this,F,`f`)[e]||(t(this,F,`f`)[e]=[])).push({listener:n}),this}off(e,n){let r=t(this,F,`f`)[e];if(!r)return this;let i=r.findIndex(e=>e.listener===n);return i>=0&&r.splice(i,1),this}once(e,n){return(t(this,F,`f`)[e]||(t(this,F,`f`)[e]=[])).push({listener:n,once:!0}),this}emitted(t){return new Promise((n,r)=>{e(this,dn,!0,`f`),t!==`error`&&this.once(`error`,r),this.once(t,n)})}async done(){e(this,dn,!0,`f`),await t(this,an,`f`)}_emit(n,...r){if(t(this,cn,`f`))return;n===`end`&&(e(this,cn,!0,`f`),t(this,on,`f`).call(this));let i=t(this,F,`f`)[n];if(i&&(t(this,F,`f`)[n]=i.filter(e=>!e.once),i.forEach(({listener:e})=>e(...r))),n===`abort`){let e=r[0];!t(this,dn,`f`)&&!i?.length&&Promise.reject(e),t(this,rn,`f`).call(this,e),t(this,sn,`f`).call(this,e),this._emit(`end`);return}if(n===`error`){let e=r[0];!t(this,dn,`f`)&&!i?.length&&Promise.reject(e),t(this,rn,`f`).call(this,e),t(this,sn,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};tn=new WeakMap,nn=new WeakMap,rn=new WeakMap,an=new WeakMap,on=new WeakMap,sn=new WeakMap,F=new WeakMap,cn=new WeakMap,ln=new WeakMap,un=new WeakMap,dn=new WeakMap,en=new WeakSet,fn=function(t){if(e(this,ln,!0,`f`),t instanceof Error&&t.name===`AbortError`&&(t=new s),t instanceof s)return e(this,un,!0,`f`),this._emit(`abort`,t);if(t instanceof a)return this._emit(`error`,t);if(t instanceof Error){let e=new a(t.message);return e.cause=t,this._emit(`error`,e)}return this._emit(`error`,new a(String(t)))};function mn(e){return typeof e.parse==`function`}var I,hn,gn,_n,vn,yn,bn,xn,Sn=10,Cn=class extends pn{constructor(){super(...arguments),I.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(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),$t(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(Qt(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 a(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),t(this,I,`m`,hn).call(this)}async finalMessage(){return await this.done(),t(this,I,`m`,gn).call(this)}async finalFunctionToolCall(){return await this.done(),t(this,I,`m`,_n).call(this)}async finalFunctionToolCallResult(){return await this.done(),t(this,I,`m`,vn).call(this)}async totalUsage(){return await this.done(),t(this,I,`m`,yn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let n=t(this,I,`m`,gn).call(this);n&&this._emit(`finalMessage`,n);let r=t(this,I,`m`,hn).call(this);r&&this._emit(`finalContent`,r);let i=t(this,I,`m`,_n).call(this);i&&this._emit(`finalFunctionToolCall`,i);let a=t(this,I,`m`,vn).call(this);a!=null&&this._emit(`finalFunctionToolCallResult`,a),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,t(this,I,`m`,yn).call(this))}async _createChatCompletion(e,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),t(this,I,`m`,bn).call(this,n);let a=await e.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Gt(a,n))}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,n,r){let i=`tool`,{tool_choice:o=`auto`,stream:s,...c}=n,l=typeof o!=`string`&&o.type===`function`&&o?.function?.name,{maxChatCompletions:u=Sn}=r||{},d=n.tools.map(e=>{if(Ut(e)){if(!e.$callback)throw new a("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}),f={};for(let e of d)e.type===`function`&&(f[e.function.name||e.function.function.name]=e.function);let p=`tools`in n?d.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 n.messages)this._addMessage(e,!1);for(let n=0;n<u;++n){let n=(await this._createChatCompletion(e,{...c,tool_choice:o,tools:p,messages:[...this.messages]},r)).choices[0]?.message;if(!n)throw new a(`missing message in ChatCompletion response`);if(!n.tool_calls?.length)return;for(let e of n.tool_calls){if(e.type!==`function`)continue;let n=e.id,{name:r,arguments:a}=e.function,o=f[r];if(!o){let e=`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(f).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;this._addMessage({role:i,tool_call_id:n,content:e});continue}if(l&&l!==r){let e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:i,tool_call_id:n,content:e});continue}let s;try{s=mn(o)?await o.parse(a):a}catch(e){let t=e instanceof Error?e.message:String(e);this._addMessage({role:i,tool_call_id:n,content:t});continue}let c=await o.function(s,this),u=t(this,I,`m`,xn).call(this,c);if(this._addMessage({role:i,tool_call_id:n,content:u}),l)return}}}};I=new WeakSet,hn=function(){return t(this,I,`m`,gn).call(this).content??null},gn=function(){let e=this.messages.length;for(;e-->0;){let t=this.messages[e];if(Qt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new a(`stream ended without producing a ChatCompletionMessage with role=assistant`)},_n=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Qt(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>e.type===`function`).at(-1)?.function}},vn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if($t(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}},yn=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},bn=function(e){if(e.n!=null&&e.n>1)throw new a(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},xn=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var wn=class e extends Cn{static runTools(t,n,r){let i=new e,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),Qt(e)&&e.content&&this._emit(`content`,e.content)}},L={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},Tn=class extends Error{},En=class extends Error{};function Dn(e,t=L.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return On(e.trim(),t)}var On=(e,t)=>{let n=e.length,r=0,i=e=>{throw new Tn(`${e} at position ${r}`)},a=e=>{throw new En(`${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`||L.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||L.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||L.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||L.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||L.MINUS_INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||L.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(L.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&&L.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(L.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(L.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(L.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&L.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(L.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&&!(L.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&L.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&&`
|
|
7
|
+
\r `.includes(e[r]);)r++};return o()},kn=e=>Dn(e,L.ALL^L.NUM),R,z,An,B,jn,Mn,Nn,Pn,Fn,In,Ln,Rn,zn=class n extends Cn{constructor(t){super(),R.add(this),z.set(this,void 0),An.set(this,void 0),B.set(this,void 0),e(this,z,t,`f`),e(this,An,[],`f`)}get currentChatCompletionSnapshot(){return t(this,B,`f`)}static fromReadableStream(e){let t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let i=new n(t);return i._run(()=>i._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createChatCompletion(e,n,r){super._createChatCompletion;let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),t(this,R,`m`,jn).call(this);let a=await e.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let e of a)t(this,R,`m`,Nn).call(this,e);if(a.controller.signal?.aborted)throw new s;return this._addChatCompletion(t(this,R,`m`,In).call(this))}async _fromReadableStream(e,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),t(this,R,`m`,jn).call(this),this._connected();let i=at.fromReadableStream(e,this.controller),a;for await(let e of i)a&&a!==e.id&&this._addChatCompletion(t(this,R,`m`,In).call(this)),t(this,R,`m`,Nn).call(this,e),a=e.id;if(i.controller.signal?.aborted)throw new s;return this._addChatCompletion(t(this,R,`m`,In).call(this))}[(z=new WeakMap,An=new WeakMap,B=new WeakMap,R=new WeakSet,jn=function(){this.ended||e(this,B,void 0,`f`)},Mn=function(e){let n=t(this,An,`f`)[e.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},t(this,An,`f`)[e.index]=n,n)},Nn=function(e){if(this.ended)return;let n=t(this,R,`m`,Rn).call(this,e);this._emit(`chunk`,e,n);for(let r of e.choices){let e=n.choices[r.index];r.delta.content!=null&&e.message?.role===`assistant`&&e.message?.content&&(this._emit(`content`,r.delta.content,e.message.content),this._emit(`content.delta`,{delta:r.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),r.delta.refusal!=null&&e.message?.role===`assistant`&&e.message?.refusal&&this._emit(`refusal.delta`,{delta:r.delta.refusal,snapshot:e.message.refusal}),r.logprobs?.content!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.content.delta`,{content:r.logprobs?.content,snapshot:e.logprobs?.content??[]}),r.logprobs?.refusal!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.refusal.delta`,{refusal:r.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let i=t(this,R,`m`,Mn).call(this,e);e.finish_reason&&(t(this,R,`m`,Fn).call(this,e),i.current_tool_call_index!=null&&t(this,R,`m`,Pn).call(this,e,i.current_tool_call_index));for(let n of r.delta.tool_calls??[])i.current_tool_call_index!==n.index&&(t(this,R,`m`,Fn).call(this,e),i.current_tool_call_index!=null&&t(this,R,`m`,Pn).call(this,e,i.current_tool_call_index)),i.current_tool_call_index=n.index;for(let t of r.delta.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)}}},Pn=function(e,n){if(t(this,R,`m`,Mn).call(this,e).done_tool_calls.has(n))return;let r=e.message.tool_calls?.[n];if(!r)throw Error(`no tool call snapshot`);if(!r.type)throw Error("tool call snapshot missing `type`");if(r.type===`function`){let e=t(this,z,`f`)?.tools?.find(e=>Vt(e)&&e.function.name===r.function.name);this._emit(`tool_calls.function.arguments.done`,{name:r.function.name,index:n,arguments:r.function.arguments,parsed_arguments:Ut(e)?e.$parseRaw(r.function.arguments):e?.function.strict?JSON.parse(r.function.arguments):null})}else r.type},Fn=function(e){let n=t(this,R,`m`,Mn).call(this,e);if(e.message.content&&!n.content_done){n.content_done=!0;let r=t(this,R,`m`,Ln).call(this);this._emit(`content.done`,{content:e.message.content,parsed:r?r.$parseRaw(e.message.content):null})}e.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit(`refusal.done`,{refusal:e.message.refusal})),e.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit(`logprobs.content.done`,{content:e.logprobs.content})),e.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit(`logprobs.refusal.done`,{refusal:e.logprobs.refusal}))},In=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);let n=t(this,B,`f`);if(!n)throw new a(`request ended without sending any chunks`);return e(this,B,void 0,`f`),e(this,An,[],`f`),Bn(n,t(this,z,`f`))},Ln=function(){let e=t(this,z,`f`)?.response_format;return Ht(e)?e:null},Rn=function(n){var r,i,a,o;let s=t(this,B,`f`),{choices:c,...l}=n;s?Object.assign(s,l):s=e(this,B,{...l,choices:[]},`f`);for(let{delta:e,finish_reason:c,index:l,logprobs:u=null,...d}of n.choices){let n=s.choices[l];if(n||=s.choices[l]={finish_reason:c,index:l,message:{},logprobs:u,...d},u)if(!n.logprobs)n.logprobs=Object.assign({},u);else{let{content:e,refusal:t,...a}=u;Object.assign(n.logprobs,a),e&&((r=n.logprobs).content??(r.content=[]),n.logprobs.content.push(...e)),t&&((i=n.logprobs).refusal??(i.refusal=[]),n.logprobs.refusal.push(...t))}if(c&&(n.finish_reason=c,t(this,z,`f`)&&Yt(t(this,z,`f`)))){if(c===`length`)throw new v;if(c===`content_filter`)throw new y}if(Object.assign(n,d),!e)continue;let{content:f,refusal:p,function_call:m,role:h,tool_calls:g,..._}=e;if(Object.assign(n.message,_),p&&(n.message.refusal=(n.message.refusal||``)+p),h&&(n.message.role=h),m&&(n.message.function_call?(m.name&&(n.message.function_call.name=m.name),m.arguments&&((a=n.message.function_call).arguments??(a.arguments=``),n.message.function_call.arguments+=m.arguments)):n.message.function_call=m),f&&(n.message.content=(n.message.content||``)+f,!n.message.refusal&&t(this,R,`m`,Ln).call(this)&&(n.message.parsed=kn(n.message.content))),g){n.message.tool_calls||(n.message.tool_calls=[]);for(let{index:e,id:r,type:i,function:a,...s}of g){let c=(o=n.message.tool_calls)[e]??(o[e]={});Object.assign(c,s),r&&(c.id=r),i&&(c.type=i),a&&(c.function??={name:a.name??``,arguments:``}),a?.name&&(c.function.name=a.name),a?.arguments&&(c.function.arguments+=a.arguments,Jt(t(this,z,`f`),c)&&(c.function.parsed_arguments=kn(c.function.arguments)))}}}return s},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`chunk`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new at(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Bn(e,t){let{id:n,choices:r,created:i,model:o,system_fingerprint:s,...c}=e;return Wt({...c,id:n,choices:r.map(({message:t,finish_reason:n,index:r,logprobs:i,...o})=>{if(!n)throw new a(`missing finish_reason for choice ${r}`);let{content:s=null,function_call:c,tool_calls:l,...u}=t,d=t.role;if(!d)throw new a(`missing role for choice ${r}`);if(c){let{arguments:e,name:l}=c;if(e==null)throw new a(`missing function_call.arguments for choice ${r}`);if(!l)throw new a(`missing function_call.name for choice ${r}`);return{...o,message:{content:s,function_call:{arguments:e,name:l},role:d,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}return l?{...o,index:r,finish_reason:n,logprobs:i,message:{...u,role:d,content:s,refusal:t.refusal??null,tool_calls:l.map((t,n)=>{let{function:i,type:o,id:s,...c}=t,{arguments:l,name:u,...d}=i||{};if(s==null)throw new a(`missing choices[${r}].tool_calls[${n}].id\n${Vn(e)}`);if(o==null)throw new a(`missing choices[${r}].tool_calls[${n}].type\n${Vn(e)}`);if(u==null)throw new a(`missing choices[${r}].tool_calls[${n}].function.name\n${Vn(e)}`);if(l==null)throw new a(`missing choices[${r}].tool_calls[${n}].function.arguments\n${Vn(e)}`);return{...c,id:s,type:o,function:{...d,name:u,arguments:l}}})}}:{...o,message:{...u,content:s,role:d,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}),created:i,model:o,object:`chat.completion`,...s?{system_fingerprint:s}:{}},t)}function Vn(e){return JSON.stringify(e)}var Hn=class e extends zn{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static runTools(t,n,r){let i=new e(n),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,a)),i}},Un=class extends N{constructor(){super(...arguments),this.messages=new Bt(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(P`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(P`/chat/completions/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chat/completions`,k,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(P`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return Zt(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>Gt(t,e))}runTools(e,t){return e.stream?Hn.runTools(this._client,e,t):wn.runTools(this._client,e,t)}stream(e,t){return zn.createChatCompletion(this._client,e,t)}};Un.Messages=Bt;var Wn=class extends N{constructor(){super(...arguments),this.completions=new Un(this._client)}};Wn.Completions=Un;var Gn=class extends N{create(e,t){return this._client.post(`/organization/admin_api_keys`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(P`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/admin_api_keys`,k,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(P`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Kn=class extends N{list(e={},t){return this._client.getAPIList(`/organization/audit_logs`,A,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},qn=class extends N{create(e,t){return this._client.post(`/organization/certificates`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(P`/organization/certificates/${e}`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(P`/organization/certificates/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/certificates`,A,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(P`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList(`/organization/certificates/activate`,O,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList(`/organization/certificates/deactivate`,O,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}},Jn=class extends N{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}})}},Yn=class extends N{create(e,t){return this._client.post(`/organization/invites`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(P`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/invites`,A,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(P`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Xn=class extends N{create(e,t){return this._client.post(`/organization/roles`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(P`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(P`/organization/roles/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/roles`,j,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(P`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Zn=class extends N{create(e,t){return this._client.post(`/organization/spend_alerts`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(P`/organization/spend_alerts/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/spend_alerts`,A,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(P`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Qn=class extends N{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}})}},$n=class extends N{create(e,t,n){return this._client.post(P`/organization/groups/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(P`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(P`/organization/groups/${e}/roles`,j,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(P`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},er=class extends N{create(e,t,n){return this._client.post(P`/organization/groups/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(P`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(P`/organization/groups/${e}/users`,j,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(P`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},tr=class extends N{constructor(){super(...arguments),this.users=new er(this._client),this.roles=new $n(this._client)}create(e,t){return this._client.post(`/organization/groups`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(P`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(P`/organization/groups/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/groups`,j,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(P`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};tr.Users=er,tr.Roles=$n;var nr=class extends N{retrieve(e,t,n){let{project_id:r}=t;return this._client.get(P`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(P`/organization/projects/${e}/api_keys`,A,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(P`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},rr=class extends N{list(e,t={},n){return this._client.getAPIList(P`/organization/projects/${e}/certificates`,A,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,t,n){return this._client.getAPIList(P`/organization/projects/${e}/certificates/activate`,O,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,n){return this._client.getAPIList(P`/organization/projects/${e}/certificates/deactivate`,O,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}},ir=class extends N{retrieve(e,t){return this._client.get(P`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(P`/organization/projects/${e}/data_retention`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}},ar=class extends N{retrieve(e,t){return this._client.get(P`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(P`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}},or=class extends N{retrieve(e,t){return this._client.get(P`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(P`/organization/projects/${e}/model_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(P`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}},sr=class extends N{listRateLimits(e,t={},n){return this._client.getAPIList(P`/organization/projects/${e}/rate_limits`,A,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,n){let{project_id:r,...i}=t;return this._client.post(P`/organization/projects/${r}/rate_limits/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}},cr=class extends N{create(e,t,n){return this._client.post(P`/projects/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(P`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(P`/projects/${r}/roles/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(P`/projects/${e}/roles`,j,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(P`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},lr=class extends N{create(e,t,n){return this._client.post(P`/organization/projects/${e}/service_accounts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(P`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(P`/organization/projects/${r}/service_accounts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(P`/organization/projects/${e}/service_accounts`,A,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(P`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},ur=class extends N{create(e,t,n){return this._client.post(P`/organization/projects/${e}/spend_alerts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(P`/organization/projects/${r}/spend_alerts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(P`/organization/projects/${e}/spend_alerts`,A,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(P`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},dr=class extends N{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(P`/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(P`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(P`/projects/${r}/groups/${e}/roles`,j,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,group_id:i}=t;return this._client.delete(P`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},fr=class extends N{constructor(){super(...arguments),this.roles=new dr(this._client)}create(e,t,n){return this._client.post(P`/organization/projects/${e}/groups`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,...i}=t;return this._client.get(P`/organization/projects/${r}/groups/${e}`,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(P`/organization/projects/${e}/groups`,j,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(P`/organization/projects/${r}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};fr.Roles=dr;var pr=class extends N{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(P`/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(P`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(P`/projects/${r}/users/${e}/roles`,j,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,user_id:i}=t;return this._client.delete(P`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},mr=class extends N{constructor(){super(...arguments),this.roles=new pr(this._client)}create(e,t,n){return this._client.post(P`/organization/projects/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(P`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(P`/organization/projects/${r}/users/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(P`/organization/projects/${e}/users`,A,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(P`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};mr.Roles=pr;var V=class extends N{constructor(){super(...arguments),this.users=new mr(this._client),this.serviceAccounts=new lr(this._client),this.apiKeys=new nr(this._client),this.rateLimits=new sr(this._client),this.modelPermissions=new or(this._client),this.hostedToolPermissions=new ar(this._client),this.groups=new fr(this._client),this.roles=new cr(this._client),this.dataRetention=new ir(this._client),this.spendAlerts=new ur(this._client),this.certificates=new rr(this._client)}create(e,t){return this._client.post(`/organization/projects`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(P`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(P`/organization/projects/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/projects`,A,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(P`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};V.Users=mr,V.ServiceAccounts=lr,V.APIKeys=nr,V.RateLimits=sr,V.ModelPermissions=or,V.HostedToolPermissions=ar,V.Groups=fr,V.Roles=cr,V.DataRetention=ir,V.SpendAlerts=ur,V.Certificates=rr;var hr=class extends N{create(e,t,n){return this._client.post(P`/organization/users/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{user_id:r}=t;return this._client.get(P`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(P`/organization/users/${e}/roles`,j,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{user_id:r}=t;return this._client.delete(P`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},gr=class extends N{constructor(){super(...arguments),this.roles=new hr(this._client)}retrieve(e,t){return this._client.get(P`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(P`/organization/users/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/users`,A,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(P`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};gr.Roles=hr;var H=class extends N{constructor(){super(...arguments),this.auditLogs=new Kn(this._client),this.adminAPIKeys=new Gn(this._client),this.usage=new Qn(this._client),this.invites=new Yn(this._client),this.users=new gr(this._client),this.groups=new tr(this._client),this.roles=new Xn(this._client),this.dataRetention=new Jn(this._client),this.spendAlerts=new Zn(this._client),this.certificates=new qn(this._client),this.projects=new V(this._client)}};H.AuditLogs=Kn,H.AdminAPIKeys=Gn,H.Usage=Qn,H.Invites=Yn,H.Users=gr,H.Groups=tr,H.Roles=Xn,H.DataRetention=Jn,H.SpendAlerts=Zn,H.Certificates=qn,H.Projects=V;var _r=class extends N{constructor(){super(...arguments),this.organization=new H(this._client)}};_r.Organization=H;var vr=Symbol(`brand.privateNullableHeaders`);function*yr(e){if(!e)return;if(vr 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():ie(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=ie(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 U=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of yr(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[vr]:!0,values:t,nulls:n}},br=class extends N{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:U([{Accept:`application/octet-stream`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},xr=class extends N{create(e,t){return this._client.post(`/audio/transcriptions`,M({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},Sr=class extends N{create(e,t){return this._client.post(`/audio/translations`,M({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},Cr=class extends N{constructor(){super(...arguments),this.transcriptions=new xr(this._client),this.translations=new Sr(this._client),this.speech=new br(this._client)}};Cr.Transcriptions=xr,Cr.Translations=Sr,Cr.Speech=br;var wr=class extends N{create(e,t){return this._client.post(`/batches`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(P`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/batches`,k,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(P`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}},Tr=class extends N{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(P`/assistants/${e}`,{...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(P`/assistants/${e}`,{body:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/assistants`,k,{query:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(P`/assistants/${e}`,{...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},Er=class extends N{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},Dr=class extends N{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},Or=class extends N{constructor(){super(...arguments),this.sessions=new Er(this._client),this.transcriptionSessions=new Dr(this._client)}};Or.Sessions=Er,Or.TranscriptionSessions=Dr;var kr=class extends N{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:U([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(P`/chatkit/sessions/${e}/cancel`,{...t,headers:U([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}},Ar=class extends N{retrieve(e,t){return this._client.get(P`/chatkit/threads/${e}`,{...t,headers:U([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,A,{query:e,...t,headers:U([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(P`/chatkit/threads/${e}`,{...t,headers:U([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},n){return this._client.getAPIList(P`/chatkit/threads/${e}/items`,A,{query:t,...n,headers:U([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers]),__security:{bearerAuth:!0}})}},jr=class extends N{constructor(){super(...arguments),this.sessions=new kr(this._client),this.threads=new Ar(this._client)}};jr.Sessions=kr,jr.Threads=Ar;var Mr=class extends N{create(e,t,n){return this._client.post(P`/threads/${e}/messages`,{body:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(P`/threads/${r}/messages/${e}`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(P`/threads/${r}/messages/${e}`,{body:i,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(P`/threads/${e}/messages`,k,{query:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(P`/threads/${r}/messages/${e}`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},Nr=class extends N{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(P`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(P`/threads/${r}/runs/${e}/steps`,k,{query:i,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},Pr=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))}},W=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},G,K,Fr,q,Ir,J,Y,Lr,X,Rr,Z,zr,Br,Vr,Hr,Ur,Wr,Gr,Kr,qr,Jr,Yr,Xr,Zr=class extends pn{constructor(){super(...arguments),G.add(this),Fr.set(this,[]),q.set(this,{}),Ir.set(this,{}),J.set(this,void 0),Y.set(this,void 0),Lr.set(this,void 0),X.set(this,void 0),Rr.set(this,void 0),Z.set(this,void 0),zr.set(this,void 0),Br.set(this,void 0),Vr.set(this,void 0)}[(Fr=new WeakMap,q=new WeakMap,Ir=new WeakMap,J=new WeakMap,Y=new WeakMap,Lr=new WeakMap,X=new WeakMap,Rr=new WeakMap,Z=new WeakMap,zr=new WeakMap,Br=new WeakMap,Vr=new WeakMap,G=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new K;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),this._connected();let i=at.fromReadableStream(e,this.controller);for await(let e of i)t(this,G,`m`,Hr).call(this,e);if(i.controller.signal?.aborted)throw new s;return this._addRun(t(this,G,`m`,Ur).call(this))}toReadableStream(){return new at(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){let i=new K;return i._run(()=>i._runToolAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createToolAssistantStream(e,n,r,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener(`abort`,()=>this.controller.abort()));let o={...r,stream:!0},c=await e.submitToolOutputs(n,o,{...i,signal:this.controller.signal});this._connected();for await(let e of c)t(this,G,`m`,Hr).call(this,e);if(c.controller.signal?.aborted)throw new s;return this._addRun(t(this,G,`m`,Ur).call(this))}static createThreadAssistantStream(e,t,n){let r=new K;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":`stream`}})),r}static createAssistantStream(e,t,n,r){let i=new K;return i._run(()=>i._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}currentEvent(){return t(this,zr,`f`)}currentRun(){return t(this,Br,`f`)}currentMessageSnapshot(){return t(this,J,`f`)}currentRunStepSnapshot(){return t(this,Vr,`f`)}async finalRunSteps(){return await this.done(),Object.values(t(this,q,`f`))}async finalMessages(){return await this.done(),Object.values(t(this,Ir,`f`))}async finalRun(){if(await this.done(),!t(this,Y,`f`))throw Error(`Final run was not received.`);return t(this,Y,`f`)}async _createThreadAssistantStream(e,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort()));let a={...n,stream:!0},o=await e.createAndRun(a,{...r,signal:this.controller.signal});this._connected();for await(let e of o)t(this,G,`m`,Hr).call(this,e);if(o.controller.signal?.aborted)throw new s;return this._addRun(t(this,G,`m`,Ur).call(this))}async _createAssistantStream(e,n,r,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener(`abort`,()=>this.controller.abort()));let o={...r,stream:!0},c=await e.create(n,o,{...i,signal:this.controller.signal});this._connected();for await(let e of c)t(this,G,`m`,Hr).call(this,e);if(c.controller.signal?.aborted)throw new s;return this._addRun(t(this,G,`m`,Ur).call(this))}static accumulateDelta(e,t){for(let[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let t=e[n];if(t==null){e[n]=r;continue}if(n===`index`||n===`type`){e[n]=r;continue}if(typeof t==`string`&&typeof r==`string`)t+=r;else if(typeof t==`number`&&typeof r==`number`)t+=r;else if(ce(t)&&ce(r))t=this.accumulateDelta(t,r);else if(Array.isArray(t)&&Array.isArray(r)){if(t.every(e=>typeof e==`string`||typeof e==`number`)){t.push(...r);continue}for(let e of r){if(!ce(e))throw Error(`Expected array delta entry to be an object but got: ${e}`);let n=e.index;if(n==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(typeof n!=`number`)throw Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);let r=t[n];r==null?t.push(e):t[n]=this.accumulateDelta(r,e)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${t}`);e[n]=t}return e}_addRun(e){return 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)}};K=Zr,Hr=function(n){if(!this.ended)switch(e(this,zr,n,`f`),t(this,G,`m`,Kr).call(this,n),n.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`:t(this,G,`m`,Xr).call(this,n);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`:t(this,G,`m`,Gr).call(this,n);break;case`thread.message.created`:case`thread.message.in_progress`:case`thread.message.delta`:case`thread.message.completed`:case`thread.message.incomplete`:t(this,G,`m`,Wr).call(this,n);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`)}},Ur=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);if(!t(this,Y,`f`))throw Error(`Final run has not been received`);return t(this,Y,`f`)},Wr=function(n){let[r,i]=t(this,G,`m`,Jr).call(this,n,t(this,J,`f`));e(this,J,r,`f`),t(this,Ir,`f`)[r.id]=r;for(let e of i){let t=r.content[e.index];t?.type==`text`&&this._emit(`textCreated`,t.text)}switch(n.event){case`thread.message.created`:this._emit(`messageCreated`,n.data);break;case`thread.message.in_progress`:break;case`thread.message.delta`:if(this._emit(`messageDelta`,n.data.delta,r),n.data.delta.content)for(let i of n.data.delta.content){if(i.type==`text`&&i.text){let e=i.text,t=r.content[i.index];if(t&&t.type==`text`)this._emit(`textDelta`,e,t.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(i.index!=t(this,Lr,`f`)){if(t(this,X,`f`))switch(t(this,X,`f`).type){case`text`:this._emit(`textDone`,t(this,X,`f`).text,t(this,J,`f`));break;case`image_file`:this._emit(`imageFileDone`,t(this,X,`f`).image_file,t(this,J,`f`))}e(this,Lr,i.index,`f`)}e(this,X,r.content[i.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(t(this,Lr,`f`)!==void 0){let e=n.data.content[t(this,Lr,`f`)];if(e)switch(e.type){case`image_file`:this._emit(`imageFileDone`,e.image_file,t(this,J,`f`));break;case`text`:this._emit(`textDone`,e.text,t(this,J,`f`))}}t(this,J,`f`)&&this._emit(`messageDone`,n.data),e(this,J,void 0,`f`)}},Gr=function(n){let r=t(this,G,`m`,qr).call(this,n);switch(e(this,Vr,r,`f`),n.event){case`thread.run.step.created`:this._emit(`runStepCreated`,n.data);break;case`thread.run.step.delta`:let i=n.data.delta;if(i.step_details&&i.step_details.type==`tool_calls`&&i.step_details.tool_calls&&r.step_details.type==`tool_calls`)for(let n of i.step_details.tool_calls)n.index==t(this,Rr,`f`)?this._emit(`toolCallDelta`,n,r.step_details.tool_calls[n.index]):(t(this,Z,`f`)&&this._emit(`toolCallDone`,t(this,Z,`f`)),e(this,Rr,n.index,`f`),e(this,Z,r.step_details.tool_calls[n.index],`f`),t(this,Z,`f`)&&this._emit(`toolCallCreated`,t(this,Z,`f`)));this._emit(`runStepDelta`,n.data.delta,r);break;case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:e(this,Vr,void 0,`f`),n.data.step_details.type==`tool_calls`&&t(this,Z,`f`)&&(this._emit(`toolCallDone`,t(this,Z,`f`)),e(this,Z,void 0,`f`)),this._emit(`runStepDone`,n.data,r)}},Kr=function(e){t(this,Fr,`f`).push(e),this._emit(`event`,e)},qr=function(e){switch(e.event){case`thread.run.step.created`:return t(this,q,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:let n=t(this,q,`f`)[e.data.id];if(!n)throw Error(`Received a RunStepDelta before creation of a snapshot`);let r=e.data;if(r.delta){let i=K.accumulateDelta(n,r.delta);t(this,q,`f`)[e.data.id]=i}return t(this,q,`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`:t(this,q,`f`)[e.data.id]=e.data}if(t(this,q,`f`)[e.data.id])return t(this,q,`f`)[e.data.id];throw Error(`No snapshot available`)},Jr=function(e,n){let r=[];switch(e.event){case`thread.message.created`:return[e.data,r];case`thread.message.delta`:if(!n)throw Error(`Received a delta with no existing snapshot (there should be one from message creation)`);let i=e.data;if(i.delta.content)for(let e of i.delta.content)if(e.index in n.content){let r=n.content[e.index];n.content[e.index]=t(this,G,`m`,Yr).call(this,e,r)}else n.content[e.index]=e,r.push(e);return[n,r];case`thread.message.in_progress`:case`thread.message.completed`:case`thread.message.incomplete`:if(n)return[n,r];throw Error(`Received thread message event with no existing snapshot`)}throw Error(`Tried to accumulate a non-message event`)},Yr=function(e,t){return K.accumulateDelta(t,e)},Xr=function(n){switch(e(this,Br,n.data,`f`),n.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`:e(this,Y,n.data,`f`),t(this,Z,`f`)&&(this._emit(`toolCallDone`,t(this,Z,`f`)),e(this,Z,void 0,`f`))}};var Qr=class extends N{constructor(){super(...arguments),this.steps=new Nr(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(P`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:U([{"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(P`/threads/${r}/runs/${e}`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(P`/threads/${r}/runs/${e}`,{body:i,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(P`/threads/${e}/runs`,k,{query:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(P`/threads/${r}/runs/${e}/cancel`,{...n,headers:U([{"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 Zr.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=U([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 de(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return Zr.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(P`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:U([{"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 Zr.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};Qr.Steps=Nr;var $r=class extends N{constructor(){super(...arguments),this.runs=new Qr(this._client),this.messages=new Mr(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(P`/threads/${e}`,{...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(P`/threads/${e}`,{body:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(P`/threads/${e}`,{...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:U([{"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 Zr.createThreadAssistantStream(e,this._client.beta.threads,t)}};$r.Runs=Qr,$r.Messages=Mr;var ei=class extends N{constructor(){super(...arguments),this.realtime=new Or(this._client),this.chatkit=new jr(this._client),this.assistants=new Tr(this._client),this.threads=new $r(this._client)}};ei.Realtime=Or,ei.ChatKit=jr,ei.Assistants=Tr,ei.Threads=$r;var ti=class extends N{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},ni=class extends N{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(P`/containers/${r}/files/${e}/content`,{...n,headers:U([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},ri=class extends N{constructor(){super(...arguments),this.content=new ni(this._client)}create(e,t,n){return this._client.post(P`/containers/${e}/files`,wt({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(P`/containers/${r}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(P`/containers/${e}/files`,k,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(P`/containers/${r}/files/${e}`,{...n,headers:U([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}};ri.Content=ni;var ii=class extends N{constructor(){super(...arguments),this.files=new ri(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(P`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/containers`,k,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(P`/containers/${e}`,{...t,headers:U([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}};ii.Files=ri;var ai=class extends N{create(e,t,n){let{include:r,...i}=t;return this._client.post(P`/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(P`/conversations/${r}/items/${e}`,{query:i,...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(P`/conversations/${e}/items`,A,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(P`/conversations/${r}/items/${e}`,{...n,__security:{bearerAuth:!0}})}},oi=class extends N{constructor(){super(...arguments),this.items=new ai(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(P`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(P`/conversations/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(P`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};oi.Items=ai;var si=class extends N{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&E(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:(E(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=Pr(t)}),e)))}},ci=class extends N{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(P`/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(P`/evals/${r}/runs/${e}/output_items`,k,{query:i,...n,__security:{bearerAuth:!0}})}},li=class extends N{constructor(){super(...arguments),this.outputItems=new ci(this._client)}create(e,t,n){return this._client.post(P`/evals/${e}/runs`,{body:t,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(P`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(P`/evals/${e}/runs`,k,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(P`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(P`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};li.OutputItems=ci;var ui=class extends N{constructor(){super(...arguments),this.runs=new li(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(P`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(P`/evals/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/evals`,k,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(P`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};ui.Runs=li;var di=class extends N{create(e,t){return this._client.post(`/files`,M({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(P`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/files`,k,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(P`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(P`/files/${e}/content`,{...t,headers:U([{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 de(t),a=await this.retrieve(e),Date.now()-i>n)throw new l({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}},fi=class extends N{},pi=class extends N{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}})}},mi=class extends N{constructor(){super(...arguments),this.graders=new pi(this._client)}};mi.Graders=pi;var hi=class extends N{create(e,t,n){return this._client.getAPIList(P`/fine_tuning/checkpoints/${e}/permissions`,O,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(P`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(P`/fine_tuning/checkpoints/${e}/permissions`,A,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(P`/fine_tuning/checkpoints/${r}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},gi=class extends N{constructor(){super(...arguments),this.permissions=new hi(this._client)}};gi.Permissions=hi;var _i=class extends N{list(e,t={},n){return this._client.getAPIList(P`/fine_tuning/jobs/${e}/checkpoints`,k,{query:t,...n,__security:{bearerAuth:!0}})}},vi=class extends N{constructor(){super(...arguments),this.checkpoints=new _i(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(P`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,k,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(P`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},n){return this._client.getAPIList(P`/fine_tuning/jobs/${e}/events`,k,{query:t,...n,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(P`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(P`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}};vi.Checkpoints=_i;var yi=class extends N{constructor(){super(...arguments),this.methods=new fi(this._client),this.jobs=new vi(this._client),this.checkpoints=new gi(this._client),this.alpha=new mi(this._client)}};yi.Methods=fi,yi.Jobs=vi,yi.Checkpoints=gi,yi.Alpha=mi;var bi=class extends N{},xi=class extends N{constructor(){super(...arguments),this.graderModels=new bi(this._client)}};xi.GraderModels=bi;var Si=class extends N{createVariation(e,t){return this._client.post(`/images/variations`,M({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post(`/images/edits`,M({body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,t){return this._client.post(`/images/generations`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},Ci=class extends N{retrieve(e,t){return this._client.get(P`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList(`/models`,O,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(P`/models/${e}`,{...t,__security:{bearerAuth:!0}})}},wi=class extends N{create(e,t){return this._client.post(`/moderations`,{body:e,...t,__security:{bearerAuth:!0}})}},Ti=class extends N{accept(e,t,n){return this._client.post(P`/realtime/calls/${e}/accept`,{body:t,...n,headers:U([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(P`/realtime/calls/${e}/hangup`,{...t,headers:U([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(P`/realtime/calls/${e}/refer`,{body:t,...n,headers:U([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},n){return this._client.post(P`/realtime/calls/${e}/reject`,{body:t,...n,headers:U([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}},Ei=class extends N{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t,__security:{bearerAuth:!0}})}},Di=class extends N{constructor(){super(...arguments),this.clientSecrets=new Ei(this._client),this.calls=new Ti(this._client)}};Di.ClientSecrets=Ei,Di.Calls=Ti;function Oi(e,t){return!t||!ji(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)}:ki(e,t)}function ki(e,t){let n=e.output.map(e=>{if(e.type===`function_call`)return{...e,parsed_arguments:Pi(t,e)};if(e.type===`message`){let n=e.content.map(e=>e.type===`output_text`?{...e,parsed:Ai(t,e.text)}:e);return{...e,content:n}}return e}),r=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,`output_text`)||Fi(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(let e of r.output)if(e.type===`message`){for(let t of e.content)if(t.type===`output_text`&&t.parsed!==null)return t.parsed}return null}}),r}function Ai(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function ji(e){return!!Ht(e.text?.format)}function Mi(e){return e?.$brand===`auto-parseable-tool`}function Ni(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function Pi(e,t){let n=Ni(e.tools??[],t.name);return{...t,...t,parsed_arguments:Mi(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function Fi(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 Ii,Li,Q,Ri,zi,Bi,Vi,Hi,Ui=class n extends pn{constructor(t){super(),Ii.add(this),Li.set(this,void 0),Q.set(this,void 0),Ri.set(this,void 0),e(this,Li,t,`f`)}static createResponse(e,t,r){let i=new n(t);return i._run(()=>i._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createOrRetrieveResponse(e,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),t(this,Ii,`m`,zi).call(this);let a,o=null;`response_id`in n?(a=await e.responses.retrieve(n.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=n.starting_after??null):a=await e.responses.create({...n,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let e of a)t(this,Ii,`m`,Bi).call(this,e,o);if(a.controller.signal?.aborted)throw new s;return t(this,Ii,`m`,Vi).call(this)}[(Li=new WeakMap,Q=new WeakMap,Ri=new WeakMap,Ii=new WeakSet,zi=function(){this.ended||e(this,Q,void 0,`f`)},Bi=function(e,n){if(this.ended)return;let r=(e,t)=>{(n==null||t.sequence_number>n)&&this._emit(e,t)},i=t(this,Ii,`m`,Hi).call(this,e);switch(r(`event`,e),e.type){case`response.output_text.delta`:{let t=i.output[e.output_index];if(!t)throw new a(`missing output at index ${e.output_index}`);if(t.type===`message`){let n=t.content[e.content_index];if(!n)throw new a(`missing content at index ${e.content_index}`);if(n.type!==`output_text`)throw new a(`expected content to be 'output_text', got ${n.type}`);r(`response.output_text.delta`,{...e,snapshot:n.text})}break}case`response.function_call_arguments.delta`:{let t=i.output[e.output_index];if(!t)throw new a(`missing output at index ${e.output_index}`);t.type===`function_call`&&r(`response.function_call_arguments.delta`,{...e,snapshot:t.arguments});break}default:r(e.type,e)}},Vi=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);let n=t(this,Q,`f`);if(!n)throw new a(`request ended without sending any events`);e(this,Q,void 0,`f`);let r=Wi(n,t(this,Li,`f`));return e(this,Ri,r,`f`),r},Hi=function(n){let r=t(this,Q,`f`);if(!r){if(n.type!==`response.created`)throw new a(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return r=e(this,Q,n.response,`f`),r}switch(n.type){case`response.output_item.added`:r.output.push(n.item);break;case`response.content_part.added`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);let t=e.type,i=n.part;t===`message`&&i.type!==`reasoning_text`?e.content.push(i):t===`reasoning`&&i.type===`reasoning_text`&&(e.content||=[],e.content.push(i));break}case`response.output_text.delta`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);if(e.type===`message`){let t=e.content[n.content_index];if(!t)throw new a(`missing content at index ${n.content_index}`);if(t.type!==`output_text`)throw new a(`expected content to be 'output_text', got ${t.type}`);t.text+=n.delta}break}case`response.function_call_arguments.delta`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);e.type===`function_call`&&(e.arguments+=n.delta);break}case`response.reasoning_text.delta`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);if(e.type===`reasoning`){let t=e.content?.[n.content_index];if(!t)throw new a(`missing content at index ${n.content_index}`);if(t.type!==`reasoning_text`)throw new a(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=n.delta}break}case`response.completed`:e(this,Q,n.response,`f`)}return r},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=t(this,Ri,`f`);if(!e)throw new a(`stream ended without producing a ChatCompletion`);return e}};function Wi(e,t){return Oi(e,t)}var Gi=class extends N{list(e,t={},n){return this._client.getAPIList(P`/responses/${e}/input_items`,k,{query:t,...n,__security:{bearerAuth:!0}})}},Ki=class extends N{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t,__security:{bearerAuth:!0}})}},qi=class extends N{constructor(){super(...arguments),this.inputItems=new Gi(this._client),this.inputTokens=new Ki(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`&&Fi(e),e))}retrieve(e,t={},n){return this._client.get(P`/responses/${e}`,{query:t,...n,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&Fi(e),e))}delete(e,t){return this._client.delete(P`/responses/${e}`,{...t,headers:U([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>ki(t,e))}stream(e,t){return Ui.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(P`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t,__security:{bearerAuth:!0}})}};qi.InputItems=Gi,qi.InputTokens=Ki;var Ji=class extends N{retrieve(e,t){return this._client.get(P`/skills/${e}/content`,{...t,headers:U([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},Yi=class extends N{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(P`/skills/${r}/versions/${e}/content`,{...n,headers:U([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},Xi=class extends N{constructor(){super(...arguments),this.content=new Yi(this._client)}create(e,t={},n){return this._client.post(P`/skills/${e}/versions`,wt({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(P`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(P`/skills/${e}/versions`,k,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(P`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};Xi.Content=Yi;var Zi=class extends N{constructor(){super(...arguments),this.content=new Ji(this._client),this.versions=new Xi(this._client)}create(e={},t){return this._client.post(`/skills`,wt({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(P`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(P`/skills/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/skills`,k,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(P`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};Zi.Content=Ji,Zi.Versions=Xi;var Qi=class extends N{create(e,t,n){return this._client.post(P`/uploads/${e}/parts`,M({body:t,...n,__security:{bearerAuth:!0}},this._client))}},$i=class extends N{constructor(){super(...arguments),this.parts=new Qi(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(P`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,n){return this._client.post(P`/uploads/${e}/complete`,{body:t,...n,__security:{bearerAuth:!0}})}};$i.Parts=Qi;var ea=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},ta=class extends N{create(e,t,n){return this._client.post(P`/vector_stores/${e}/file_batches`,{body:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(P`/vector_stores/${r}/file_batches/${e}`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(P`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(P`/vector_stores/${r}/file_batches/${e}/files`,k,{query:i,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,n){let r=U([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 de(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 ea(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c})}},na=class extends N{create(e,t,n){return this._client.post(P`/vector_stores/${e}/files`,{body:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(P`/vector_stores/${r}/files/${e}`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(P`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(P`/vector_stores/${e}/files`,k,{query:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(P`/vector_stores/${r}/files/${e}`,{...n,headers:U([{"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=U([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 de(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(P`/vector_stores/${r}/files/${e}/content`,O,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},ra=class extends N{constructor(){super(...arguments),this.files=new na(this._client),this.fileBatches=new ta(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(P`/vector_stores/${e}`,{...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(P`/vector_stores/${e}`,{body:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/vector_stores`,k,{query:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(P`/vector_stores/${e}`,{...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,n){return this._client.getAPIList(P`/vector_stores/${e}/search`,O,{body:t,method:`post`,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}};ra.Files=na,ra.FileBatches=ta;var ia=class extends N{create(e,t){return this._client.post(`/videos`,M({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(P`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/videos`,A,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(P`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post(`/videos/characters`,M({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},n){return this._client.get(P`/videos/${e}/content`,{query:t,...n,headers:U([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post(`/videos/edits`,M({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post(`/videos/extensions`,M({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(P`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,n){return this._client.post(P`/videos/${e}/remix`,wt({body:t,...n,__security:{bearerAuth:!0}},this._client))}},aa,oa,sa,ca=class extends N{constructor(){super(...arguments),aa.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,n,r=this._client.webhookSecret,i=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");t(this,aa,`m`,oa).call(this,r);let a=U([n]).values,o=t(this,aa,`m`,sa).call(this,a,`webhook-signature`),s=t(this,aa,`m`,sa).call(this,a,`webhook-timestamp`),c=t(this,aa,`m`,sa).call(this,a,`webhook-id`),l=parseInt(s,10);if(isNaN(l))throw new b(`Invalid webhook timestamp format`);let u=Math.floor(Date.now()/1e3);if(u-l>i)throw new b(`Webhook timestamp is too old`);if(l>u+i)throw new b(`Webhook timestamp is too new`);let d=o.split(` `).map(e=>e.startsWith(`v1,`)?e.substring(3):e),f=r.startsWith(`whsec_`)?Buffer.from(r.replace(`whsec_`,``),`base64`):Buffer.from(r,`utf-8`),p=c?`${c}.${s}.${e}`:`${s}.${e}`,m=await crypto.subtle.importKey(`raw`,f,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);for(let e of d)try{let t=Buffer.from(e,`base64`);if(await crypto.subtle.verify(`HMAC`,m,t,new TextEncoder().encode(p)))return}catch{continue}throw new b(`The given webhook signature does not match the expected signature`)}};aa=new WeakSet,oa=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`)},sa=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 la,ua,da,fa,pa=`workload-identity-auth`,$=class{constructor({baseURL:t=W(`OPENAI_BASE_URL`),apiKey:n=W(`OPENAI_API_KEY`)??null,adminAPIKey:r=W(`OPENAI_ADMIN_KEY`)??null,organization:i=W(`OPENAI_ORG_ID`)??null,project:o=W(`OPENAI_PROJECT_ID`)??null,webhookSecret:s=W(`OPENAI_WEBHOOK_SECRET`)??null,workloadIdentity:c,...l}={}){la.add(this),da.set(this,void 0),this.completions=new ti(this),this.chat=new Wn(this),this.embeddings=new si(this),this.files=new di(this),this.images=new Si(this),this.audio=new Cr(this),this.moderations=new wi(this),this.models=new Ci(this),this.fineTuning=new yi(this),this.graders=new xi(this),this.vectorStores=new ra(this),this.webhooks=new ca(this),this.beta=new ei(this),this.batches=new wr(this),this.uploads=new $i(this),this.admin=new _r(this),this.responses=new qi(this),this.realtime=new Di(this),this.conversations=new oi(this),this.evals=new ui(this),this.containers=new ii(this),this.skills=new Zi(this),this.videos=new ia(this);let u={apiKey:n,adminAPIKey:r,organization:i,project:o,webhookSecret:s,workloadIdentity:c,...l,baseURL:t||`https://api.openai.com/v1`};if(n&&c)throw new a("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!n&&!r&&!c)throw new a("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!u.dangerouslyAllowBrowser&&pe())throw new a(`It looks like you're running in a browser-like environment.
|
|
8
|
+
|
|
9
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
10
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
11
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
12
|
+
|
|
13
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
14
|
+
|
|
15
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
16
|
+
`);this.baseURL=u.baseURL,this.timeout=u.timeout??ua.DEFAULT_TIMEOUT,this.logger=u.logger??console;let d=`warn`;this.logLevel=d,this.logLevel=$e(u.logLevel,`ClientOptions.logLevel`,this)??$e(W(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??d,this.fetchOptions=u.fetchOptions,this.maxRetries=u.maxRetries??2,this.fetch=u.fetch??xe(),e(this,da,Ee,`f`);let f=W(`OPENAI_CUSTOM_HEADERS`);if(f){let e={};for(let t of f.split(`
|
|
17
|
+
`)){let n=t.indexOf(`:`);n>=0&&(e[t.substring(0,n).trim()]=t.substring(n+1).trim())}u.defaultHeaders=U([e,u.defaultHeaders])}this._options=u,c&&(this._workloadIdentityAuth=new yt(c,this.fetch)),this.apiKey=typeof n==`string`?n:null,this.adminAPIKey=r,this.organization=i,this.project=o,this.webhookSecret=s}withOptions(e){return new this.constructor({...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,...e})}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 U([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return U([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return U([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return U([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Ue(e)}getUserAgent(){return`${this.constructor.name}/JS ${fe}`}defaultIdempotencyKey(){return`stainless-node-retry-${n()}`}makeStatusError(e,t,n,r){return o.generate(e,t,n,r)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!=`function`)return!1;let t;try{t=await e()}catch(e){throw e instanceof a?e:new a(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof t!=`string`||!t)throw new a(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,n,r){let i=!t(this,la,`m`,fa).call(this)&&r||this.baseURL,a=re(e)?new URL(e):new URL(i+(i.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),o=this.defaultQuery(),s=Object.fromEntries(a.searchParams);return(!oe(o)||!oe(s))&&(n={...s,...o,...n}),typeof n==`object`&&n&&!Array.isArray(n)&&(a.search=this.stringifyQuery(n)),a.toString()}async prepareOptions(e){(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 new pt(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let a=await e,o=a.maxRetries??this.maxRetries;t??=o,await this.prepareOptions(a);let{req:u,url:d,timeout:f}=await this.buildRequest(a,{retryCount:o-t});await this.prepareRequest(u,{url:d,options:a});let p=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),m=n===void 0?``:`, retryOf: ${n}`,h=Date.now();if(E(this).debug(`[${p}] sending request`,D({retryOfRequestLogID:n,method:a.method,url:d,options:a,headers:u.headers})),a.signal?.aborted)throw new s;let g=a.__security??{bearerAuth:!0},_=new AbortController,v=await this.fetchWithAuth(d,u,f,_,g).catch(i),y=Date.now();if(v instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(a.signal?.aborted)throw new s;let i=r(v)||/timed? ?out/i.test(String(v)+(`cause`in v?String(v.cause):``));if(t)return E(this).info(`[${p}] connection ${i?`timed out`:`failed`} - ${e}`),E(this).debug(`[${p}] connection ${i?`timed out`:`failed`} (${e})`,D({retryOfRequestLogID:n,url:d,durationMs:y-h,message:v.message})),this.retryRequest(a,t,n??p);throw E(this).info(`[${p}] connection ${i?`timed out`:`failed`} - error; no more retries left`),E(this).debug(`[${p}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,D({retryOfRequestLogID:n,url:d,durationMs:y-h,message:v.message})),v instanceof ee||v instanceof te?v:i?new l:new c({message:ma(v),cause:v})}let b=`[${p}${m}${[...v.headers.entries()].filter(([e])=>e===`x-request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${u.method} ${d} ${v.ok?`succeeded`:`failed`} with status ${v.status} in ${y-h}ms`;if(!v.ok){if(v.status===401&&this._workloadIdentityAuth&&g.bearerAuth&&!a.__metadata?.hasStreamingBody&&!a.__metadata?.workloadIdentityTokenRefreshed)return await Te(v.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...a,__metadata:{...a.__metadata,workloadIdentityTokenRefreshed:!0}},t,n??p);let e=await this.shouldRetry(v);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await Te(v.body),E(this).info(`${b} - ${e}`),E(this).debug(`[${p}] response error (${e})`,D({retryOfRequestLogID:n,url:v.url,status:v.status,headers:v.headers,durationMs:y-h})),this.retryRequest(a,t,n??p,v.headers)}let r=e?`error; no more retries left`:`error; not retryable`;E(this).info(`${b} - ${r}`);let o=await v.text().catch(e=>i(e).message),s=ue(o),c=s?void 0:o;throw E(this).debug(`[${p}] response error (${r})`,D({retryOfRequestLogID:n,url:v.url,status:v.status,headers:v.headers,message:c,durationMs:Date.now()-h})),this.makeStatusError(v.status,s,c,v.headers)}return E(this).info(b),E(this).debug(`[${p}] response start`,D({retryOfRequestLogID:n,url:v.url,status:v.status,headers:v.headers,durationMs:y-h})),{response:v,options:a,controller:_,requestLogID:p,retryOfRequestLogID:n,startTime:h}}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);return new gt(this,n,e)}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 ${pa}`){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);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}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){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await de(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&&le(`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=U([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...be(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a,e.__security??{bearerAuth:!0}),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let r=U([n]),i=globalThis.ReadableStream!==void 0&&e instanceof globalThis.ReadableStream,a=!i&&(typeof e==`string`||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||globalThis.Blob!==void 0&&e instanceof globalThis.Blob||e instanceof URLSearchParams||e instanceof FormData);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&r.values.has(`content-type`)||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||i?{bodyHeaders:void 0,body:e,isStreamingBody:!a}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:Ce(e),isStreamingBody:!0}:typeof e==`object`&&r.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(e),isStreamingBody:!1}:{...t(this,da,`f`).call(this,{body:e,headers:r}),isStreamingBody:!1}}};ua=$,da=new WeakMap,la=new WeakSet,fa=function(){return this.baseURL!==`https://api.openai.com/v1`},$.OpenAI=ua,$.DEFAULT_TIMEOUT=6e5,$.OpenAIError=a,$.APIError=o,$.APIConnectionError=c,$.APIConnectionTimeoutError=l,$.APIUserAbortError=s,$.NotFoundError=p,$.ConflictError=m,$.RateLimitError=g,$.BadRequestError=u,$.AuthenticationError=d,$.InternalServerError=_,$.PermissionDeniedError=f,$.UnprocessableEntityError=h,$.InvalidWebhookSignatureError=b,$.toFile=Ft,$.Completions=ti,$.Chat=Wn,$.Embeddings=si,$.Files=di,$.Images=Si,$.Audio=Cr,$.Moderations=wi,$.Models=Ci,$.FineTuning=yi,$.Graders=xi,$.VectorStores=ra,$.Webhooks=ca,$.Beta=ei,$.Batches=wr,$.Uploads=$i,$.Admin=_r,$.Responses=qi,$.Realtime=Di,$.Conversations=oi,$.Evals=ui,$.Containers=ii,$.Skills=Zi,$.Videos=ia;function ma(e){if(ha(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 ha(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 ga=class extends ${constructor({baseURL:e=W(`OPENAI_BASE_URL`),apiKey:t=W(`AZURE_OPENAI_API_KEY`),apiVersion:n=W(`OPENAI_API_VERSION`),endpoint:r,deployment:i,azureADTokenProvider:o,dangerouslyAllowBrowser:s,...c}={}){if(!n)throw new a(`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 o==`function`&&(s=!0),!o&&!t)throw new a("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&t)throw new a("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(c.defaultQuery={...c.defaultQuery,"api-version":n},!e){if(r||={}.AZURE_OPENAI_ENDPOINT,!r)throw new a("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${r}/openai`}else if(r)throw new a(`baseURL and endpoint are mutually exclusive`);super({apiKey:o??t,baseURL:e,...c,...s===void 0?{}:{dangerouslyAllowBrowser:s}}),this.apiVersion=``,this.apiVersion=n,this.deploymentName=i}async buildRequest(e,t={}){if(_a.has(e.path)&&e.method===`post`&&e.body!==void 0){if(!ce(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=`/deployments/${t}${e.path}`)}return super.buildRequest(e,t)}async authHeaders(e,t){let n=t??{bearerAuth:!0,adminAPIKeyAuth:!0};return n.bearerAuth&&typeof this._options.apiKey==`string`?U([{"api-key":this.apiKey}]):super.authHeaders(e,n)}},_a=new Set([`/completions`,`/chat/completions`,`/embeddings`,`/audio/transcriptions`,`/audio/translations`,`/audio/speech`,`/images/generations`,`/batches`,`/images/edits`]);export{$ as n,ga as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{H as e,d as t}from"./account-store-
|
|
1
|
+
import{H as e,d as t}from"./account-store-Bwe7JMH-.js";import{a as n}from"./diagnostics-DN_idNHx.js";import{p as r}from"./bedrock-camp-B0KF_4RS.js";import{n as i,o as a}from"./legacy-api-aliases-nSD9C16V.js";import"./provider-settings-BkIna1v7.js";import{n as o,r as s,t as c}from"./pkce-hGf_TEnP.js";const l=`openai-codex`,u=`app_EMoamEEZ73f0CkXaXp7hrann`,d=`https://auth.openai.com/oauth/token`,f=`http://localhost:1455/auth/callback`,p=`https://chatgpt.com/backend-api`,m=`openai-codex-responses`,h=`${l}-openai`,g={xhigh:`xhigh`,minimal:`low`},_=[{id:`gpt-5.5`,name:`GPT-5.5`,input:[`text`,`image`]},{id:`gpt-5.4`,name:`GPT-5.4`,input:[`text`,`image`]},{id:`gpt-5.4-mini`,name:`GPT-5.4 mini`,input:[`text`,`image`]},{id:`gpt-5.3-codex`,name:`GPT-5.3 Codex`,input:[`text`,`image`]},{id:`gpt-5.3-codex-spark`,name:`GPT-5.3 Codex Spark`,input:[`text`]},{id:`gpt-5.2`,name:`GPT-5.2`,input:[`text`,`image`]}].map(e=>({...e,api:`openai`,reasoning:!0,context_window:272e3,max_tokens:128e3,thinkingLevelMap:g}));async function v(e,t){let n=new URLSearchParams({grant_type:`authorization_code`,client_id:u,code:e,code_verifier:t,redirect_uri:f}),r=await fetch(d,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:n});if(!r.ok)throw Error(`OpenAI Codex token exchange failed: ${r.status} ${await r.text()}`);let i=await r.json();if(!i.access_token)throw Error(`OpenAI Codex token exchange did not return access_token.`);return i}async function y(e){try{let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e,client_id:u}),n=await fetch(d,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});return n.ok?await n.json():(console.error(`[openai-codex] refresh failed:`,n.status,await n.text()),null)}catch(e){return console.error(`[openai-codex] refresh error:`,e instanceof Error?e.message:String(e)),null}}function b(e){try{let t=e.split(`.`);if(t.length!==3)return;let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`);return n.length%4&&(n+=`=`.repeat(4-n.length%4)),JSON.parse(atob(n))}catch{return}}function x(e){let t=b(e)?.[`https://api.openai.com/profile`];return typeof t?.email==`string`?t.email:void 0}function S(e){let t=b(e)?.[`https://api.openai.com/auth`],n=x(e),r=typeof t?.chatgpt_plan_type==`string`?t.chatgpt_plan_type:void 0,i=r?r.charAt(0).toUpperCase()+r.slice(1):void 0;if(n&&i)return`${n} (${i})`;if(n)return n;if(i)return`ChatGPT ${i}`}async function C(e){let t=x(e);if(t)try{let e=t.trim().toLowerCase(),n=new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)));return`https://www.gravatar.com/avatar/${Array.from(n).map(e=>e.toString(16).padStart(2,`0`)).join(``)}?s=128&d=404`}catch{return}}function w(){return t().find(e=>e.providerId===l)}async function T(){let t=w();if(!t?.accessToken)throw Error("Not signed in to OpenAI Codex — run `oauth-token openai-codex` or /login");let n=t.tokenExpiresAt??0;if(n&&Date.now()+6e4<n)return t.accessToken;if(t.refreshToken){let n=await y(t.refreshToken);if(n?.access_token)return await e({providerId:l,accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,tokenExpiresAt:Date.now()+(n.expires_in??3600)*1e3,baseUrl:p,userName:S(n.access_token),userAvatar:await C(n.access_token),scopes:n.scope??t.scopes}),n.access_token}return t.accessToken}function E(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:h,provider:l,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:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}const D=(e,t,r={})=>{let a=n();return(async()=>{try{let n=await T(),o={...e,baseUrl:p,api:m},s=i(o,t,{...r,apiKey:n,transport:`sse`});for await(let e of s)a.push(e);a.end()}catch(t){console.error(`[openai-codex] Stream error:`,t instanceof Error?t.message:String(t)),a.push(E(e,t)),a.end()}})(),a},O=(e,t,r)=>{let i=n();return(async()=>{try{let n=await T(),o={...e,baseUrl:p,api:m},s=a(o,t,{...r,apiKey:n,transport:`sse`});for await(let e of s)i.push(e);i.end()}catch(t){console.error(`[openai-codex] Stream error:`,t instanceof Error?t.message:String(t)),i.push(E(e,t)),i.end()}})(),i},k={id:l,name:`OpenAI Codex (ChatGPT Subscription)`,description:`GPT-5 Codex via your ChatGPT Plus/Pro/Business subscription — OAuth login, no API key needed. Default model is GPT-5.5.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`gpt-5.5`,oauthTokenDomains:[`chatgpt.com`,`*.chatgpt.com`,`auth.openai.com`,`api.openai.com`],getModelIds:()=>_,onOAuthLoginIntercepted:async(t,n,r)=>{let i=o(),a=await c(i),d=s(),m=new URL(`https://auth.openai.com/oauth/authorize`);m.searchParams.set(`response_type`,`code`),m.searchParams.set(`client_id`,u),m.searchParams.set(`redirect_uri`,f),m.searchParams.set(`scope`,r?.scopes??`openid profile email offline_access`),m.searchParams.set(`code_challenge`,a),m.searchParams.set(`code_challenge_method`,`S256`),m.searchParams.set(`state`,d),m.searchParams.set(`id_token_add_organizations`,`true`),m.searchParams.set(`codex_cli_simplified_flow`,`true`),m.searchParams.set(`originator`,`pi`);let h=await t({authorizeUrl:m.toString(),redirectUriPattern:`http://localhost:1455/auth/callback*`,onCapture:`close`});if(!h)throw Error(`OpenAI Codex OAuth login was cancelled or timed out`);let g=new URL(h),_=g.searchParams.get(`code`),y=g.searchParams.get(`state`);if(!_)throw Error(`OpenAI Codex OAuth redirect did not include a code`);if(y!==d)throw Error(`OpenAI Codex OAuth state mismatch — possible CSRF, aborting`);let b=await v(_,i);await e({providerId:l,accessToken:b.access_token,refreshToken:b.refresh_token,tokenExpiresAt:Date.now()+(b.expires_in??3600)*1e3,baseUrl:p,userName:S(b.access_token),userAvatar:await C(b.access_token),scopes:b.scope}),n()},onOAuthLogout:async()=>{await e({providerId:l,accessToken:``})},onSilentRenew:async()=>{let t=w();if(!t?.refreshToken)return null;let n=await y(t.refreshToken);return n?.access_token?(await e({providerId:l,accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,tokenExpiresAt:Date.now()+(n.expires_in??3600)*1e3,baseUrl:p,userName:S(n.access_token),userAvatar:await C(n.access_token),scopes:n.scope??t.scopes}),n.access_token):null}};function A(){r({api:h,stream:D,streamSimple:O})}export{k as config,A as register};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{H as e,d as t}from"./account-store-
|
|
1
|
+
import{H as e,d as t}from"./account-store-Ch65aCFb.js";import{a as n}from"./diagnostics-DN_idNHx.js";import{p as r}from"./bedrock-camp-qpZqnqLa.js";import{n as i,o as a}from"./legacy-api-aliases-CsTVszvY.js";import"./provider-settings-DrEGQ7ef.js";import{n as o,r as s,t as c}from"./pkce-hGf_TEnP.js";var l=`openai-codex`,u=`app_EMoamEEZ73f0CkXaXp7hrann`,d=`https://auth.openai.com/oauth/authorize`,f=`https://auth.openai.com/oauth/token`,p=`openid profile email offline_access`,m=`http://localhost:1455/auth/callback`,h=`http://localhost:1455/auth/callback*`,g=`https://chatgpt.com/backend-api`,_=`openai-codex-responses`,v=`${l}-openai`,y={xhigh:`xhigh`,minimal:`low`},b=[{id:`gpt-5.5`,name:`GPT-5.5`,input:[`text`,`image`]},{id:`gpt-5.4`,name:`GPT-5.4`,input:[`text`,`image`]},{id:`gpt-5.4-mini`,name:`GPT-5.4 mini`,input:[`text`,`image`]},{id:`gpt-5.3-codex`,name:`GPT-5.3 Codex`,input:[`text`,`image`]},{id:`gpt-5.3-codex-spark`,name:`GPT-5.3 Codex Spark`,input:[`text`]},{id:`gpt-5.2`,name:`GPT-5.2`,input:[`text`,`image`]}].map(e=>({...e,api:`openai`,reasoning:!0,context_window:272e3,max_tokens:128e3,thinkingLevelMap:y}));async function x(e,t){let n=new URLSearchParams({grant_type:`authorization_code`,client_id:u,code:e,code_verifier:t,redirect_uri:m}),r=await fetch(f,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:n});if(!r.ok)throw Error(`OpenAI Codex token exchange failed: ${r.status} ${await r.text()}`);let i=await r.json();if(!i.access_token)throw Error(`OpenAI Codex token exchange did not return access_token.`);return i}async function S(e){try{let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e,client_id:u}),n=await fetch(f,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});return n.ok?await n.json():(console.error(`[openai-codex] refresh failed:`,n.status,await n.text()),null)}catch(e){return console.error(`[openai-codex] refresh error:`,e instanceof Error?e.message:String(e)),null}}function C(e){try{let t=e.split(`.`);if(t.length!==3)return;let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`);return n.length%4&&(n+=`=`.repeat(4-n.length%4)),JSON.parse(atob(n))}catch{return}}function w(e){let t=C(e)?.[`https://api.openai.com/profile`];return typeof t?.email==`string`?t.email:void 0}function T(e){let t=C(e)?.[`https://api.openai.com/auth`],n=w(e),r=typeof t?.chatgpt_plan_type==`string`?t.chatgpt_plan_type:void 0,i=r?r.charAt(0).toUpperCase()+r.slice(1):void 0;if(n&&i)return`${n} (${i})`;if(n)return n;if(i)return`ChatGPT ${i}`}async function E(e){let t=w(e);if(t)try{let e=t.trim().toLowerCase(),n=new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)));return`https://www.gravatar.com/avatar/${Array.from(n).map(e=>e.toString(16).padStart(2,`0`)).join(``)}?s=128&d=404`}catch{return}}function D(){return t().find(e=>e.providerId===l)}async function O(){let t=D();if(!t?.accessToken)throw Error("Not signed in to OpenAI Codex — run `oauth-token openai-codex` or /login");let n=t.tokenExpiresAt??0;if(n&&Date.now()+6e4<n)return t.accessToken;if(t.refreshToken){let n=await S(t.refreshToken);if(n?.access_token)return await e({providerId:l,accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,tokenExpiresAt:Date.now()+(n.expires_in??3600)*1e3,baseUrl:g,userName:T(n.access_token),userAvatar:await E(n.access_token),scopes:n.scope??t.scopes}),n.access_token}return t.accessToken}function k(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:v,provider:l,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:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}var A=(e,t,r={})=>{let a=n();return(async()=>{try{let n=await O(),o={...e,baseUrl:g,api:_},s=i(o,t,{...r,apiKey:n,transport:`sse`});for await(let e of s)a.push(e);a.end()}catch(t){console.error(`[openai-codex] Stream error:`,t instanceof Error?t.message:String(t)),a.push(k(e,t)),a.end()}})(),a},j=(e,t,r)=>{let i=n();return(async()=>{try{let n=await O(),o={...e,baseUrl:g,api:_},s=a(o,t,{...r,apiKey:n,transport:`sse`});for await(let e of s)i.push(e);i.end()}catch(t){console.error(`[openai-codex] Stream error:`,t instanceof Error?t.message:String(t)),i.push(k(e,t)),i.end()}})(),i},M={id:l,name:`OpenAI Codex (ChatGPT Subscription)`,description:`GPT-5 Codex via your ChatGPT Plus/Pro/Business subscription — OAuth login, no API key needed. Default model is GPT-5.5.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`gpt-5.5`,oauthTokenDomains:[`chatgpt.com`,`*.chatgpt.com`,`auth.openai.com`,`api.openai.com`],getModelIds:()=>b,onOAuthLoginIntercepted:async(t,n,r)=>{let i=o(),a=await c(i),f=s(),_=new URL(d);_.searchParams.set(`response_type`,`code`),_.searchParams.set(`client_id`,u),_.searchParams.set(`redirect_uri`,m),_.searchParams.set(`scope`,r?.scopes??p),_.searchParams.set(`code_challenge`,a),_.searchParams.set(`code_challenge_method`,`S256`),_.searchParams.set(`state`,f),_.searchParams.set(`id_token_add_organizations`,`true`),_.searchParams.set(`codex_cli_simplified_flow`,`true`),_.searchParams.set(`originator`,`pi`);let v=await t({authorizeUrl:_.toString(),redirectUriPattern:h,onCapture:`close`});if(!v)throw Error(`OpenAI Codex OAuth login was cancelled or timed out`);let y=new URL(v),b=y.searchParams.get(`code`),S=y.searchParams.get(`state`);if(!b)throw Error(`OpenAI Codex OAuth redirect did not include a code`);if(S!==f)throw Error(`OpenAI Codex OAuth state mismatch — possible CSRF, aborting`);let C=await x(b,i);await e({providerId:l,accessToken:C.access_token,refreshToken:C.refresh_token,tokenExpiresAt:Date.now()+(C.expires_in??3600)*1e3,baseUrl:g,userName:T(C.access_token),userAvatar:await E(C.access_token),scopes:C.scope}),n()},onOAuthLogout:async()=>{await e({providerId:l,accessToken:``})},onSilentRenew:async()=>{let t=D();if(!t?.refreshToken)return null;let n=await S(t.refreshToken);return n?.access_token?(await e({providerId:l,accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,tokenExpiresAt:Date.now()+(n.expires_in??3600)*1e3,baseUrl:g,userName:T(n.access_token),userAvatar:await E(n.access_token),scopes:n.scope??t.scopes}),n.access_token):null}};function N(){r({api:v,stream:A,streamSimple:j})}export{M as config,N as register};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{i as e,n as t,r as n,t as r}from"./diagnostics-DN_idNHx.js";import{c as i,i as a}from"./transform-messages-DEFauvrq.js";import{t as o}from"./provider-env-CILujRmO.js";import{t as s}from"./deferred-tools-DNuoafg8.js";import{t as c}from"./headers-CbDaTl3c.js";import{t as l}from"./pi-user-agent-BlGZrXbX.js";import{n as u}from"./constrained-sampling-BNmnoM-i.js";import{n as d,t as f}from"./error-body-pkrba6pf.js";import{t as p}from"./openai-prompt-cache-DXo9f3w5.js";import{n as m,r as h,t as g}from"./openai-responses-shared-DxcsuzHF.js";const _=new Set;function v(e){return _.add(e),()=>{_.delete(e)}}let y=-1/0,b=0;function x(e){if(globalThis.crypto?.getRandomValues){globalThis.crypto.getRandomValues(e);return}for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}function S(){let e=new Uint8Array(16);x(e);let t=Date.now();t>y?(b=e[6]*16777216+e[7]*65536+e[8]*256+e[9],y=t):(b=b+1>>>0,b===0&&y++);let n=new Uint8Array(16);n[0]=y/1099511627776&255,n[1]=y/4294967296&255,n[2]=y/16777216&255,n[3]=y/65536&255,n[4]=y/256&255,n[5]=y&255,n[6]=112|b>>>28&15,n[7]=b>>>20&255,n[8]=128|b>>>14&63,n[9]=b>>>6&255,n[10]=(b&63)<<2|e[10]&3,n[11]=e[11],n[12]=e[12],n[13]=e[13],n[14]=e[14],n[15]=e[15];let r=Array.from(n,e=>e.toString(16).padStart(2,`0`));return`${r.slice(0,4).join(``)}-${r.slice(4,6).join(``)}-${r.slice(6,8).join(``)}-${r.slice(8,10).join(``)}-${r.slice(10,16).join(``)}`}function C(e){let t=e.filter(e=>e!==void 0);if(t.length===0)return{cleanup:()=>{}};if(t.length===1)return{signal:t[0],cleanup:()=>{}};let n=new AbortController,r=[],i=e=>{n.signal.aborted||n.abort(e.reason)};for(let e of t){if(e.aborted){i(e);break}let t=()=>i(e);e.addEventListener(`abort`,t,{once:!0}),r.push({signal:e,listener:t})}return{signal:n.signal,cleanup:()=>{for(let{signal:e,listener:t}of r)e.removeEventListener(`abort`,t)}}}const w={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function T(e,t){let n=e.toLowerCase(),r=e.toUpperCase();return t?.[n]||t?.[r]||o(n)||o(r)||``}function E(e){if(e instanceof URL)return e;try{return new URL(e)}catch{return}}function D(e,t,n){let r=T(`no_proxy`,n).toLowerCase();return!r||r!==`*`&&r.split(/[,\s]/).every(n=>{if(!n)return!0;let r=n.match(/^(.+):(\d+)$/),i=r?r[1]:n,a=r?Number.parseInt(r[2],10):0;return a&&a!==t?!0:/^[.*]/.test(i)?(i.startsWith(`*`)&&(i=i.slice(1)),!e.endsWith(i)):e!==i})}function O(e,t){let n=E(e);if(!n?.protocol||!n.host)return``;let r=n.protocol.split(`:`,1)[0];if(!D(n.host.replace(/:\d*$/,``),Number.parseInt(n.port,10)||w[r]||0,t))return``;let i=T(`${r}_proxy`,t)||T(`all_proxy`,t);return i&&!i.includes(`://`)&&(i=`${r}://${i}`),i}function k(e,t){let n=O(e,t);if(!n)return;let r;try{r=new URL(n)}catch(e){throw Error(`Invalid proxy URL ${JSON.stringify(n)}: ${e instanceof Error?e.message:String(e)}`)}if(r.protocol!==`http:`&&r.protocol!==`https:`)throw Error(`Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL. Got ${r.protocol}`);return r}const A=1e3,j=new Set([`openai`,`openai-codex`,`opencode`]),M=new Set([`completed`,`incomplete`,`failed`,`cancelled`,`queued`,`in_progress`]);function N(e){if(e.stopReason===`pending`)throw Error(`Codex stream ended without a stop reason`);if(e.stopReason===`error`||e.stopReason===`aborted`)throw Error(e.errorMessage||`An unknown error occurred`)}function P(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function ee(e,t){return e===429&&P(t)?!1:e===429||e===500||e===502||e===503||e===504||/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function te(e){let t=e.get(`retry-after-ms`);if(t!==null){let e=Number(t);if(Number.isFinite(e))return Math.max(0,e)}let n=e.get(`retry-after`);if(!n)return;let r=Number(n);if(Number.isFinite(r))return Math.max(0,r*1e3);let i=Date.parse(n);if(!Number.isNaN(i))return Math.max(0,i-Date.now())}var F=class extends Error{};function ne(e,t){let n=t?.maxRetryDelayMs??6e4;if(n>0&&e>n)throw new F(`Server requested ${Math.ceil(e/1e3)}s retry delay (max: ${Math.ceil(n/1e3)}s)`);return e}function re(e,t){return new Promise((n,r)=>{if(t?.aborted){r(Error(`Request was aborted`));return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`Request was aborted`))})})}function ie(e){if(e!==void 0){if(!Number.isFinite(e)||e<0)throw Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}}function ae(){return typeof process>`u`||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.(`node:zlib`)??null}function oe(e){let t=ae();if(!t||typeof t.zstdCompressSync!=`function`)return null;try{let n=t.zstdCompressSync(e,{params:{[t.constants.ZSTD_c_compressionLevel]:3}});return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}catch{return null}}const I=(n,i,a)=>{let o=new e;return(async()=>{let e={role:`assistant`,content:[],api:`openai-codex-responses`,provider:n.provider,model:n.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`pending`,timestamp:Date.now()};try{let s=a?.apiKey;if(!s)throw Error(`No API key for provider: ${n.provider}`);let l=ze(s),d=u(i.tools,n.compat?.supportsOpenAIGrammarTools??!1),f=a?.cacheRetention===`none`?void 0:a?.sessionId,m=p(f),h=ce(n,i,a,m,d),g=await a?.onPayload?.(h,n);g!==void 0&&(h=g);let _=m||S(),v=Ve(n.headers,a?.headers,l,s,m),y=He(n.headers,a?.headers,l,s,_),b=JSON.stringify(h),x=ie(a?.timeoutMs),w=ie(a?.websocketConnectTimeoutMs),T=a?.transport||`auto`,E=!1,D=T!==`sse`&&J(f);if(D&&Y(f),T!==`sse`&&!D){let i=!1,s=!1,c=!1;for(;;){i=!1;try{if(await Le(ue(n.baseUrl),h,y,e,o,n,()=>{i=!0,E||(E=!0,o.push({type:`start`,partial:e}))},x,w,f,l,d,a),a?.signal?.aborted)throw Error(`Request was aborted`);N(e),o.push({type:`done`,reason:e.stopReason,message:e}),o.end();return}catch(n){let o=a?.signal?.aborted,l=!i&&pe(n),u=me(n);if(!o&&u&&!c){c=!0;continue}if(!o&&l&&!s){s=!0;continue}if(o||fe(n)&&!l||(r(e,t(`provider_transport_failure`,n,{configuredTransport:T,fallbackTransport:i?void 0:`sse`,eventsEmitted:i,phase:i?`after_message_stream_start`:`before_message_stream_start`,requestBytes:new TextEncoder().encode(b).byteLength})),be(f,n),i))throw n;Y(f);break}}}let O=oe(b);O&&v.set(`content-encoding`,`zstd`);let k=O??b,j,M,P=a?.maxRetries??0;for(let e=0;e<=P;e++){if(a?.signal?.aborted)throw Error(`Request was aborted`);try{let t=x!==void 0&&x>0?AbortSignal.timeout(x):void 0,r=C([a?.signal,t]);try{j=await(a?.fetch??globalThis.fetch)(z(n.baseUrl),{method:`POST`,headers:v,body:k,signal:r.signal})}catch(e){throw t?.aborted&&!a?.signal?.aborted?Error(`Codex SSE response headers timed out after ${x}ms`):e}finally{r.cleanup()}if(await a?.onResponse?.({status:j.status,headers:c(j.headers)},n),j.ok)break;let i=await j.text();if(e<P&&ee(j.status,i)){let t=te(j.headers);await re(t===void 0?A*2**e:ne(t,a),a?.signal);continue}let o=await Re(new Response(i,{status:j.status,statusText:j.statusText}));throw Error(o.friendlyMessage||o.message)}catch(t){if(t instanceof Error&&(t.name===`AbortError`||t.message===`Request was aborted`))throw Error(`Request was aborted`);if(M=t instanceof Error?t:Error(String(t)),e<P&&!(M instanceof F)&&!M.message.includes(`usage limit`)){await re(A*2**e,a?.signal);continue}throw M}}if(!j?.ok)throw M??Error(`Failed after retries`);if(!j.body)throw Error(`No response body`);if(E||(E=!0,o.push({type:`start`,partial:e})),await de(j,e,o,n,d,a),a?.signal?.aborted)throw Error(`Request was aborted`);N(e),o.push({type:`done`,reason:e.stopReason,message:e}),o.end()}catch(t){for(let t of e.content)delete t.partialJson,delete t.customInput;e.stopReason=a?.signal?.aborted?`aborted`:`error`,e.errorMessage=f(d(t)),o.push({type:`error`,reason:e.stopReason,error:e}),o.end()}})(),o},se=(e,t,n)=>{let r=n?.apiKey;if(!r)throw Error(`No API key for provider: ${e.provider}`);let o=a(e,t,n,r),s=n?.reasoning?i(e,n.reasoning):void 0,c=s===`off`?void 0:s;return I(e,t,{...o,reasoningEffort:c})};function ce(e,t,n,r,i=u(t.tools,e.compat?.supportsOpenAIGrammarTools??!1)){let a=e.compat?.supportsStrictMode??!0,o=e.compat?.supportsOpenAIGrammarTools??!1,c=e.compat?.supportsAdditionalTools?`additional-tools`:e.compat?.supportsToolSearch?`tool-search`:void 0,l=s(t,c!==void 0),d=g(e,t,j,{includeSystemPrompt:!1,grammarToolInputProperties:i,deferredTools:l.deferred,deferredToolsMode:c,toolOptions:{strict:null,supportsStrictMode:a,supportsOpenAIGrammarTools:o}}),f={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt||`You are a helpful assistant.`,input:d,text:{verbosity:n?.textVerbosity||`low`},include:[`reasoning.encrypted_content`],prompt_cache_key:r,tool_choice:n?.toolChoice??`auto`,parallel_tool_calls:!0};if(n?.temperature!==void 0&&(f.temperature=n.temperature),n?.serviceTier!==void 0&&(f.service_tier=n.serviceTier),l.immediate.length>0&&(f.tools=m(l.immediate,{strict:null,supportsStrictMode:a,supportsOpenAIGrammarTools:o})),n?.reasoningEffort!==void 0){let t=n.reasoningEffort===`none`?e.thinkingLevelMap?.off??`none`:e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;t!==null&&(f.reasoning={effort:t,summary:n.reasoningSummary??`auto`})}return f}function le(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function L(e,t,n){let r=le(n,t);r!==1&&(e.cost.input*=r,e.cost.output*=r,e.cost.cacheRead*=r,e.cost.cacheWrite*=r,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}function R(e,t){return e==="default"&&(t===`flex`||t===`priority`)?t:e??t}function z(e){let t=(e&&e.trim().length>0?e:`https://chatgpt.com/backend-api`).replace(/\/+$/,``);return t.endsWith(`/codex/responses`)?t:t.endsWith(`/codex`)?`${t}/responses`:`${t}/codex/responses`}function ue(e){let t=new URL(z(e));return t.protocol===`https:`&&(t.protocol=`wss:`),t.protocol===`http:`&&(t.protocol=`ws:`),t.toString()}async function de(e,t,n,r,i,a){await h(H(_e(e,a?.signal),t),t,n,r,{serviceTier:a?.serviceTier,grammarToolInputProperties:i,resolveServiceTier:R,applyServiceTierPricing:(e,t)=>L(e,t,r)})}var B=class extends Error{code;payload;constructor(e,t){super(e),this.name=`CodexApiError`,this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}},V=class extends Error{payload;constructor(e,t){super(e),this.name=`CodexProtocolError`,this.payload=t?.payload,this.cause=t?.cause}};function fe(e){return e instanceof B||e instanceof V}function pe(e){return e instanceof B&&e.code===`websocket_connection_limit_reached`}function me(e){return e instanceof B&&e.code===`previous_response_not_found`}function he(e){let t=e.error&&typeof e.error==`object`?e.error:void 0;return{code:typeof e.code==`string`?e.code:typeof t?.code==`string`?t.code:void 0,message:typeof e.message==`string`?e.message:typeof t?.message==`string`?t.message:void 0}}async function*H(e,t){for await(let n of e){let e=typeof n.type==`string`?n.type:void 0;if(e){if(e===`error`){let{code:e,message:t}=he(n);throw new B(`Codex error: ${t||e||JSON.stringify(n)}`,{code:e,payload:n})}if(e===`response.failed`){let e=n.response,t=e?.error?.code,r=e?.error?.message;throw new B(r||`Codex response failed`,{code:t,payload:n})}if(e===`response.done`||e===`response.completed`||e===`response.incomplete`){let e=n.response;typeof e?.end_turn==`boolean`&&(t.endTurn=e.end_turn);let r=e&&{...e,status:ge(e.status)};yield{...n,type:`response.completed`,response:r};return}yield n}}}function ge(e){if(typeof e==`string`)return M.has(e)?e:void 0}async function*_e(e,t){if(!e.body)return;let r=e.body.getReader(),i=new TextDecoder,a=``,o=()=>{r.cancel().catch(()=>{})};t?.addEventListener(`abort`,o,{once:!0});try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);let{done:e,value:o}=await r.read();if(t?.aborted)throw Error(`Request was aborted`);if(e)break;a+=i.decode(o,{stream:!0});let s=a.indexOf(`
|
|
2
|
+
|
|
3
|
+
`);for(;s!==-1;){let e=a.slice(0,s);a=a.slice(s+2);let t=e.split(`
|
|
4
|
+
`).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());if(t.length>0){let e=t.join(`
|
|
5
|
+
`).trim();if(e&&e!==`[DONE]`)try{yield JSON.parse(e)}catch(t){throw new V(`Invalid Codex SSE JSON: ${n(t)}`,{cause:t,payload:e})}}s=a.indexOf(`
|
|
6
|
+
|
|
7
|
+
`)}}}finally{t?.removeEventListener(`abort`,o);try{await r.cancel()}catch{}try{r.releaseLock()}catch{}}}const U=new Map,W=new Map,G=new Set;function K(e){let t=W.get(e);return t||(t={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},W.set(e,t)),t}function ve(e){let t=W.get(e);return t?{...t}:void 0}function ye(e){if(e){W.delete(e),G.delete(e);return}W.clear(),G.clear()}function q(e){let t=e=>{e.idleTimer&&clearTimeout(e.idleTimer),Q(e.socket,1e3,`debug_close`)};if(e){for(let n of U.get(e)?.values()??[])t(n);U.delete(e);return}for(let e of U.values())for(let n of e.values())t(n);U.clear()}v(q);function J(e){return e?G.has(e):!1}function Y(e){if(!e)return;let t=K(e);t.sseFallbacks++,t.websocketFallbackActive=J(e)}function be(e,t){if(!e)return;G.add(e);let r=K(e);r.websocketFailures++,r.lastWebSocketError=n(t),r.websocketFallbackActive=!0}let X=null;async function xe(e){if(!e&&X)return X;if(typeof process<`u`&&process.versions?.bun){let t=class extends WebSocket{constructor(t,n){let r={};r=Array.isArray(n)||typeof n==`string`?{protocols:n}:{...n};let i=k(t.toString().replace(/^wss:/,`https:`).replace(/^ws:/,`http:`),e);super(t,{...r,...i?{proxy:i.toString()}:{}})}};return e||(X=t),t}let t=globalThis.WebSocket;return typeof t==`function`?t:null}var Se=class extends Error{code;reason;wasClean;constructor(e,t){super(e),this.name=`WebSocketCloseError`,this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}};function Ce(e){let t=e.readyState;return typeof t==`number`?t:void 0}function Z(e){let t=Ce(e);return t===void 0||t===1}function we(e){return Date.now()-e.createdAt>=33e5}function Q(e,t=1e3,n=`done`){try{e.close(t,n)}catch{}}function Te(e,t,n){n.idleTimer&&clearTimeout(n.idleTimer),n.idleTimer=setTimeout(()=>{if(n.busy)return;Q(n.socket,1e3,`idle_timeout`);let r=U.get(e);r?.get(t)===n&&r.delete(t),r?.size===0&&U.delete(e)},3e5)}async function $(e,t,n,r=15e3,i){let a=await xe(i);if(!a)throw Error(`WebSocket transport is not available in this runtime`);let o=c(t);return delete o[`OpenAI-Beta`],new Promise((t,i)=>{let s=!1,c,l;try{l=new a(e,{headers:o})}catch(e){i(e instanceof Error?e:Error(String(e)));return}let u=()=>{c&&=(clearTimeout(c),void 0),l.removeEventListener(`open`,f),l.removeEventListener(`error`,p),l.removeEventListener(`close`,m),n?.removeEventListener(`abort`,h)},d=(e,t)=>{s||(s=!0,u(),t&&Q(l,1e3,t),i(e))},f=()=>{s||(s=!0,u(),t(l))},p=e=>{d(De(e))},m=e=>{d(Oe(e))},h=()=>{d(Error(`Request was aborted`),`aborted`)};l.addEventListener(`open`,f),l.addEventListener(`error`,p),l.addEventListener(`close`,m),n?.addEventListener(`abort`,h),r>0&&(c=setTimeout(()=>{d(Error(`WebSocket connect timeout after ${r}ms`),`connect_timeout`)},r)),n?.aborted&&h()})}async function Ee(e,t,n,r,i,a,o){if(!n){let n=await $(e,t,i,a,o);return{socket:n,reused:!1,release:()=>Q(n)}}let s=U.get(n),c=s?.get(r);if(c){if(c.idleTimer&&=(clearTimeout(c.idleTimer),void 0),!c.busy&&we(c))Q(c.socket,1e3,`connection_age_limit`),s?.delete(r),s?.size===0&&U.delete(n);else if(!c.busy&&Z(c.socket))return c.busy=!0,{socket:c.socket,entry:c,reused:!0,release:({keep:e}={})=>{if(!e||!Z(c.socket)){Q(c.socket);let e=U.get(n);e?.get(r)===c&&e.delete(r),e?.size===0&&U.delete(n);return}c.busy=!1,Te(n,r,c)}};if(c.busy){let n=await $(e,t,i,a,o);return{socket:n,reused:!1,release:()=>{Q(n)}}}Z(c.socket)||(Q(c.socket),s?.delete(r),s?.size===0&&U.delete(n))}let l=await $(e,t,i,a,o),u={socket:l,busy:!0,createdAt:Date.now()};return s=U.get(n),s||(s=new Map,U.set(n,s)),s.set(r,u),{socket:l,entry:u,reused:!1,release:({keep:e}={})=>{if(!e||!Z(u.socket)){Q(u.socket),u.idleTimer&&clearTimeout(u.idleTimer);let e=U.get(n);e?.get(r)===u&&e.delete(r),e?.size===0&&U.delete(n);return}u.busy=!1,Te(n,r,u)}}}function De(e){if(e&&typeof e==`object`){let t=`message`in e?e.message:void 0;if(typeof t==`string`&&t.length>0)return Error(t);let n=`error`in e?e.error:void 0;if(n instanceof Error&&n.message.length>0)return n;if(n&&typeof n==`object`&&`message`in n){let e=n.message;if(typeof e==`string`&&e.length>0)return Error(e)}}return Error(`WebSocket error`)}function Oe(e){if(e&&typeof e==`object`){let t=`code`in e?e.code:void 0,n=`reason`in e?e.reason:void 0,r=`wasClean`in e?e.wasClean:void 0,i=typeof t==`number`?` ${t}`:``,a=typeof n==`string`&&n.length>0?` ${n}`:``;return!a&&t===1009&&(a=` message too big`),new Se(`WebSocket closed${i}${a}`.trim(),{code:typeof t==`number`?t:void 0,reason:typeof n==`string`&&n.length>0?n:void 0,wasClean:typeof r==`boolean`?r:void 0})}return Error(`WebSocket closed`)}async function ke(e){if(typeof e==`string`)return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(e&&typeof e==`object`&&`arrayBuffer`in e){let t=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}async function*Ae(e,t,r){let i=[],a=null,o=!1,s=null,c=!1,l=()=>{if(!a)return;let e=a;a=null,e()},u=e=>{(async()=>{let t=null;try{if(!e||typeof e!=`object`||!(`data`in e)||(t=await ke(e.data),!t))return;let n=JSON.parse(t),r=typeof n.type==`string`?n.type:``;(r===`response.completed`||r===`response.done`||r===`response.incomplete`)&&(c=!0,o=!0),i.push(n),l()}catch(e){s=new V(`Invalid Codex WebSocket JSON: ${n(e)}`,{cause:e,payload:t}),o=!0,l()}})()},d=e=>{s=De(e),o=!0,l()},f=e=>{if(c){o=!0,l();return}s||=Oe(e),o=!0,l()},p=()=>{s=Error(`Request was aborted`),o=!0,l()};e.addEventListener(`message`,u),e.addEventListener(`error`,d),e.addEventListener(`close`,f),t?.addEventListener(`abort`,p);try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);if(i.length>0){yield i.shift();continue}if(o)break;let n;await new Promise((t,i)=>{a=t,r!==void 0&&r>0&&(n=setTimeout(()=>{let t=Error(`WebSocket idle timeout after ${r}ms`);s=t,o=!0,a=null,Q(e,1e3,`idle_timeout`),i(t)},r))}).finally(()=>{n&&clearTimeout(n)})}if(s)throw s;if(!c)throw Error(`WebSocket stream closed before response.completed`)}finally{e.removeEventListener(`message`,u),e.removeEventListener(`error`,d),e.removeEventListener(`close`,f),t?.removeEventListener(`abort`,p)}}function je(e){let{input:t,previous_response_id:n,...r}=e;return r}function Me(e,t){return JSON.stringify(e??[])===JSON.stringify(t??[])}function Ne(e,t){return JSON.stringify(je(e))===JSON.stringify(je(t))}function Pe(e,t){if(!Ne(e,t.lastRequestBody))return;let n=e.input??[],r=[...t.lastRequestBody.input??[],...t.lastResponseItems];if(!(n.length<r.length)&&Me(n.slice(0,r.length),r))return n.slice(r.length)}function Fe(e,t){let n=e.continuation;if(!n)return t;let r=Pe(t,n);return!r||!n.lastResponseId?(e.continuation=void 0,t):{...t,previous_response_id:n.lastResponseId,input:r}}async function*Ie(e,t){let n=!1;for await(let r of e)n||(n=!0,t()),yield r}async function Le(e,t,n,r,i,a,o,s,c,l,u,d,f){let{socket:p,entry:m,reused:_,release:v}=await Ee(e,n,l,u,f?.signal,c,f?.env),y=!0,b=f?.transport===`websocket-cached`||f?.transport===`auto`,x=t,S=b&&m?Fe(m,x):x,C=l?K(l):void 0;C&&(C.requests++,_?C.connectionsReused++:C.connectionsCreated++,b&&C.cachedContextRequests++,S.store===!0&&C.storeTrueRequests++,C.lastInputItems=S.input?.length??0,S.previous_response_id?(C.deltaRequests++,C.lastDeltaInputItems=S.input?.length??0,C.lastPreviousResponseId=S.previous_response_id):(C.fullContextRequests++,C.lastDeltaInputItems=void 0,C.lastPreviousResponseId=void 0));try{if(p.send(JSON.stringify({type:`response.create`,...S})),await h(Ie(H(Ae(p,f?.signal,s),r),o),r,i,a,{serviceTier:f?.serviceTier,grammarToolInputProperties:d,resolveServiceTier:R,applyServiceTierPricing:(e,t)=>L(e,t,a)}),f?.signal?.aborted)y=!1;else if(b&&m&&r.responseId){let e=g(a,{messages:[r]},j,{includeSystemPrompt:!1,grammarToolInputProperties:d}).filter(e=>e.type!==`function_call_output`&&e.type!==`custom_tool_call_output`);m.continuation={lastRequestBody:x,lastResponseId:r.responseId,lastResponseItems:e}}}catch(e){throw m&&(m.continuation=void 0),y=!1,e}finally{v({keep:y})}}async function Re(e){let t=await e.text(),n=t||e.statusText||`Request failed`,r;try{let i=JSON.parse(t)?.error;if(i){let t=i.code||i.type||``;if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(t)||e.status===429){let e=i.plan_type?` (${i.plan_type.toLowerCase()} plan)`:``,t=i.resets_at?Math.max(0,Math.round((i.resets_at*1e3-Date.now())/6e4)):void 0;r=`You have hit your ChatGPT usage limit${e}.${t===void 0?``:` Try again in ~${t} min.`}`.trim()}n=i.message||r||n}}catch{}return{message:n,friendlyMessage:r}}function ze(e){try{let t=e.split(`.`);if(t.length!==3)throw Error(`Invalid token`);let n=JSON.parse(atob(t[1]))?.[`https://api.openai.com/auth`]?.chatgpt_account_id;if(!n)throw Error(`No account ID in token`);return n}catch{throw Error(`Failed to extract accountId from token`)}}function Be(e,t,n,r){let i=new Headers(e);for(let[e,n]of Object.entries(t||{}))n===null?i.delete(e):i.set(e,n);return i.set(`Authorization`,`Bearer ${r}`),i.set(`chatgpt-account-id`,n),i.set(`originator`,`pi`),i.set(`User-Agent`,l()),i}function Ve(e,t,n,r,i){let a=Be(e,t,n,r);return a.set(`OpenAI-Beta`,`responses=experimental`),a.set(`accept`,`text/event-stream`),a.set(`content-type`,`application/json`),i&&(a.set(`session-id`,i),a.set(`x-client-request-id`,i)),a}function He(e,t,n,r,i){let a=Be(e,t,n,r);return a.delete(`accept`),a.delete(`content-type`),a.delete(`OpenAI-Beta`),a.delete(`openai-beta`),a.set(`OpenAI-Beta`,`responses_websockets=2026-02-06`),a.set(`x-client-request-id`,i),a.set(`session-id`,i),a}export{q as closeOpenAICodexWebSocketSessions,ve as getOpenAICodexWebSocketDebugStats,ye as resetOpenAICodexWebSocketDebugStats,I as stream,se as streamSimple};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{i as e,n as t,r as n,t as r}from"./diagnostics-DN_idNHx.js";import{c as i,i as a}from"./transform-messages-N_eMsP2M.js";import{t as o}from"./provider-env-CTOcDKrQ.js";import{t as s}from"./deferred-tools-C1IEsG5C.js";import{t as c}from"./headers-CbDaTl3c.js";import{t as l}from"./pi-user-agent-6Rm79QmC.js";import{n as u}from"./constrained-sampling-Zzx2ko9x.js";import{n as d,t as f}from"./error-body-pkrba6pf.js";import{t as p}from"./openai-prompt-cache-DXo9f3w5.js";import{n as m,r as h,t as g}from"./openai-responses-shared-DhnqxYC9.js";var _=new Set;function v(e){return _.add(e),()=>{_.delete(e)}}var y=-1/0,b=0;function x(e){if(globalThis.crypto?.getRandomValues){globalThis.crypto.getRandomValues(e);return}for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}function S(){let e=new Uint8Array(16);x(e);let t=Date.now();t>y?(b=e[6]*16777216+e[7]*65536+e[8]*256+e[9],y=t):(b=b+1>>>0,b===0&&y++);let n=new Uint8Array(16);n[0]=y/1099511627776&255,n[1]=y/4294967296&255,n[2]=y/16777216&255,n[3]=y/65536&255,n[4]=y/256&255,n[5]=y&255,n[6]=112|b>>>28&15,n[7]=b>>>20&255,n[8]=128|b>>>14&63,n[9]=b>>>6&255,n[10]=(b&63)<<2|e[10]&3,n[11]=e[11],n[12]=e[12],n[13]=e[13],n[14]=e[14],n[15]=e[15];let r=Array.from(n,e=>e.toString(16).padStart(2,`0`));return`${r.slice(0,4).join(``)}-${r.slice(4,6).join(``)}-${r.slice(6,8).join(``)}-${r.slice(8,10).join(``)}-${r.slice(10,16).join(``)}`}function C(e){let t=e.filter(e=>e!==void 0);if(t.length===0)return{cleanup:()=>{}};if(t.length===1)return{signal:t[0],cleanup:()=>{}};let n=new AbortController,r=[],i=e=>{n.signal.aborted||n.abort(e.reason)};for(let e of t){if(e.aborted){i(e);break}let t=()=>i(e);e.addEventListener(`abort`,t,{once:!0}),r.push({signal:e,listener:t})}return{signal:n.signal,cleanup:()=>{for(let{signal:e,listener:t}of r)e.removeEventListener(`abort`,t)}}}var w={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function T(e,t){let n=e.toLowerCase(),r=e.toUpperCase();return t?.[n]||t?.[r]||o(n)||o(r)||``}function E(e){if(e instanceof URL)return e;try{return new URL(e)}catch{return}}function D(e,t,n){let r=T(`no_proxy`,n).toLowerCase();return!r||r!==`*`&&r.split(/[,\s]/).every(n=>{if(!n)return!0;let r=n.match(/^(.+):(\d+)$/),i=r?r[1]:n,a=r?Number.parseInt(r[2],10):0;return a&&a!==t?!0:/^[.*]/.test(i)?(i.startsWith(`*`)&&(i=i.slice(1)),!e.endsWith(i)):e!==i})}function O(e,t){let n=E(e);if(!n?.protocol||!n.host)return``;let r=n.protocol.split(`:`,1)[0];if(!D(n.host.replace(/:\d*$/,``),Number.parseInt(n.port,10)||w[r]||0,t))return``;let i=T(`${r}_proxy`,t)||T(`all_proxy`,t);return i&&!i.includes(`://`)&&(i=`${r}://${i}`),i}var k=`Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.`;function A(e,t){let n=O(e,t);if(!n)return;let r;try{r=new URL(n)}catch(e){throw Error(`Invalid proxy URL ${JSON.stringify(n)}: ${e instanceof Error?e.message:String(e)}`)}if(r.protocol!==`http:`&&r.protocol!==`https:`)throw Error(`${k} Got ${r.protocol}`);return r}var j=`https://chatgpt.com/backend-api`,M=`https://api.openai.com/auth`,ee=0,N=1e3,te=6e4,ne=15e3,re=3,ie=new Set([`openai`,`openai-codex`,`opencode`]),ae=1009,oe=`websocket_connection_limit_reached`,se=`previous_response_not_found`,ce=new Set([`completed`,`incomplete`,`failed`,`cancelled`,`queued`,`in_progress`]);function P(e){if(e.stopReason===`pending`)throw Error(`Codex stream ended without a stop reason`);if(e.stopReason===`error`||e.stopReason===`aborted`)throw Error(e.errorMessage||`An unknown error occurred`)}function le(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function ue(e,t){return e===429&&le(t)?!1:e===429||e===500||e===502||e===503||e===504||/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function de(e){let t=e.get(`retry-after-ms`);if(t!==null){let e=Number(t);if(Number.isFinite(e))return Math.max(0,e)}let n=e.get(`retry-after`);if(!n)return;let r=Number(n);if(Number.isFinite(r))return Math.max(0,r*1e3);let i=Date.parse(n);if(!Number.isNaN(i))return Math.max(0,i-Date.now())}var F=class extends Error{};function fe(e,t){let n=t?.maxRetryDelayMs??te;if(n>0&&e>n)throw new F(`Server requested ${Math.ceil(e/1e3)}s retry delay (max: ${Math.ceil(n/1e3)}s)`);return e}function I(e,t){return new Promise((n,r)=>{if(t?.aborted){r(Error(`Request was aborted`));return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`Request was aborted`))})})}function L(e){if(e!==void 0){if(!Number.isFinite(e)||e<0)throw Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}}function pe(){return typeof process>`u`||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.(`node:zlib`)??null}function me(e){let t=pe();if(!t||typeof t.zstdCompressSync!=`function`)return null;try{let n=t.zstdCompressSync(e,{params:{[t.constants.ZSTD_c_compressionLevel]:re}});return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}catch{return null}}var R=(n,i,a)=>{let o=new e;return(async()=>{let e={role:`assistant`,content:[],api:`openai-codex-responses`,provider:n.provider,model:n.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`pending`,timestamp:Date.now()};try{let s=a?.apiKey;if(!s)throw Error(`No API key for provider: ${n.provider}`);let l=Qe(s),d=u(i.tools,n.compat?.supportsOpenAIGrammarTools??!1),f=a?.cacheRetention===`none`?void 0:a?.sessionId,m=p(f),h=ge(n,i,a,m,d),g=await a?.onPayload?.(h,n);g!==void 0&&(h=g);let _=m||S(),v=et(n.headers,a?.headers,l,s,m),y=tt(n.headers,a?.headers,l,s,_),b=JSON.stringify(h),x=L(a?.timeoutMs),w=L(a?.websocketConnectTimeoutMs),T=a?.transport||`auto`,E=!1,D=T!==`sse`&&Me(f);if(D&&Ne(f),T!==`sse`&&!D){let i=!1,s=!1,c=!1;for(;;){i=!1;try{if(await Xe(ve(n.baseUrl),h,y,e,o,n,()=>{i=!0,E||(E=!0,o.push({type:`start`,partial:e}))},x,w,f,l,d,a),a?.signal?.aborted)throw Error(`Request was aborted`);P(e),o.push({type:`done`,reason:e.stopReason,message:e}),o.end();return}catch(n){let o=a?.signal?.aborted,l=!i&&xe(n),u=Se(n);if(!o&&u&&!c){c=!0;continue}if(!o&&l&&!s){s=!0;continue}if(o||be(n)&&!l||(r(e,t(`provider_transport_failure`,n,{configuredTransport:T,fallbackTransport:i?void 0:`sse`,eventsEmitted:i,phase:i?`after_message_stream_start`:`before_message_stream_start`,requestBytes:new TextEncoder().encode(b).byteLength})),Pe(f,n),i))throw n;Ne(f);break}}}let O=me(b);O&&v.set(`content-encoding`,`zstd`);let k=O??b,A,j,M=a?.maxRetries??ee;for(let e=0;e<=M;e++){if(a?.signal?.aborted)throw Error(`Request was aborted`);try{let t=x!==void 0&&x>0?AbortSignal.timeout(x):void 0,r=C([a?.signal,t]);try{A=await(a?.fetch??globalThis.fetch)(V(n.baseUrl),{method:`POST`,headers:v,body:k,signal:r.signal})}catch(e){throw t?.aborted&&!a?.signal?.aborted?Error(`Codex SSE response headers timed out after ${x}ms`):e}finally{r.cleanup()}if(await a?.onResponse?.({status:A.status,headers:c(A.headers)},n),A.ok)break;let i=await A.text();if(e<M&&ue(A.status,i)){let t=de(A.headers);await I(t===void 0?N*2**e:fe(t,a),a?.signal);continue}let o=await Ze(new Response(i,{status:A.status,statusText:A.statusText}));throw Error(o.friendlyMessage||o.message)}catch(t){if(t instanceof Error&&(t.name===`AbortError`||t.message===`Request was aborted`))throw Error(`Request was aborted`);if(j=t instanceof Error?t:Error(String(t)),e<M&&!(j instanceof F)&&!j.message.includes(`usage limit`)){await I(N*2**e,a?.signal);continue}throw j}}if(!A?.ok)throw j??Error(`Failed after retries`);if(!A.body)throw Error(`No response body`);if(E||(E=!0,o.push({type:`start`,partial:e})),await ye(A,e,o,n,d,a),a?.signal?.aborted)throw Error(`Request was aborted`);P(e),o.push({type:`done`,reason:e.stopReason,message:e}),o.end()}catch(t){for(let t of e.content)delete t.partialJson,delete t.customInput;e.stopReason=a?.signal?.aborted?`aborted`:`error`,e.errorMessage=f(d(t)),o.push({type:`error`,reason:e.stopReason,error:e}),o.end()}})(),o},he=(e,t,n)=>{let r=n?.apiKey;if(!r)throw Error(`No API key for provider: ${e.provider}`);let o=a(e,t,n,r),s=n?.reasoning?i(e,n.reasoning):void 0,c=s===`off`?void 0:s;return R(e,t,{...o,reasoningEffort:c})};function ge(e,t,n,r,i=u(t.tools,e.compat?.supportsOpenAIGrammarTools??!1)){let a=e.compat?.supportsStrictMode??!0,o=e.compat?.supportsOpenAIGrammarTools??!1,c=e.compat?.supportsAdditionalTools?`additional-tools`:e.compat?.supportsToolSearch?`tool-search`:void 0,l=s(t,c!==void 0),d=g(e,t,ie,{includeSystemPrompt:!1,grammarToolInputProperties:i,deferredTools:l.deferred,deferredToolsMode:c,toolOptions:{strict:null,supportsStrictMode:a,supportsOpenAIGrammarTools:o}}),f={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt||`You are a helpful assistant.`,input:d,text:{verbosity:n?.textVerbosity||`low`},include:[`reasoning.encrypted_content`],prompt_cache_key:r,tool_choice:n?.toolChoice??`auto`,parallel_tool_calls:!0};if(n?.temperature!==void 0&&(f.temperature=n.temperature),n?.serviceTier!==void 0&&(f.service_tier=n.serviceTier),l.immediate.length>0&&(f.tools=m(l.immediate,{strict:null,supportsStrictMode:a,supportsOpenAIGrammarTools:o})),n?.reasoningEffort!==void 0){let t=n.reasoningEffort===`none`?e.thinkingLevelMap?.off??`none`:e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;t!==null&&(f.reasoning={effort:t,summary:n.reasoningSummary??`auto`})}return f}function _e(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function z(e,t,n){let r=_e(n,t);r!==1&&(e.cost.input*=r,e.cost.output*=r,e.cost.cacheRead*=r,e.cost.cacheWrite*=r,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}function B(e,t){return e==="default"&&(t===`flex`||t===`priority`)?t:e??t}function V(e){let t=(e&&e.trim().length>0?e:j).replace(/\/+$/,``);return t.endsWith(`/codex/responses`)?t:t.endsWith(`/codex`)?`${t}/responses`:`${t}/codex/responses`}function ve(e){let t=new URL(V(e));return t.protocol===`https:`&&(t.protocol=`wss:`),t.protocol===`http:`&&(t.protocol=`ws:`),t.toString()}async function ye(e,t,n,r,i,a){await h(W(Te(e,a?.signal),t),t,n,r,{serviceTier:a?.serviceTier,grammarToolInputProperties:i,resolveServiceTier:B,applyServiceTierPricing:(e,t)=>z(e,t,r)})}var H=class extends Error{code;payload;constructor(e,t){super(e),this.name=`CodexApiError`,this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}},U=class extends Error{payload;constructor(e,t){super(e),this.name=`CodexProtocolError`,this.payload=t?.payload,this.cause=t?.cause}};function be(e){return e instanceof H||e instanceof U}function xe(e){return e instanceof H&&e.code===oe}function Se(e){return e instanceof H&&e.code===se}function Ce(e){let t=e.error&&typeof e.error==`object`?e.error:void 0;return{code:typeof e.code==`string`?e.code:typeof t?.code==`string`?t.code:void 0,message:typeof e.message==`string`?e.message:typeof t?.message==`string`?t.message:void 0}}async function*W(e,t){for await(let n of e){let e=typeof n.type==`string`?n.type:void 0;if(e){if(e===`error`){let{code:e,message:t}=Ce(n);throw new H(`Codex error: ${t||e||JSON.stringify(n)}`,{code:e,payload:n})}if(e===`response.failed`){let e=n.response,t=e?.error?.code,r=e?.error?.message;throw new H(r||`Codex response failed`,{code:t,payload:n})}if(e===`response.done`||e===`response.completed`||e===`response.incomplete`){let e=n.response;typeof e?.end_turn==`boolean`&&(t.endTurn=e.end_turn);let r=e&&{...e,status:we(e.status)};yield{...n,type:`response.completed`,response:r};return}yield n}}}function we(e){if(typeof e==`string`)return ce.has(e)?e:void 0}async function*Te(e,t){if(!e.body)return;let r=e.body.getReader(),i=new TextDecoder,a=``,o=()=>{r.cancel().catch(()=>{})};t?.addEventListener(`abort`,o,{once:!0});try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);let{done:e,value:o}=await r.read();if(t?.aborted)throw Error(`Request was aborted`);if(e)break;a+=i.decode(o,{stream:!0});let s=a.indexOf(`
|
|
2
|
+
|
|
3
|
+
`);for(;s!==-1;){let e=a.slice(0,s);a=a.slice(s+2);let t=e.split(`
|
|
4
|
+
`).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());if(t.length>0){let e=t.join(`
|
|
5
|
+
`).trim();if(e&&e!==`[DONE]`)try{yield JSON.parse(e)}catch(t){throw new U(`Invalid Codex SSE JSON: ${n(t)}`,{cause:t,payload:e})}}s=a.indexOf(`
|
|
6
|
+
|
|
7
|
+
`)}}}finally{t?.removeEventListener(`abort`,o);try{await r.cancel()}catch{}try{r.releaseLock()}catch{}}}var Ee=`responses_websockets=2026-02-06`,De=3e5,Oe=33e5,G=new Map,K=new Map,q=new Set;function J(e){let t=K.get(e);return t||(t={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},K.set(e,t)),t}function ke(e){let t=K.get(e);return t?{...t}:void 0}function Ae(e){if(e){K.delete(e),q.delete(e);return}K.clear(),q.clear()}function je(e){let t=e=>{e.idleTimer&&clearTimeout(e.idleTimer),Z(e.socket,1e3,`debug_close`)};if(e){for(let n of G.get(e)?.values()??[])t(n);G.delete(e);return}for(let e of G.values())for(let n of e.values())t(n);G.clear()}v(je);function Me(e){return e?q.has(e):!1}function Ne(e){if(!e)return;let t=J(e);t.sseFallbacks++,t.websocketFallbackActive=Me(e)}function Pe(e,t){if(!e)return;q.add(e);let r=J(e);r.websocketFailures++,r.lastWebSocketError=n(t),r.websocketFallbackActive=!0}var Y=null;async function Fe(e){if(!e&&Y)return Y;if(typeof process<`u`&&process.versions?.bun){let t=class extends WebSocket{constructor(t,n){let r={};r=Array.isArray(n)||typeof n==`string`?{protocols:n}:{...n};let i=A(t.toString().replace(/^wss:/,`https:`).replace(/^ws:/,`http:`),e);super(t,{...r,...i?{proxy:i.toString()}:{}})}};return e||(Y=t),t}let t=globalThis.WebSocket;return typeof t==`function`?t:null}var Ie=class extends Error{code;reason;wasClean;constructor(e,t){super(e),this.name=`WebSocketCloseError`,this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}};function Le(e){let t=e.readyState;return typeof t==`number`?t:void 0}function X(e){let t=Le(e);return t===void 0||t===1}function Re(e){return Date.now()-e.createdAt>=Oe}function Z(e,t=1e3,n=`done`){try{e.close(t,n)}catch{}}function ze(e,t,n){n.idleTimer&&clearTimeout(n.idleTimer),n.idleTimer=setTimeout(()=>{if(n.busy)return;Z(n.socket,1e3,`idle_timeout`);let r=G.get(e);r?.get(t)===n&&r.delete(t),r?.size===0&&G.delete(e)},De)}async function Q(e,t,n,r=ne,i){let a=await Fe(i);if(!a)throw Error(`WebSocket transport is not available in this runtime`);let o=c(t);return delete o[`OpenAI-Beta`],new Promise((t,i)=>{let s=!1,c,l;try{l=new a(e,{headers:o})}catch(e){i(e instanceof Error?e:Error(String(e)));return}let u=()=>{c&&=(clearTimeout(c),void 0),l.removeEventListener(`open`,f),l.removeEventListener(`error`,p),l.removeEventListener(`close`,m),n?.removeEventListener(`abort`,h)},d=(e,t)=>{s||(s=!0,u(),t&&Z(l,1e3,t),i(e))},f=()=>{s||(s=!0,u(),t(l))},p=e=>{d(Ve(e))},m=e=>{d($(e))},h=()=>{d(Error(`Request was aborted`),`aborted`)};l.addEventListener(`open`,f),l.addEventListener(`error`,p),l.addEventListener(`close`,m),n?.addEventListener(`abort`,h),r>0&&(c=setTimeout(()=>{d(Error(`WebSocket connect timeout after ${r}ms`),`connect_timeout`)},r)),n?.aborted&&h()})}async function Be(e,t,n,r,i,a,o){if(!n){let n=await Q(e,t,i,a,o);return{socket:n,reused:!1,release:()=>Z(n)}}let s=G.get(n),c=s?.get(r);if(c){if(c.idleTimer&&=(clearTimeout(c.idleTimer),void 0),!c.busy&&Re(c))Z(c.socket,1e3,`connection_age_limit`),s?.delete(r),s?.size===0&&G.delete(n);else if(!c.busy&&X(c.socket))return c.busy=!0,{socket:c.socket,entry:c,reused:!0,release:({keep:e}={})=>{if(!e||!X(c.socket)){Z(c.socket);let e=G.get(n);e?.get(r)===c&&e.delete(r),e?.size===0&&G.delete(n);return}c.busy=!1,ze(n,r,c)}};if(c.busy){let n=await Q(e,t,i,a,o);return{socket:n,reused:!1,release:()=>{Z(n)}}}X(c.socket)||(Z(c.socket),s?.delete(r),s?.size===0&&G.delete(n))}let l=await Q(e,t,i,a,o),u={socket:l,busy:!0,createdAt:Date.now()};return s=G.get(n),s||(s=new Map,G.set(n,s)),s.set(r,u),{socket:l,entry:u,reused:!1,release:({keep:e}={})=>{if(!e||!X(u.socket)){Z(u.socket),u.idleTimer&&clearTimeout(u.idleTimer);let e=G.get(n);e?.get(r)===u&&e.delete(r),e?.size===0&&G.delete(n);return}u.busy=!1,ze(n,r,u)}}}function Ve(e){if(e&&typeof e==`object`){let t=`message`in e?e.message:void 0;if(typeof t==`string`&&t.length>0)return Error(t);let n=`error`in e?e.error:void 0;if(n instanceof Error&&n.message.length>0)return n;if(n&&typeof n==`object`&&`message`in n){let e=n.message;if(typeof e==`string`&&e.length>0)return Error(e)}}return Error(`WebSocket error`)}function $(e){if(e&&typeof e==`object`){let t=`code`in e?e.code:void 0,n=`reason`in e?e.reason:void 0,r=`wasClean`in e?e.wasClean:void 0,i=typeof t==`number`?` ${t}`:``,a=typeof n==`string`&&n.length>0?` ${n}`:``;return!a&&t===ae&&(a=` message too big`),new Ie(`WebSocket closed${i}${a}`.trim(),{code:typeof t==`number`?t:void 0,reason:typeof n==`string`&&n.length>0?n:void 0,wasClean:typeof r==`boolean`?r:void 0})}return Error(`WebSocket closed`)}async function He(e){if(typeof e==`string`)return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(e&&typeof e==`object`&&`arrayBuffer`in e){let t=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}async function*Ue(e,t,r){let i=[],a=null,o=!1,s=null,c=!1,l=()=>{if(!a)return;let e=a;a=null,e()},u=e=>{(async()=>{let t=null;try{if(!e||typeof e!=`object`||!(`data`in e)||(t=await He(e.data),!t))return;let n=JSON.parse(t),r=typeof n.type==`string`?n.type:``;(r===`response.completed`||r===`response.done`||r===`response.incomplete`)&&(c=!0,o=!0),i.push(n),l()}catch(e){s=new U(`Invalid Codex WebSocket JSON: ${n(e)}`,{cause:e,payload:t}),o=!0,l()}})()},d=e=>{s=Ve(e),o=!0,l()},f=e=>{if(c){o=!0,l();return}s||=$(e),o=!0,l()},p=()=>{s=Error(`Request was aborted`),o=!0,l()};e.addEventListener(`message`,u),e.addEventListener(`error`,d),e.addEventListener(`close`,f),t?.addEventListener(`abort`,p);try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);if(i.length>0){yield i.shift();continue}if(o)break;let n;await new Promise((t,i)=>{a=t,r!==void 0&&r>0&&(n=setTimeout(()=>{let t=Error(`WebSocket idle timeout after ${r}ms`);s=t,o=!0,a=null,Z(e,1e3,`idle_timeout`),i(t)},r))}).finally(()=>{n&&clearTimeout(n)})}if(s)throw s;if(!c)throw Error(`WebSocket stream closed before response.completed`)}finally{e.removeEventListener(`message`,u),e.removeEventListener(`error`,d),e.removeEventListener(`close`,f),t?.removeEventListener(`abort`,p)}}function We(e){let{input:t,previous_response_id:n,...r}=e;return r}function Ge(e,t){return JSON.stringify(e??[])===JSON.stringify(t??[])}function Ke(e,t){return JSON.stringify(We(e))===JSON.stringify(We(t))}function qe(e,t){if(!Ke(e,t.lastRequestBody))return;let n=e.input??[],r=[...t.lastRequestBody.input??[],...t.lastResponseItems];if(!(n.length<r.length)&&Ge(n.slice(0,r.length),r))return n.slice(r.length)}function Je(e,t){let n=e.continuation;if(!n)return t;let r=qe(t,n);return!r||!n.lastResponseId?(e.continuation=void 0,t):{...t,previous_response_id:n.lastResponseId,input:r}}async function*Ye(e,t){let n=!1;for await(let r of e)n||(n=!0,t()),yield r}async function Xe(e,t,n,r,i,a,o,s,c,l,u,d,f){let{socket:p,entry:m,reused:_,release:v}=await Be(e,n,l,u,f?.signal,c,f?.env),y=!0,b=f?.transport===`websocket-cached`||f?.transport===`auto`,x=t,S=b&&m?Je(m,x):x,C=l?J(l):void 0;C&&(C.requests++,_?C.connectionsReused++:C.connectionsCreated++,b&&C.cachedContextRequests++,S.store===!0&&C.storeTrueRequests++,C.lastInputItems=S.input?.length??0,S.previous_response_id?(C.deltaRequests++,C.lastDeltaInputItems=S.input?.length??0,C.lastPreviousResponseId=S.previous_response_id):(C.fullContextRequests++,C.lastDeltaInputItems=void 0,C.lastPreviousResponseId=void 0));try{if(p.send(JSON.stringify({type:`response.create`,...S})),await h(Ye(W(Ue(p,f?.signal,s),r),o),r,i,a,{serviceTier:f?.serviceTier,grammarToolInputProperties:d,resolveServiceTier:B,applyServiceTierPricing:(e,t)=>z(e,t,a)}),f?.signal?.aborted)y=!1;else if(b&&m&&r.responseId){let e=g(a,{messages:[r]},ie,{includeSystemPrompt:!1,grammarToolInputProperties:d}).filter(e=>e.type!==`function_call_output`&&e.type!==`custom_tool_call_output`);m.continuation={lastRequestBody:x,lastResponseId:r.responseId,lastResponseItems:e}}}catch(e){throw m&&(m.continuation=void 0),y=!1,e}finally{v({keep:y})}}async function Ze(e){let t=await e.text(),n=t||e.statusText||`Request failed`,r;try{let i=JSON.parse(t)?.error;if(i){let t=i.code||i.type||``;if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(t)||e.status===429){let e=i.plan_type?` (${i.plan_type.toLowerCase()} plan)`:``,t=i.resets_at?Math.max(0,Math.round((i.resets_at*1e3-Date.now())/6e4)):void 0;r=`You have hit your ChatGPT usage limit${e}.${t===void 0?``:` Try again in ~${t} min.`}`.trim()}n=i.message||r||n}}catch{}return{message:n,friendlyMessage:r}}function Qe(e){try{let t=e.split(`.`);if(t.length!==3)throw Error(`Invalid token`);let n=JSON.parse(atob(t[1]))?.[M]?.chatgpt_account_id;if(!n)throw Error(`No account ID in token`);return n}catch{throw Error(`Failed to extract accountId from token`)}}function $e(e,t,n,r){let i=new Headers(e);for(let[e,n]of Object.entries(t||{}))n===null?i.delete(e):i.set(e,n);return i.set(`Authorization`,`Bearer ${r}`),i.set(`chatgpt-account-id`,n),i.set(`originator`,`pi`),i.set(`User-Agent`,l()),i}function et(e,t,n,r,i){let a=$e(e,t,n,r);return a.set(`OpenAI-Beta`,`responses=experimental`),a.set(`accept`,`text/event-stream`),a.set(`content-type`,`application/json`),i&&(a.set(`session-id`,i),a.set(`x-client-request-id`,i)),a}function tt(e,t,n,r,i){let a=$e(e,t,n,r);return a.delete(`accept`),a.delete(`content-type`),a.delete(`OpenAI-Beta`),a.delete(`openai-beta`),a.set(`OpenAI-Beta`,Ee),a.set(`x-client-request-id`,i),a.set(`session-id`,i),a}export{je as closeOpenAICodexWebSocketSessions,ke as getOpenAICodexWebSocketDebugStats,Ae as resetOpenAICodexWebSocketDebugStats,R as stream,he as streamSimple};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{i as e}from"./diagnostics-DN_idNHx.js";import{c as t,i as n,n as r,o as i,s as a,t as o}from"./transform-messages-N_eMsP2M.js";import{n as s}from"./json-parse-CgFfIg4Q.js";import{t as c}from"./provider-env-CTOcDKrQ.js";import{t as l}from"./headers-CbDaTl3c.js";import{t as u}from"./provider-retry-C8PJzY_l.js";import{t as d}from"./sanitize-unicode-DmIE6hZJ.js";import{a as f,i as p,n as m,o as h,r as g,t as _}from"./constrained-sampling-Zzx2ko9x.js";import{n as v,t as y}from"./github-copilot-headers-DRgtIyTm.js";import{n as b}from"./openai-ZcrxEOGB.js";import{n as x,t as S}from"./error-body-pkrba6pf.js";import{t as C}from"./openai-prompt-cache-DXo9f3w5.js";import{t as w}from"./hash-yQufAZII.js";function T(e,t){if(!e)return!1;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n&&r!==null&&r.trim().length>0)return!0;return!1}function E(e,t,n){if(t)return t;if(T(n,`authorization`)||T(n,`cf-aig-authorization`))return`unused`;throw Error(`No API key for provider: ${e}`)}function D(e){for(let t of e)if(t.role===`toolResult`||t.role===`assistant`&&t.content.some(e=>e.type===`toolCall`))return!0;return!1}function O(e){let t=new Set;for(let n of e)if(n.role===`toolResult`)for(let e of n.addedToolNames??[])t.add(e);return t}function k(e,t){if(!e)return[];let n=new Map(e.map(e=>[e.name,e]));return Array.from(t).map(e=>n.get(e)).filter(e=>e!==void 0)}function A(e){return e.type===`text`}function j(e){return e.type===`thinking`}function M(e){return e.type===`toolCall`}function N(e){return e.type===`image`}function P(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.type===`reasoning.encrypted`&&typeof t.id==`string`&&t.id.length>0&&typeof t.data==`string`&&t.data.length>0}function F(e,t){return e||(c(`PI_CACHE_RETENTION`,t)===`long`?`long`:`short`)}var I=(t,n,r)=>{let i=new e;return(async()=>{let e={role:`assistant`,content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`pending`,timestamp:Date.now()};try{let a=E(t.provider,r?.apiKey,r?.headers),o=$(t),c=m(n.tools,o.supportsOpenAIGrammarTools),d=F(r?.cacheRetention,r?.env),f=d===`none`?void 0:r?.sessionId,p=R(t,n,a,r?.headers,r?.fetch,f,o),h=z(t,n,r,o,d,c),g=await r?.onPayload?.(h,t);g!==void 0&&(h=g);let v={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs===void 0?{}:{timeout:r.timeoutMs},maxRetries:0},{data:y,response:b}=await u(()=>p.chat.completions.create(h,v).withResponse(),{maxRetries:r?.maxRetries,maxRetryDelayMs:r?.maxRetryDelayMs,signal:r?.signal});await r?.onResponse?.({status:b.status,headers:l(b.headers)},t),i.push({type:`start`,partial:e});let x=null,S=null,C=!1,w=new Map,T=new Map,D=new Map,O=e.content,k=e=>O.indexOf(e),A=e=>{let t=e.customInput?.property;if(t===void 0)return``;let n=e.arguments[t];return typeof n==`string`?n:``},j=(e,t,n)=>{let r=e.customInput;if(!r)return;let i=_(r.jsonBuffer,r.property,t,n);return e.arguments={[r.property]:t},i},M=t=>{let n=k(t);if(n!==-1){if(t.type===`text`)i.push({type:`text_end`,contentIndex:n,content:t.text,partial:e});else if(t.type===`thinking`)i.push({type:`thinking_end`,contentIndex:n,content:t.thinking,partial:e});else if(t.type===`toolCall`){if(t.customInput){let r=j(t,A(t),!0);r!==void 0&&i.push({type:`toolcall_delta`,contentIndex:n,delta:r,partial:e})}else t.arguments=s(t.partialArgs);delete t.partialArgs,delete t.customInput,delete t.streamIndex,i.push({type:`toolcall_end`,contentIndex:n,toolCall:t,partial:e})}}},N=()=>(x||(x={type:`text`,text:``},O.push(x),i.push({type:`text_start`,contentIndex:k(x),partial:e})),x),I=t=>(S||(S={type:`thinking`,thinking:``,thinkingSignature:t},O.push(S),i.push({type:`thinking_start`,contentIndex:k(S),partial:e})),S),L=e=>{if(!e.id)return;let t=D.get(e.id);t&&(e.thoughtSignature=t,D.delete(e.id))},B=t=>{let n=typeof t.index==`number`?t.index:void 0,r=t.function?.name??t.custom?.name??``,a=n===void 0?void 0:w.get(n);if(!a&&t.id&&(a=T.get(t.id)),!a){let o=t.custom&&!t.function?c.get(r)??`input`:void 0,s=o!==void 0;a={type:`toolCall`,id:t.id||``,name:r,arguments:s?{[o]:``}:{},partialArgs:s?void 0:``,customInput:s?{property:o,jsonBuffer:{input:``,started:!1,closed:!1}}:void 0,streamIndex:n},n!==void 0&&w.set(n,a),t.id&&T.set(t.id,a),O.push(a),i.push({type:`toolcall_start`,contentIndex:k(a),partial:e})}if(n!==void 0&&a.streamIndex===void 0&&(a.streamIndex=n,w.set(n,a)),t.id&&T.set(t.id,a),!a.name&&r&&(a.name=r),t.custom&&!t.function&&!a.customInput){let e=c.get(a.name)??`input`;a.arguments={[e]:``},a.customInput={property:e,jsonBuffer:{input:``,started:!1,closed:!1}},delete a.partialArgs}return L(a),a};for await(let n of y){if(!n||typeof n!=`object`)continue;e.responseId||=n.id,typeof n.model==`string`&&n.model.length>0&&n.model!==t.id&&(e.responseModel||=n.model),n.usage&&(e.usage=Q(n.usage,t));let r=Array.isArray(n.choices)?n.choices[0]:void 0;if(r){if(!n.usage&&r.usage&&(e.usage=Q(r.usage,t)),r.finish_reason){e.rawStopReason=r.finish_reason;let t=ee(r.finish_reason);e.stopReason=t.stopReason,t.errorMessage&&(e.errorMessage=t.errorMessage),C=!0}if(r.delta){if(r.delta.content!==null&&r.delta.content!==void 0&&r.delta.content.length>0){let t=N();t.text+=r.delta.content,i.push({type:`text_delta`,contentIndex:k(t),delta:r.delta.content,partial:e})}let n=[`reasoning_content`,`reasoning`,`reasoning_text`],a=r.delta,o=null;for(let e of n){let t=a[e];if(typeof t==`string`&&t.length>0){o=e;break}}if(o){let n=a[o];if(typeof n==`string`&&n.length>0){let r=I(t.provider===`opencode-go`&&o===`reasoning`?`reasoning_content`:o);r.thinking+=n,i.push({type:`thinking_delta`,contentIndex:k(r),delta:n,partial:e})}}if(r?.delta?.tool_calls)for(let t of r.delta.tool_calls){let n=B(t);!n.id&&t.id&&(n.id=t.id,T.set(t.id,n));let r=t.function?.name??t.custom?.name;!n.name&&r&&(n.name=r);let a=``;t.function?.arguments?(a=t.function.arguments,n.partialArgs=(n.partialArgs??``)+t.function.arguments,n.arguments=s(n.partialArgs)):t.custom?.input&&(a=j(n,A(n)+t.custom.input,!1)??``),i.push({type:`toolcall_delta`,contentIndex:k(n),delta:a,partial:e})}let c=r.delta.reasoning_details;if(Array.isArray(c)){for(let e of c)if(P(e)){let t=JSON.stringify(e),n=T.get(e.id);n?n.thoughtSignature=t:D.set(e.id,t)}}}}}for(let e of O)M(e);if(r?.signal?.aborted||e.stopReason===`aborted`)throw Error(`Request was aborted`);if(!C&&!o.supportsFinishReason&&(e.stopReason=e.content.some(e=>e.type===`toolCall`)?`toolUse`:`stop`),e.stopReason===`error`)throw Error(e.errorMessage||`Provider returned an error stop reason`);if(o.supportsFinishReason&&!C||e.stopReason===`pending`)throw Error(`Stream ended without finish_reason`);i.push({type:`done`,reason:e.stopReason,message:e}),i.end()}catch(t){for(let t of e.content)delete t.index,delete t.partialArgs,delete t.customInput,delete t.streamIndex;e.stopReason=r?.signal?.aborted?`aborted`:`error`,e.errorMessage=S(x(t));let n=t?.error?.metadata?.raw;n&&!e.errorMessage.includes(String(n))&&(e.errorMessage+=`\n${n}`),i.push({type:`error`,reason:e.stopReason,error:e}),i.end()}})(),i},L=(e,r,i)=>{E(e.provider,i?.apiKey,i?.headers);let a=n(e,r,i,i?.apiKey),o=i?.reasoning?t(e,i.reasoning):void 0,s=o===`off`?void 0:o,c=i?.toolChoice;return I(e,r,{...a,reasoningEffort:s,toolChoice:c,thinkingBudgets:i?.thinkingBudgets})};function R(e,t,n,r,i,a,o=$(e)){let s={...e.headers};if(e.provider===`github-copilot`){let e=v(t.messages),n=y({messages:t.messages,hasImages:e});Object.assign(s,n)}return a&&o.sendSessionAffinityHeaders&&(o.sessionAffinityFormat===`openrouter`?s[`x-session-id`]=a:(o.sessionAffinityFormat===`openai`&&(s.session_id=a),s[`x-client-request-id`]=a,s[`x-session-affinity`]=a)),r&&Object.assign(s,r),new b({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:i,defaultHeaders:s})}function z(e,t,n,a=$(e),o=F(n?.cacheRetention,n?.env),s=m(t.tools,a.supportsOpenAIGrammarTools)){let c=X(e,t,a,{grammarToolInputProperties:s}),l=H(a,o),u={model:e.id,messages:c,stream:!0,prompt_cache_key:e.baseUrl.includes(`api.openai.com`)&&o!==`none`||o===`long`&&a.supportsLongCacheRetention?C(n?.sessionId):void 0,prompt_cache_retention:o===`long`&&a.supportsLongCacheRetention?`24h`:void 0};a.supportsUsageInStreaming!==!1&&(u.stream_options={include_usage:!0}),a.supportsStore&&(u.store=!1),n?.maxTokens&&(a.maxTokensField===`max_tokens`?u.max_tokens=n.maxTokens:u.max_completion_tokens=n.maxTokens),n?.temperature!==void 0&&(u.temperature=n.temperature);let d=a.deferredToolsMode===`kimi`?O(t.messages):new Set,f=t.tools?.filter(e=>!d.has(e.name));if(f&&f.length>0?(u.tools=Z(f,a),a.zaiToolStream&&(u.tool_stream=!0)):D(t.messages)&&(u.tools=[]),l&&U(c,u.tools,l),n?.toolChoice&&(u.tool_choice=n.toolChoice),a.thinkingFormat===`zai`&&e.reasoning){let t=u;if(t.thinking=n?.reasoningEffort?{type:`enabled`,clear_thinking:!1}:{type:`disabled`},n?.reasoningEffort&&a.supportsReasoningEffort){let r=e.thinkingLevelMap?.[n.reasoningEffort],i=r===void 0?n.reasoningEffort:r;typeof i==`string`&&(t.reasoning_effort=i)}}else if(a.thinkingFormat===`qwen`&&e.reasoning){if(u.enable_thinking=!!n?.reasoningEffort,n?.reasoningEffort&&a.supportsReasoningEffort){let t=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;typeof t==`string`&&(u.reasoning_effort=t)}}else if(a.thinkingFormat===`qwen-chat-template`&&e.reasoning)u.chat_template_kwargs={enable_thinking:!!n?.reasoningEffort,preserve_thinking:!0};else if(a.thinkingFormat===`chat-template`&&e.reasoning){let t=B(e,n,a.chatTemplateKwargs);t&&(u.chat_template_kwargs=t)}else if(a.thinkingFormat===`baseten`&&e.reasoning){let t=u,r=B(e,n,a.chatTemplateArgs);if(r&&(t.chat_template_args=r),a.supportsReasoningEffort){let r=n?.reasoningEffort,i=r?e.thinkingLevelMap?.[r]:e.thinkingLevelMap?.off,a=i===void 0?r:i;typeof a==`string`&&(t.reasoning_effort=a)}}else if(a.thinkingFormat===`deepseek`&&e.reasoning)n?.reasoningEffort?u.thinking={type:`enabled`}:e.thinkingLevelMap?.off!==null&&(u.thinking={type:`disabled`}),n?.reasoningEffort&&a.supportsReasoningEffort&&(u.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort);else if(a.thinkingFormat===`openrouter`&&e.reasoning){let t=u;n?.reasoningEffort?t.reasoning={effort:e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort}:e.thinkingLevelMap?.off!==null&&(t.reasoning={effort:e.thinkingLevelMap?.off??`none`})}else if(a.thinkingFormat===`ant-ling`&&e.reasoning&&n?.reasoningEffort){let t=e.thinkingLevelMap?.[n.reasoningEffort];typeof t==`string`&&(u.reasoning={effort:t})}else if(a.thinkingFormat===`together`&&e.reasoning){let t=u;t.reasoning={enabled:!!n?.reasoningEffort},n?.reasoningEffort&&a.supportsReasoningEffort&&(t.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort)}else if(a.thinkingFormat===`string-thinking`&&e.reasoning){let t=u;n?.reasoningEffort?t.thinking=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort:e.thinkingLevelMap?.off!==null&&(t.thinking=e.thinkingLevelMap?.off??`none`)}else if(n?.reasoningEffort&&e.reasoning&&a.supportsReasoningEffort)u.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;else if(!n?.reasoningEffort&&e.reasoning&&a.supportsReasoningEffort){let t=e.thinkingLevelMap?.off;typeof t==`string`&&(u.reasoning_effort=t)}if(a.supportsThinkingTokenBudget&&n?.reasoningEffort&&e.reasoning){let t=i(n.reasoningEffort),a={minimal:1024,low:2048,medium:8192,high:16384,...n.thinkingBudgets},o=u.max_tokens??u.max_completion_tokens??e.maxTokens,s=Math.min(a[t],Math.max(0,o-r));s>0&&(u.thinking_token_budget=s)}if(e.compat?.openRouterRouting&&(u.provider=e.compat.openRouterRouting),e.compat?.vercelGatewayRouting){let t=e.compat.vercelGatewayRouting;if(t.only||t.order){let e={};t.only&&(e.only=t.only),t.order&&(e.order=t.order),u.providerOptions={gateway:e}}}return n?.samplingParams&&Object.assign(u,n.samplingParams),u}function B(e,t,n){let r={};for(let[i,a]of Object.entries(n)){let n=V(e,t,a);n!==void 0&&(r[i]=n)}return Object.keys(r).length>0?r:void 0}function V(e,t,n){if(typeof n!=`object`||!n)return n;let r=t?.reasoningEffort;if(!r&&n.omitWhenOff)return;if(n.$var===`thinking.enabled`)return!!r;let i=r?e.thinkingLevelMap?.[r]:e.thinkingLevelMap?.off;return i===void 0?r:typeof i==`string`?i:void 0}function H(e,t){if(e.cacheControlFormat!==`anthropic`||t===`none`)return;let n=t===`long`&&e.supportsLongCacheRetention?`1h`:void 0;return{type:`ephemeral`,...n?{ttl:n}:{}}}function U(e,t,n){W(e,n),K(t,n),G(e,n)}function W(e,t){for(let n of e)if(n.role===`system`||n.role===`developer`){q(n,t);return}}function G(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if((r.role===`user`||r.role===`assistant`||r.role===`tool`)&&J(r,t))return}}function K(e,t){if(!e||e.length===0)return;let n=e[e.length-1];n.cache_control=t}function q(e,t){return Y(e,t)}function J(e,t){return e.role===`user`||e.role===`assistant`||e.role===`tool`?Y(e,t):!1}function Y(e,t){let n=e.content;if(typeof n==`string`)return n.length!==0&&(e.content=[{type:`text`,text:n,cache_control:t}],!0);if(!Array.isArray(n))return!1;for(let e=n.length-1;e>=0;e--){let r=n[e];if(r?.type===`text`){let e=r;return e.cache_control=t,!0}}return!1}function X(e,t,n,r){let i=[],a=t=>{if(t.includes(`|`)){let e=t.indexOf(`|`),n=t.slice(0,e).replace(/[^a-zA-Z0-9_-]/g,`_`),r=t.slice(e+1).replace(/[^a-zA-Z0-9_-]/g,`_`),i=r.length>0?`${n}_${r}`:n;if(i.length<=40)return i;let a=w(t).slice(0,8);return`${n.slice(0,Math.max(1,40-a.length-1))}_${a}`}return e.provider===`openai`&&t.length>40?t.slice(0,40):t},s=o(t.messages,e,e=>a(e));if(t.systemPrompt){let r=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;i.push({role:r,content:d(t.systemPrompt)})}let c=null;for(let a=0;a<s.length;a++){let o=s[a];if(n.requiresAssistantAfterToolResult&&c===`toolResult`&&o.role===`user`&&i.push({role:`assistant`,content:`I have processed the tool results.`}),o.role===`user`)if(typeof o.content==`string`)i.push({role:`user`,content:d(o.content)});else{let e=o.content.map(e=>e.type===`text`?{type:`text`,text:d(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}});if(e.length===0)continue;i.push({role:`user`,content:e})}else if(o.role===`assistant`){let t={role:`assistant`,content:n.requiresAssistantAfterToolResult?``:null},a=o.content.filter(A).filter(e=>e.text.trim().length>0).map(e=>({type:`text`,text:d(e.text)})),s=a.map(e=>e.text).join(``),c=o.content.filter(j).filter(e=>e.thinking.trim().length>0);if(c.length>0)if(n.requiresThinkingAsText)t.content=[{type:`text`,text:c.map(e=>d(e.thinking)).join(`
|
|
2
|
+
|
|
3
|
+
`)},...a];else{s.length>0&&(t.content=s);let n=c[0].thinkingSignature;e.provider===`opencode-go`&&n===`reasoning`&&(n=`reasoning_content`),n&&n.length>0&&(t[n]=c.map(e=>e.thinking).join(`
|
|
4
|
+
`))}else s.length>0&&(t.content=s);let l=o.content.filter(M);if(l.length>0){t.tool_calls=l.map(e=>{let t=r?.grammarToolInputProperties?.get(e.name);return t===void 0?{id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}:{id:e.id,type:`custom`,custom:{name:e.name,input:d(g(e.name,e.arguments,t))}}});let e=l.filter(e=>e.thoughtSignature).map(e=>{try{return JSON.parse(e.thoughtSignature)}catch{return null}}).filter(Boolean);e.length>0&&(t.reasoning_details=e)}n.requiresReasoningContentOnAssistantMessages&&e.reasoning&&t.reasoning_content===void 0&&(t.reasoning_content=``);let u=t.content;if(!(u!=null&&u.length>0)&&!t.tool_calls)continue;i.push(t)}else if(o.role===`toolResult`){let r=[],o=new Set,l=a;for(;l<s.length&&s[l].role===`toolResult`;l++){let t=s[l],a=t.content.filter(A).map(e=>e.text).join(`
|
|
5
|
+
`),c=t.content.some(e=>e.type===`image`),u=a.length>0?a:c?`(see attached image)`:`(no tool output)`,f={role:`tool`,content:d(u),tool_call_id:t.toolCallId};if(n.requiresToolResultName&&t.toolName&&(f.name=t.toolName),i.push(f),n.deferredToolsMode===`kimi`)for(let e of t.addedToolNames??[])o.add(e);if(c&&e.input.includes(`image`))for(let e of t.content)N(e)&&r.push({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}if(a=l-1,r.length>0?(n.requiresAssistantAfterToolResult&&i.push({role:`assistant`,content:`I have processed the tool results.`}),i.push({role:`user`,content:[{type:`text`,text:`Attached image(s) from tool result:`},...r]}),c=`user`):c=`toolResult`,o.size>0){let e=k(t.tools,o);if(e.length>0){let t={role:`system`,tools:Z(e,n)};i.push(t)}}continue}c=o.role}return i}function Z(e,t){return e.map(e=>{let n=f(e,t.supportsOpenAIGrammarTools);if(n)return{type:`custom`,custom:{name:e.name,description:e.description,format:{type:`grammar`,grammar:{syntax:n.format,definition:n.definition}}}};let r=h(e,t.supportsStrictMode!==!1);return{type:`function`,function:{name:e.name,description:e.description,parameters:p(e,r),...t.supportsStrictMode!==!1&&{strict:r??!1}}}})}function Q(e,t){let n=e.prompt_tokens||0,r=e.prompt_tokens_details?.cached_tokens??e.prompt_cache_hit_tokens??0,i=e.prompt_tokens_details?.cache_write_tokens||0,o=Math.max(0,n-r-i),s=e.completion_tokens||0,c={input:o,output:s,cacheRead:r,cacheWrite:i,reasoning:e.completion_tokens_details?.reasoning_tokens||0,totalTokens:o+s+r+i,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return a(t,c),c}function ee(e){if(e===null)return{stopReason:`stop`};switch(e){case`stop`:case`end`:return{stopReason:`stop`};case`length`:return{stopReason:`length`};case`function_call`:case`tool_calls`:return{stopReason:`toolUse`};case`content_filter`:return{stopReason:`error`,errorMessage:`Provider finish_reason: content_filter`};case`network_error`:return{stopReason:`error`,errorMessage:`Provider finish_reason: network_error`};default:return{stopReason:`error`,errorMessage:`Provider finish_reason: ${e}`}}}function te(e){let t=e.provider,n=e.baseUrl,r=t===`zai`||t===`zai-coding-cn`||n.includes(`api.z.ai`)||n.includes(`open.bigmodel.cn`),i=t===`together`||n.includes(`api.together.ai`)||n.includes(`api.together.xyz`),a=t===`moonshotai`||t===`moonshotai-cn`||n.includes(`api.moonshot.`),o=t===`openrouter`||n.includes(`openrouter.ai`),s=t===`cloudflare-workers-ai`||n.includes(`api.cloudflare.com`),c=t===`cloudflare-ai-gateway`||n.includes(`gateway.ai.cloudflare.com`),l=t===`nvidia`||n.includes(`integrate.api.nvidia.com`),u=t===`ant-ling`||n.includes(`api.ant-ling.com`),d=t===`deepseek`||n.toLowerCase().includes(`deepseek.com`),f=l||t===`cerebras`||n.includes(`cerebras.ai`)||t===`xai`||n.includes(`api.x.ai`)||i||n.includes(`chutes.ai`)||d||r||a||t===`opencode`||n.includes(`opencode.ai`)||s||c||u,p=n.includes(`chutes.ai`)||d||a||c||i||l||u||r,m=t===`xai`||n.includes(`api.x.ai`),h=o&&(e.id.startsWith(`anthropic/`)||e.id.startsWith(`openai/`)),g=t===`openrouter`&&e.id.startsWith(`anthropic/`)?`anthropic`:void 0;return{supportsStore:!f,supportsDeveloperRole:h||!f&&!o,supportsReasoningEffort:!m&&!r&&!a&&!i&&!c&&!l&&!u,supportsUsageInStreaming:!0,supportsFinishReason:!0,maxTokensField:p?`max_tokens`:`max_completion_tokens`,requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:d,thinkingFormat:d?`deepseek`:r?`zai`:i?`together`:u?`ant-ling`:o?`openrouter`:`openai`,openRouterRouting:{},vercelGatewayRouting:{},chatTemplateKwargs:{},chatTemplateArgs:{},zaiToolStream:!1,supportsThinkingTokenBudget:!1,supportsStrictMode:!a&&!i&&!c&&!l,supportsOpenAIGrammarTools:!1,cacheControlFormat:g,sendSessionAffinityHeaders:!1,deferredToolsMode:void 0,sessionAffinityFormat:o?`openrouter`:`openai`,supportsLongCacheRetention:!(i||s||c||l||u)}}function $(e){let t=te(e);return e.compat?{supportsStore:e.compat.supportsStore??t.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??t.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??t.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??t.supportsUsageInStreaming,supportsFinishReason:e.compat.supportsFinishReason??t.supportsFinishReason,maxTokensField:e.compat.maxTokensField??t.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??t.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??t.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??t.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:e.compat.requiresReasoningContentOnAssistantMessages??t.requiresReasoningContentOnAssistantMessages,thinkingFormat:e.compat.thinkingFormat??t.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??t.vercelGatewayRouting,chatTemplateKwargs:e.compat.chatTemplateKwargs??t.chatTemplateKwargs,chatTemplateArgs:e.compat.chatTemplateArgs??t.chatTemplateArgs,zaiToolStream:e.compat.zaiToolStream??t.zaiToolStream,supportsThinkingTokenBudget:e.compat.supportsThinkingTokenBudget??t.supportsThinkingTokenBudget,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode,supportsOpenAIGrammarTools:e.compat.supportsOpenAIGrammarTools??t.supportsOpenAIGrammarTools,cacheControlFormat:e.compat.cacheControlFormat??t.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??t.sendSessionAffinityHeaders,deferredToolsMode:e.compat.deferredToolsMode??t.deferredToolsMode,sessionAffinityFormat:e.compat.sessionAffinityFormat??t.sessionAffinityFormat,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??t.supportsLongCacheRetention}:t}export{X as convertMessages,I as stream,L as streamSimple};
|