@pen.dev/cli 0.3.3 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -6
- package/dist/anthropic-messages-COZrsSdY.mjs +40 -0
- package/dist/azure-openai-responses-Dmf1EaVz.mjs +2 -0
- package/dist/browserAll-BZYrVO32.mjs +2 -0
- package/dist/{dist-BEo0Z8Vf.mjs → dist-D9ROAuw3.mjs} +348 -319
- package/dist/{dist-BY6vOcMF.mjs → dist-DGrygXHh.mjs} +2 -2
- package/dist/{error-body-D2Mrqb4g.mjs → error-body-BBlqjbe7.mjs} +1 -1
- package/dist/google-generative-ai-BMEzR_34.mjs +2 -0
- package/dist/google-shared-DXgnvvDU.mjs +318 -0
- package/dist/google-vertex-In7qdx36.mjs +2 -0
- package/dist/index.mjs +2 -2
- package/dist/mistral-conversations-DdYjdrRy.mjs +5 -0
- package/dist/models-BBd5zwn6.mjs +2 -0
- package/dist/{multipart-parser-DX5ZDxQv.mjs → multipart-parser-BdmM0fdd.mjs} +1 -1
- package/dist/node_modules/@highagency/pencil-wasm/package.json +1 -1
- package/dist/node_modules/@highagency/pencil-wasm/pencil.d.ts +3 -0
- package/dist/node_modules/@highagency/pencil-wasm/pencil.js +1 -1
- package/dist/node_modules/@highagency/pencil-wasm/pencil.wasm +0 -0
- package/dist/openai-CbFQ5q5I.mjs +18 -0
- package/dist/openai-codex-responses-CD-2hfWB.mjs +8 -0
- package/dist/openai-completions-DamtYjy7.mjs +6 -0
- package/dist/openai-responses-DgeWdtm-.mjs +2 -0
- package/dist/openai-responses-shared-DKseiGAg.mjs +11 -0
- package/dist/{openrouter-images-BbBWg9zF.mjs → openrouter-images-gArAwqnL.mjs} +1 -1
- package/dist/out/mcp-server-darwin-arm64 +0 -0
- package/dist/out/mcp-server-darwin-x64 +0 -0
- package/dist/out/mcp-server-linux-arm64 +0 -0
- package/dist/out/mcp-server-linux-x64 +0 -0
- package/dist/out/mcp-server-windows-arm64.exe +0 -0
- package/dist/out/mcp-server-windows-x64.exe +0 -0
- package/dist/out/skills/pen-dev/SKILL.md +204 -0
- package/dist/out/skills/pen-dev/execute.md +364 -0
- package/dist/out/skills/pen-dev/guide/code.md +198 -0
- package/dist/out/skills/pen-dev/guide/components.md +45 -0
- package/dist/out/skills/pen-dev/guide/design-system.md +556 -0
- package/dist/out/skills/pen-dev/guide/landing-page.md +31 -0
- package/dist/out/skills/pen-dev/guide/mobile-app.md +31 -0
- package/dist/out/skills/pen-dev/guide/slides.md +222 -0
- package/dist/out/skills/pen-dev/guide/table.md +37 -0
- package/dist/out/skills/pen-dev/guide/tailwind.md +328 -0
- package/dist/out/skills/pen-dev/guide/web-app.md +245 -0
- package/dist/out/skills/pen-dev/pen-schema.md +202 -0
- package/dist/out/skills/pen-dev/scripts-and-shaders.md +94 -0
- package/dist/pi-user-agent-m9a4CjJo.mjs +2 -0
- package/dist/{src-B_lvnEtX.mjs → src-KoDMTA_Q.mjs} +1 -1
- package/dist/transform-messages-BHnJzowk.mjs +2 -0
- package/dist/webworkerAll-CB00nbs9.mjs +2 -0
- package/package.json +3 -3
- package/dist/anthropic-messages-Bf-fvkNu.mjs +0 -40
- package/dist/azure-openai-responses-CzgVqECr.mjs +0 -2
- package/dist/browserAll-8jKh1NRi.mjs +0 -2
- package/dist/completionchunk-BQtPqA8U.mjs +0 -28
- package/dist/google-generative-ai-DSOqI0LF.mjs +0 -2
- package/dist/google-shared-CetPT_Vt.mjs +0 -318
- package/dist/google-vertex-CPtOc5oU.mjs +0 -2
- package/dist/mistral-conversations-CUsdbDQ8.mjs +0 -10
- package/dist/models-CwK5xZH9.mjs +0 -2
- package/dist/openai-Brr_V-tF.mjs +0 -17
- package/dist/openai-codex-responses-Cb5pfH5S.mjs +0 -8
- package/dist/openai-completions-BvTlcCeP.mjs +0 -6
- package/dist/openai-responses-IuaLTEHh.mjs +0 -2
- package/dist/openai-responses-shared-D4d0NbBE.mjs +0 -11
- package/dist/otel-CaADOqYZ.mjs +0 -4
- package/dist/transform-messages-CSBQpmXO.mjs +0 -2
- package/dist/webworkerAll-BD-7VH16.mjs +0 -2
- /package/dist/{dist-BnoSGZKP.mjs → dist-D8tvRm1b.mjs} +0 -0
- /package/dist/{emscripten-module.browser-F76W5DM6-CNibWX-6.mjs → emscripten-module.browser-F76W5DM6-DWhj_jYh.mjs} +0 -0
- /package/dist/{emscripten-module.browser-XIKQQPVU-BNfdGnMe.mjs → emscripten-module.browser-XIKQQPVU-Dmh4no3c.mjs} +0 -0
- /package/dist/{ffi-C5tLdQO9.mjs → ffi-BroAqW9B.mjs} +0 -0
- /package/dist/{ffi-BuJ13coi.mjs → ffi-DwdyvnFx.mjs} +0 -0
- /package/dist/{from-py2TfO8m.mjs → from-Choxbpmr.mjs} +0 -0
- /package/dist/{github-copilot-headers-DZOfokGy.mjs → github-copilot-headers-DCj7hJoC.mjs} +0 -0
- /package/dist/{hash-Kp92CI9R.mjs → hash-DNYCELl4.mjs} +0 -0
- /package/dist/{html-GGJ1fTRB.mjs → html-DEPARSNH.mjs} +0 -0
- /package/dist/{init-B9LSomNH.mjs → init-DwIpBeuP.mjs} +0 -0
- /package/dist/{module-ES6BEMUI-DwQ9nTMF.mjs → module-ES6BEMUI-DUGQwtIb.mjs} +0 -0
- /package/dist/{module-asyncify-2EFITU5U-B54Mkt6K.mjs → module-asyncify-2EFITU5U-U7fqmMTF.mjs} +0 -0
- /package/dist/{openai-prompt-cache-t4kk9puG.mjs → openai-prompt-cache-tVHrB8oW.mjs} +0 -0
- /package/dist/{photon_rs-BySSRmP5.mjs → photon_rs-o0nbTM4F.mjs} +0 -0
- /package/dist/{provider-retry-BM3ArvaW.mjs → provider-retry-wOYAq0sa.mjs} +0 -0
- /package/dist/{sanitize-unicode-CHjuq5rK.mjs → sanitize-unicode-Byz9nlLd.mjs} +0 -0
- /package/dist/{standalone-DYT2Zg6I.mjs → standalone-DwaYVpTH.mjs} +0 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
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)}let 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`))}const 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)};var 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}};const ne=/^[a-z][a-z0-9+.-]*:/i,re=e=>ne.test(e);let 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)}const 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`}const 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}const _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`);let ye;const 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}const 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};let Ae=(e,t)=>(Ae=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ae(e,t));const 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)}const 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])};let Le;const 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`}const 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}let Ge;function Ke(e){let t;return(Ge??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}let 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(`
|
|
3
|
+
`):[]}};w=new WeakMap,T=new WeakMap,Ye.NEWLINE_CHARS=new Set([`
|
|
4
|
+
`,`\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}const 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)}const nt={error:et,warn:et,info:et,debug:et};let 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}const 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);var 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)+`
|
|
5
|
+
`);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(`
|
|
6
|
+
`),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?!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?!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?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...ae(this.options.query),after:e}}:null}};const _t={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`};var vt=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:`urn:ietf:params:oauth:grant-type:token-exchange`,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}};const yt=()=>{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 bt(e,t,n){return yt(),new File(e,t??`unknown_file`,n)}function xt(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}const St=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,Ct=async(e,t)=>kt(e.body)?{...e,body:await Et(e.body,t)}:e,M=async(e,t)=>({...e,body:await Et(e.body,t)}),wt=new WeakMap;function Tt(e){let t=typeof e==`function`?e:e.fetch,n=wt.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 wt.set(t,r),r}const Et=async(e,t)=>{if(!await Tt(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])=>At(n,e,t))),n},Dt=e=>e instanceof Blob&&`name`in e,Ot=e=>typeof e==`object`&&!!e&&(e instanceof Response||St(e)||Dt(e)),kt=e=>{if(Ot(e))return!0;if(Array.isArray(e))return e.some(kt);if(e&&typeof e==`object`){for(let t in e)if(kt(e[t]))return!0}return!1},At=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,bt([await n.blob()],xt(n)));else if(St(n))e.append(t,bt([await new Response(Ce(n)).blob()],xt(n)));else if(Dt(n))e.append(t,n,xt(n));else if(Array.isArray(n))await Promise.all(n.map(n=>At(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>At(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`)}},jt=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`,Mt=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&jt(e),Nt=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function Pt(e,t,n){if(yt(),e=await e,Mt(e))return e instanceof File?e:bt([await e.arrayBuffer()],e.name);if(Nt(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),bt(await Ft(r),t,n)}let r=await Ft(e);if(t||=xt(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return bt(r,t,n)}async function Ft(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(jt(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(St(e))for await(let n of e)t.push(...await Ft(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${It(e)}`)}return t}function It(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var N=class{constructor(e){this._client=e}};function Lt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Rt=Object.freeze(Object.create(null)),P=((e=Lt)=>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??Rt)??Rt)?.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(`
|
|
7
|
+
`)}\n${o}\n${t}`)}return o})(Lt);var zt=class extends N{list(e,t={},n){return this._client.getAPIList(P`/chat/completions/${e}/messages`,k,{query:t,...n,__security:{bearerAuth:!0}})}};function Bt(e){return e!==void 0&&`function`in e&&e.function!==void 0}function Vt(e){return e?.$brand===`auto-parseable-response-format`}function Ht(e){return e?.$brand===`auto-parseable-tool`}function Ut(e,t){return!t||!Jt(t)?{...e,choices:e.choices.map(e=>(Yt(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:Wt(e,t)}function Wt(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 Yt(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>Kt(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?Gt(t,e.message.content):null}}});return{...e,choices:n}}function Gt(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 Kt(e,t){let n=e.tools?.find(e=>Bt(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Ht(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function qt(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>Bt(e)&&e.function?.name===t.function.name);return Bt(n)&&(Ht(n)||n?.function.strict||!1)}function Jt(e){return Vt(e.response_format)?!0:e.tools?.some(e=>Ht(e)||e.type===`function`&&e.function.strict===!0)??!1}function Yt(e){for(let t of e||[])if(t.type!==`function`)throw new a(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function Xt(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`)}}const Zt=e=>e?.role===`assistant`,Qt=e=>e?.role===`tool`;var $t,en,tn,nn,rn,an,on,F,sn,cn,ln,un,dn,fn=class{constructor(){$t.add(this),this.controller=new AbortController,en.set(this,void 0),tn.set(this,()=>{}),nn.set(this,()=>{}),rn.set(this,void 0),an.set(this,()=>{}),on.set(this,()=>{}),F.set(this,{}),sn.set(this,!1),cn.set(this,!1),ln.set(this,!1),un.set(this,!1),e(this,en,new Promise((t,n)=>{e(this,tn,t,`f`),e(this,nn,n,`f`)}),`f`),e(this,rn,new Promise((t,n)=>{e(this,an,t,`f`),e(this,on,n,`f`)}),`f`),t(this,en,`f`).catch(()=>{}),t(this,rn,`f`).catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit(`end`)},t(this,$t,`m`,dn).bind(this))},0)}_connected(){this.ended||(t(this,tn,`f`).call(this),this._emit(`connect`))}get ended(){return t(this,sn,`f`)}get errored(){return t(this,cn,`f`)}get aborted(){return t(this,ln,`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,un,!0,`f`),t!==`error`&&this.once(`error`,r),this.once(t,n)})}async done(){e(this,un,!0,`f`),await t(this,rn,`f`)}_emit(n,...r){if(t(this,sn,`f`))return;n===`end`&&(e(this,sn,!0,`f`),t(this,an,`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,un,`f`)&&!i?.length&&Promise.reject(e),t(this,nn,`f`).call(this,e),t(this,on,`f`).call(this,e),this._emit(`end`);return}if(n===`error`){let e=r[0];!t(this,un,`f`)&&!i?.length&&Promise.reject(e),t(this,nn,`f`).call(this,e),t(this,on,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};en=new WeakMap,tn=new WeakMap,nn=new WeakMap,rn=new WeakMap,an=new WeakMap,on=new WeakMap,F=new WeakMap,sn=new WeakMap,cn=new WeakMap,ln=new WeakMap,un=new WeakMap,$t=new WeakSet,dn=function(t){if(e(this,cn,!0,`f`),t instanceof Error&&t.name===`AbortError`&&(t=new s),t instanceof s)return e(this,ln,!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 pn(e){return typeof e.parse==`function`}var I,mn,hn,gn,_n,vn,yn,bn,xn=class extends fn{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),Qt(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(Zt(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`,mn).call(this)}async finalMessage(){return await this.done(),t(this,I,`m`,hn).call(this)}async finalFunctionToolCall(){return await this.done(),t(this,I,`m`,gn).call(this)}async finalFunctionToolCallResult(){return await this.done(),t(this,I,`m`,_n).call(this)}async totalUsage(){return await this.done(),t(this,I,`m`,vn).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`,hn).call(this);n&&this._emit(`finalMessage`,n);let r=t(this,I,`m`,mn).call(this);r&&this._emit(`finalContent`,r);let i=t(this,I,`m`,gn).call(this);i&&this._emit(`finalFunctionToolCall`,i);let a=t(this,I,`m`,_n).call(this);a!=null&&this._emit(`finalFunctionToolCallResult`,a),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,t(this,I,`m`,vn).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`,yn).call(this,n);let a=await e.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Wt(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=10}=r||{},d=n.tools.map(e=>{if(Ht(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}else 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=pn(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`,bn).call(this,c);if(this._addMessage({role:i,tool_call_id:n,content:u}),l)return}}}};I=new WeakSet,mn=function(){return t(this,I,`m`,hn).call(this).content??null},hn=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(Zt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new a(`stream ended without producing a ChatCompletionMessage with role=assistant`)},gn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Zt(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>e.type===`function`).at(-1)?.function}},_n=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Qt(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}},vn=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},yn=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.`)},bn=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var Sn=class e extends xn{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),Zt(e)&&e.content&&this._emit(`content`,e.content)}};const 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};var Cn=class extends Error{},wn=class extends Error{};function Tn(e,t=L.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return En(e.trim(),t)}const En=(e,t)=>{let n=e.length,r=0,i=e=>{throw new Cn(`${e} at position ${r}`)},a=e=>{throw new wn(`${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:!1,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&&`
|
|
8
|
+
\r `.includes(e[r]);)r++};return o()},Dn=e=>Tn(e,L.ALL^L.NUM);var R,z,On,B,kn,An,jn,Mn,Nn,Pn,Fn,In,Ln=class n extends xn{constructor(t){super(),R.add(this),z.set(this,void 0),On.set(this,void 0),B.set(this,void 0),e(this,z,t,`f`),e(this,On,[],`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`,kn).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`,jn).call(this,e);if(a.controller.signal?.aborted)throw new s;return this._addChatCompletion(t(this,R,`m`,Pn).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`,kn).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`,Pn).call(this)),t(this,R,`m`,jn).call(this,e),a=e.id;if(i.controller.signal?.aborted)throw new s;return this._addChatCompletion(t(this,R,`m`,Pn).call(this))}[(z=new WeakMap,On=new WeakMap,B=new WeakMap,R=new WeakSet,kn=function(){this.ended||e(this,B,void 0,`f`)},An=function(e){let n=t(this,On,`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,On,`f`)[e.index]=n,n)},jn=function(e){if(this.ended)return;let n=t(this,R,`m`,In).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`,An).call(this,e);e.finish_reason&&(t(this,R,`m`,Nn).call(this,e),i.current_tool_call_index!=null&&t(this,R,`m`,Mn).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`,Nn).call(this,e),i.current_tool_call_index!=null&&t(this,R,`m`,Mn).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)}}},Mn=function(e,n){if(t(this,R,`m`,An).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=>Bt(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:Ht(e)?e.$parseRaw(r.function.arguments):e?.function.strict?JSON.parse(r.function.arguments):null})}else r.type},Nn=function(e){let n=t(this,R,`m`,An).call(this,e);if(e.message.content&&!n.content_done){n.content_done=!0;let r=t(this,R,`m`,Fn).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}))},Pn=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,On,[],`f`),Rn(n,t(this,z,`f`))},Fn=function(){let e=t(this,z,`f`)?.response_format;return Vt(e)?e:null},In=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`)&&Jt(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`,Fn).call(this)&&(n.message.parsed=Dn(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,qt(t(this,z,`f`),c)&&(c.function.parsed_arguments=Dn(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 Rn(e,t){let{id:n,choices:r,created:i,model:o,system_fingerprint:s,...c}=e;return Ut({...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${zn(e)}`);if(o==null)throw new a(`missing choices[${r}].tool_calls[${n}].type\n${zn(e)}`);if(u==null)throw new a(`missing choices[${r}].tool_calls[${n}].function.name\n${zn(e)}`);if(l==null)throw new a(`missing choices[${r}].tool_calls[${n}].function.arguments\n${zn(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 zn(e){return JSON.stringify(e)}var Bn=class e extends Ln{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}},Vn=class extends N{constructor(){super(...arguments),this.messages=new zt(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 Xt(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>Wt(t,e))}runTools(e,t){return e.stream?Bn.runTools(this._client,e,t):Sn.runTools(this._client,e,t)}stream(e,t){return Ln.createChatCompletion(this._client,e,t)}};Vn.Messages=zt;var Hn=class extends N{constructor(){super(...arguments),this.completions=new Vn(this._client)}};Hn.Completions=Vn;var Un=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}})}},Wn=class extends N{list(e={},t){return this._client.getAPIList(`/organization/audit_logs`,A,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},Gn=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}})}},Kn=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}})}},qn=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}})}},Jn=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}})}},Yn=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}})}},Xn=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}})}},Zn=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}})}},Qn=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}})}},$n=class extends N{constructor(){super(...arguments),this.users=new Qn(this._client),this.roles=new Zn(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}})}};$n.Users=Qn,$n.Roles=Zn;var er=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}})}},tr=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}})}},nr=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}})}},rr=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}})}},ir=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}})}},ar=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}})}},or=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}})}},sr=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}})}},cr=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}})}},lr=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}})}},ur=class extends N{constructor(){super(...arguments),this.roles=new lr(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}})}};ur.Roles=lr;var dr=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}})}},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}/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}})}};fr.Roles=dr;var V=class extends N{constructor(){super(...arguments),this.users=new fr(this._client),this.serviceAccounts=new sr(this._client),this.apiKeys=new er(this._client),this.rateLimits=new ar(this._client),this.modelPermissions=new ir(this._client),this.hostedToolPermissions=new rr(this._client),this.groups=new ur(this._client),this.roles=new or(this._client),this.dataRetention=new nr(this._client),this.spendAlerts=new cr(this._client),this.certificates=new tr(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=fr,V.ServiceAccounts=sr,V.APIKeys=er,V.RateLimits=ar,V.ModelPermissions=ir,V.HostedToolPermissions=rr,V.Groups=ur,V.Roles=or,V.DataRetention=nr,V.SpendAlerts=cr,V.Certificates=tr;var pr=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}})}},mr=class extends N{constructor(){super(...arguments),this.roles=new pr(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}})}};mr.Roles=pr;var H=class extends N{constructor(){super(...arguments),this.auditLogs=new Wn(this._client),this.adminAPIKeys=new Un(this._client),this.usage=new Xn(this._client),this.invites=new qn(this._client),this.users=new mr(this._client),this.groups=new $n(this._client),this.roles=new Jn(this._client),this.dataRetention=new Kn(this._client),this.spendAlerts=new Yn(this._client),this.certificates=new Gn(this._client),this.projects=new V(this._client)}};H.AuditLogs=Wn,H.AdminAPIKeys=Un,H.Usage=Xn,H.Invites=qn,H.Users=mr,H.Groups=$n,H.Roles=Jn,H.DataRetention=Kn,H.SpendAlerts=Yn,H.Certificates=Gn,H.Projects=V;var hr=class extends N{constructor(){super(...arguments),this.organization=new H(this._client)}};hr.Organization=H;const gr=Symbol(`brand.privateNullableHeaders`);function*_r(e){if(!e)return;if(gr 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])}}const U=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of _r(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{[gr]:!0,values:t,nulls:n}};var vr=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})}},yr=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))}},br=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))}},xr=class extends N{constructor(){super(...arguments),this.transcriptions=new yr(this._client),this.translations=new br(this._client),this.speech=new vr(this._client)}};xr.Transcriptions=yr,xr.Translations=br,xr.Speech=vr;var Sr=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}})}},Cr=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}})}},wr=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}})}},Tr=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}})}},Er=class extends N{constructor(){super(...arguments),this.sessions=new wr(this._client),this.transcriptionSessions=new Tr(this._client)}};Er.Sessions=wr,Er.TranscriptionSessions=Tr;var Dr=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}})}},Or=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}})}},kr=class extends N{constructor(){super(...arguments),this.sessions=new Dr(this._client),this.threads=new Or(this._client)}};kr.Sessions=Dr,kr.Threads=Or;var Ar=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}})}},jr=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}})}};const Mr=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))}else{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 globalThis.process.env?.[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0};var G,K,Nr,q,Pr,J,Y,Fr,X,Ir,Z,Lr,Rr,zr,Br,Vr,Hr,Ur,Wr,Gr,Kr,qr,Jr,Yr=class extends fn{constructor(){super(...arguments),G.add(this),Nr.set(this,[]),q.set(this,{}),Pr.set(this,{}),J.set(this,void 0),Y.set(this,void 0),Fr.set(this,void 0),X.set(this,void 0),Ir.set(this,void 0),Z.set(this,void 0),Lr.set(this,void 0),Rr.set(this,void 0),zr.set(this,void 0)}[(Nr=new WeakMap,q=new WeakMap,Pr=new WeakMap,J=new WeakMap,Y=new WeakMap,Fr=new WeakMap,X=new WeakMap,Ir=new WeakMap,Z=new WeakMap,Lr=new WeakMap,Rr=new WeakMap,zr=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`,Br).call(this,e);if(i.controller.signal?.aborted)throw new s;return this._addRun(t(this,G,`m`,Vr).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`,Br).call(this,e);if(c.controller.signal?.aborted)throw new s;return this._addRun(t(this,G,`m`,Vr).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,Lr,`f`)}currentRun(){return t(this,Rr,`f`)}currentMessageSnapshot(){return t(this,J,`f`)}currentRunStepSnapshot(){return t(this,zr,`f`)}async finalRunSteps(){return await this.done(),Object.values(t(this,q,`f`))}async finalMessages(){return await this.done(),Object.values(t(this,Pr,`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`,Br).call(this,e);if(o.controller.signal?.aborted)throw new s;return this._addRun(t(this,G,`m`,Vr).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`,Br).call(this,e);if(c.controller.signal?.aborted)throw new s;return this._addRun(t(this,G,`m`,Vr).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=Yr,Br=function(n){if(!this.ended)switch(e(this,Lr,n,`f`),t(this,G,`m`,Wr).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`,Jr).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`,Ur).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`,Hr).call(this,n);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`);default:}},Vr=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`)},Hr=function(n){let[r,i]=t(this,G,`m`,Kr).call(this,n,t(this,J,`f`));e(this,J,r,`f`),t(this,Pr,`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,Fr,`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`));break}e(this,Fr,i.index,`f`)}e(this,X,r.content[i.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(t(this,Fr,`f`)!==void 0){let e=n.data.content[t(this,Fr,`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`));break}}t(this,J,`f`)&&this._emit(`messageDone`,n.data),e(this,J,void 0,`f`)}},Ur=function(n){let r=t(this,G,`m`,Gr).call(this,n);switch(e(this,zr,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,Ir,`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,Ir,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,zr,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);break;case`thread.run.step.in_progress`:break}},Wr=function(e){t(this,Nr,`f`).push(e),this._emit(`event`,e)},Gr=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;break}if(t(this,q,`f`)[e.data.id])return t(this,q,`f`)[e.data.id];throw Error(`No snapshot available`)},Kr=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`,qr).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`)},qr=function(e,t){return K.accumulateDelta(t,e)},Jr=function(n){switch(e(this,Rr,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`));break;case`thread.run.cancelling`:break}};var Xr=class extends N{constructor(){super(...arguments),this.steps=new jr(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 Yr.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 Yr.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 Yr.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};Xr.Steps=jr;var Zr=class extends N{constructor(){super(...arguments),this.runs=new Xr(this._client),this.messages=new Ar(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 Yr.createThreadAssistantStream(e,this._client.beta.threads,t)}};Zr.Runs=Xr,Zr.Messages=Ar;var Qr=class extends N{constructor(){super(...arguments),this.realtime=new Er(this._client),this.chatkit=new kr(this._client),this.assistants=new Cr(this._client),this.threads=new Zr(this._client)}};Qr.Realtime=Er,Qr.ChatKit=kr,Qr.Assistants=Cr,Qr.Threads=Zr;var $r=class extends N{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},ei=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})}},ti=class extends N{constructor(){super(...arguments),this.content=new ei(this._client)}create(e,t,n){return this._client.post(P`/containers/${e}/files`,Ct({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}})}};ti.Content=ei;var ni=class extends N{constructor(){super(...arguments),this.files=new ti(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}})}};ni.Files=ti;var ri=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}})}},ii=class extends N{constructor(){super(...arguments),this.items=new ri(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}})}};ii.Items=ri;var ai=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=Mr(t)}),e)))}},oi=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}})}},si=class extends N{constructor(){super(...arguments),this.outputItems=new oi(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}})}};si.OutputItems=oi;var ci=class extends N{constructor(){super(...arguments),this.runs=new si(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}})}};ci.Runs=si;var li=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=1800*1e3}={}){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}},ui=class extends N{},di=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}})}},fi=class extends N{constructor(){super(...arguments),this.graders=new di(this._client)}};fi.Graders=di;var pi=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}})}},mi=class extends N{constructor(){super(...arguments),this.permissions=new pi(this._client)}};mi.Permissions=pi;var hi=class extends N{list(e,t={},n){return this._client.getAPIList(P`/fine_tuning/jobs/${e}/checkpoints`,k,{query:t,...n,__security:{bearerAuth:!0}})}},gi=class extends N{constructor(){super(...arguments),this.checkpoints=new hi(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}})}};gi.Checkpoints=hi;var _i=class extends N{constructor(){super(...arguments),this.methods=new ui(this._client),this.jobs=new gi(this._client),this.checkpoints=new mi(this._client),this.alpha=new fi(this._client)}};_i.Methods=ui,_i.Jobs=gi,_i.Checkpoints=mi,_i.Alpha=fi;var vi=class extends N{},yi=class extends N{constructor(){super(...arguments),this.graderModels=new vi(this._client)}};yi.GraderModels=vi;var bi=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}})}},xi=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}})}},Si=class extends N{create(e,t){return this._client.post(`/moderations`,{body:e,...t,__security:{bearerAuth:!0}})}},Ci=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}})}},wi=class extends N{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t,__security:{bearerAuth:!0}})}},Ti=class extends N{constructor(){super(...arguments),this.clientSecrets=new wi(this._client),this.calls=new Ci(this._client)}};Ti.ClientSecrets=wi,Ti.Calls=Ci;function Ei(e,t){return!t||!ki(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)}:Di(e,t)}function Di(e,t){let n=e.output.map(e=>{if(e.type===`function_call`)return{...e,parsed_arguments:Mi(t,e)};if(e.type===`message`){let n=e.content.map(e=>e.type===`output_text`?{...e,parsed:Oi(t,e.text)}:e);return{...e,content:n}}return e}),r=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,`output_text`)||Ni(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 Oi(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function ki(e){return!!Vt(e.text?.format)}function Ai(e){return e?.$brand===`auto-parseable-tool`}function ji(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function Mi(e,t){let n=ji(e.tools??[],t.name);return{...t,...t,parsed_arguments:Ai(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function Ni(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 Pi,Fi,Q,Ii,Li,Ri,zi,Bi,Vi=class n extends fn{constructor(t){super(),Pi.add(this),Fi.set(this,void 0),Q.set(this,void 0),Ii.set(this,void 0),e(this,Fi,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,Pi,`m`,Li).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,Pi,`m`,Ri).call(this,e,o);if(a.controller.signal?.aborted)throw new s;return t(this,Pi,`m`,zi).call(this)}[(Fi=new WeakMap,Q=new WeakMap,Ii=new WeakMap,Pi=new WeakSet,Li=function(){this.ended||e(this,Q,void 0,`f`)},Ri=function(e,n){if(this.ended)return;let r=(e,t)=>{(n==null||t.sequence_number>n)&&this._emit(e,t)},i=t(this,Pi,`m`,Bi).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);break}},zi=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=Hi(n,t(this,Fi,`f`));return e(this,Ii,r,`f`),r},Bi=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`);break}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,Ii,`f`);if(!e)throw new a(`stream ended without producing a ChatCompletion`);return e}};function Hi(e,t){return Ei(e,t)}var Ui=class extends N{list(e,t={},n){return this._client.getAPIList(P`/responses/${e}/input_items`,k,{query:t,...n,__security:{bearerAuth:!0}})}},Wi=class extends N{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t,__security:{bearerAuth:!0}})}},Gi=class extends N{constructor(){super(...arguments),this.inputItems=new Ui(this._client),this.inputTokens=new Wi(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`&&Ni(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`&&Ni(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=>Di(t,e))}stream(e,t){return Vi.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}})}};Gi.InputItems=Ui,Gi.InputTokens=Wi;var Ki=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})}},qi=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})}},Ji=class extends N{constructor(){super(...arguments),this.content=new qi(this._client)}create(e,t={},n){return this._client.post(P`/skills/${e}/versions`,Ct({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}})}};Ji.Content=qi;var Yi=class extends N{constructor(){super(...arguments),this.content=new Ki(this._client),this.versions=new Ji(this._client)}create(e={},t){return this._client.post(`/skills`,Ct({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}})}};Yi.Content=Ki,Yi.Versions=Ji;var Xi=class extends N{create(e,t,n){return this._client.post(P`/uploads/${e}/parts`,M({body:t,...n,__security:{bearerAuth:!0}},this._client))}},Zi=class extends N{constructor(){super(...arguments),this.parts=new Xi(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}})}};Zi.Parts=Xi;const Qi=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};var $i=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 Qi(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c})}},ea=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}})}},ta=class extends N{constructor(){super(...arguments),this.files=new ea(this._client),this.fileBatches=new $i(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}})}};ta.Files=ea,ta.FileBatches=$i;var na=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`,Ct({body:t,...n,__security:{bearerAuth:!0}},this._client))}},ra,ia,aa,oa=class extends N{constructor(){super(...arguments),ra.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,ra,`m`,ia).call(this,r);let a=U([n]).values,o=t(this,ra,`m`,aa).call(this,a,`webhook-signature`),s=t(this,ra,`m`,aa).call(this,a,`webhook-timestamp`),c=t(this,ra,`m`,aa).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`)}};ra=new WeakSet,ia=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`)},aa=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 sa,ca,la,ua,$=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}={}){sa.add(this),la.set(this,void 0),this.completions=new $r(this),this.chat=new Hn(this),this.embeddings=new ai(this),this.files=new li(this),this.images=new bi(this),this.audio=new xr(this),this.moderations=new Si(this),this.models=new xi(this),this.fineTuning=new _i(this),this.graders=new yi(this),this.vectorStores=new ta(this),this.webhooks=new oa(this),this.beta=new Qr(this),this.batches=new Sr(this),this.uploads=new Zi(this),this.admin=new hr(this),this.responses=new Gi(this),this.realtime=new Ti(this),this.conversations=new ii(this),this.evals=new ci(this),this.containers=new ni(this),this.skills=new Yi(this),this.videos=new na(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.
|
|
9
|
+
|
|
10
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
11
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
12
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
13
|
+
|
|
14
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
15
|
+
|
|
16
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
17
|
+
`);this.baseURL=u.baseURL,this.timeout=u.timeout??ca.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,la,Ee,`f`);let f=W(`OPENAI_CUSTOM_HEADERS`);if(f){let e={};for(let t of f.split(`
|
|
18
|
+
`)){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 vt(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,sa,`m`,ua).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:da(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 workload-identity-auth`){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,la,`f`).call(this,{body:e,headers:r}),isStreamingBody:!1}}};ca=$,la=new WeakMap,sa=new WeakSet,ua=function(){return this.baseURL!==`https://api.openai.com/v1`},$.OpenAI=ca,$.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=Pt,$.Completions=$r,$.Chat=Hn,$.Embeddings=ai,$.Files=li,$.Images=bi,$.Audio=xr,$.Moderations=Si,$.Models=xi,$.FineTuning=_i,$.Graders=yi,$.VectorStores=ta,$.Webhooks=oa,$.Beta=Qr,$.Batches=Sr,$.Uploads=Zi,$.Admin=hr,$.Responses=Gi,$.Realtime=Ti,$.Conversations=ii,$.Evals=ci,$.Containers=ni,$.Skills=Yi,$.Videos=na;function da(e){if(fa(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 fa(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 pa=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||=process.env.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(ma.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)}};const ma=new Set([`/completions`,`/chat/completions`,`/embeddings`,`/audio/transcriptions`,`/audio/translations`,`/audio/speech`,`/images/generations`,`/batches`,`/images/edits`]);export{$ as n,pa as t};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{a as e,i as t,n,t as r}from"./diagnostics-B0j2bfEp.mjs";import{n as i}from"./models-BBd5zwn6.mjs";import{r as a,t as o}from"./uuid-CwuSNv96.mjs";import"./json-parse-BzRcyI3e.mjs";import{t as s}from"./provider-env-CL5ShLlj.mjs";import{t as c}from"./deferred-tools-D8j2Ra6f.mjs";import{t as l}from"./headers-BvGum5dc.mjs";import{t as u}from"./pi-user-agent-m9a4CjJo.mjs";import{c as d,i as f}from"./transform-messages-BHnJzowk.mjs";import{n as p,t as m}from"./error-body-BBlqjbe7.mjs";import{t as h}from"./openai-prompt-cache-tVHrB8oW.mjs";import{n as g,r as _,t as v}from"./openai-responses-shared-DKseiGAg.mjs";function y(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 b={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function x(e,t){let n=e.toLowerCase(),r=e.toUpperCase();return t?.[n]||t?.[r]||s(n)||s(r)||``}function S(e){if(e instanceof URL)return e;try{return new URL(e)}catch{return}}function C(e,t,n){let r=x(`no_proxy`,n).toLowerCase();return r?r===`*`?!1: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}):!0}function ee(e,t){let n=S(e);if(!n?.protocol||!n.host)return``;let r=n.protocol.split(`:`,1)[0];if(!C(n.host.replace(/:\d*$/,``),Number.parseInt(n.port,10)||b[r]||0,t))return``;let i=x(`${r}_proxy`,t)||x(`all_proxy`,t);return i&&!i.includes(`://`)&&(i=`${r}://${i}`),i}function w(e,t){let n=ee(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 T=1e3,E=new Set([`openai`,`openai-codex`,`opencode`]),D=new Set([`completed`,`incomplete`,`failed`,`cancelled`,`queued`,`in_progress`]);function te(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 O(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function ne(e,t){return e===429&&O(t)?!1:e===429||e===500||e===502||e===503||e===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function re(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 k=class extends Error{};function ie(e,t){let n=t?.maxRetryDelayMs??6e4;if(n>0&&e>n)throw new k(`Server requested ${Math.ceil(e/1e3)}s retry delay (max: ${Math.ceil(n/1e3)}s)`);return e}function A(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 j(e){if(e!==void 0){if(!Number.isFinite(e)||e<0)throw Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}}function M(){return typeof process>`u`||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.(`node:zlib`)??null}function ae(e){let t=M();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 N=(t,i,a)=>{let s=new e;return(async()=>{let e={role:`assistant`,content:[],api:`openai-codex-responses`,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 c=a?.apiKey;if(!c)throw Error(`No API key for provider: ${t.provider}`);let u=Fe(c),f=d(i.tools,t.compat?.supportsOpenAIGrammarTools??!1),p=a?.cacheRetention===`none`?void 0:a?.sessionId,m=h(p),g=oe(t,i,a,m,f),_=await a?.onPayload?.(g,t);_!==void 0&&(g=_);let v=m||o(),b=Le(t.headers,a?.headers,u,c,m),x=Re(t.headers,a?.headers,u,c,v),S=JSON.stringify(g),C=j(a?.timeoutMs),ee=j(a?.websocketConnectTimeoutMs),w=a?.transport||`auto`,E=!1,D=w!==`sse`&&q(p);if(D&&J(p),w!==`sse`&&!D){let i=!1,o=!1,c=!1;for(;;){i=!1;try{if(await Ne(se(t.baseUrl),g,x,e,s,t,()=>{i=!0,E||(E=!0,s.push({type:`start`,partial:e}))},C,ee,p,u,f,a),a?.signal?.aborted)throw Error(`Request was aborted`);te(e),s.push({type:`done`,reason:e.stopReason,message:e}),s.end();return}catch(t){let s=a?.signal?.aborted,l=!i&&ue(t),u=de(t);if(!s&&u&&!c){c=!0;continue}if(!s&&l&&!o){o=!0;continue}if(s||le(t)&&!l||(r(e,n(`provider_transport_failure`,t,{configuredTransport:w,fallbackTransport:i?void 0:`sse`,eventsEmitted:i,phase:i?`after_message_stream_start`:`before_message_stream_start`,requestBytes:new TextEncoder().encode(S).byteLength})),_e(p,t),i))throw t;J(p);break}}}let O=ae(S);O&&b.set(`content-encoding`,`zstd`);let M=O??S,N,P,F=a?.maxRetries??0;for(let e=0;e<=F;e++){if(a?.signal?.aborted)throw Error(`Request was aborted`);try{let n=C!==void 0&&C>0?AbortSignal.timeout(C):void 0,r=y([a?.signal,n]);try{N=await(a?.fetch??globalThis.fetch)(R(t.baseUrl),{method:`POST`,headers:b,body:M,signal:r.signal})}catch(e){throw n?.aborted&&!a?.signal?.aborted?Error(`Codex SSE response headers timed out after ${C}ms`):e}finally{r.cleanup()}if(await a?.onResponse?.({status:N.status,headers:l(N.headers)},t),N.ok)break;let i=await N.text();if(e<F&&ne(N.status,i)){let t=re(N.headers);await A(t===void 0?T*2**e:ie(t,a),a?.signal);continue}let o=await Pe(new Response(i,{status:N.status,statusText:N.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(P=t instanceof Error?t:Error(String(t)),e<F&&!(P instanceof k)&&!P.message.includes(`usage limit`)){await A(T*2**e,a?.signal);continue}throw P}}if(!N?.ok)throw P??Error(`Failed after retries`);if(!N.body)throw Error(`No response body`);if(E||(E=!0,s.push({type:`start`,partial:e})),await ce(N,e,s,t,f,a),a?.signal?.aborted)throw Error(`Request was aborted`);te(e),s.push({type:`done`,reason:e.stopReason,message:e}),s.end()}catch(t){for(let t of e.content)delete t.partialJson,delete t.customInput;e.stopReason=a?.signal?.aborted?`aborted`:`error`,e.errorMessage=m(p(t)),s.push({type:`error`,reason:e.stopReason,error:e}),s.end()}})(),s},P=(e,t,n)=>{let r=n?.apiKey;if(!r)throw Error(`No API key for provider: ${e.provider}`);let a=f(e,t,n,r),o=n?.reasoning?i(e,n.reasoning):void 0,s=o===`off`?void 0:o;return N(e,t,{...a,reasoningEffort:s})};function oe(e,t,n,r,i=d(t.tools,e.compat?.supportsOpenAIGrammarTools??!1)){let a=e.compat?.supportsStrictMode??!0,o=e.compat?.supportsOpenAIGrammarTools??!1,s=e.compat?.supportsAdditionalTools?`additional-tools`:e.compat?.supportsToolSearch?`tool-search`:void 0,l=c(t,s!==void 0),u=v(e,t,E,{includeSystemPrompt:!1,grammarToolInputProperties:i,deferredTools:l.deferred,deferredToolsMode:s,toolOptions:{strict:null,supportsStrictMode:a,supportsOpenAIGrammarTools:o}}),f={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt||`You are a helpful assistant.`,input:u,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=g(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 F(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function I(e,t,n){let r=F(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 L(e,t){return e===`default`&&(t===`flex`||t===`priority`)?t:e??t}function R(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 se(e){let t=new URL(R(e));return t.protocol===`https:`&&(t.protocol=`wss:`),t.protocol===`http:`&&(t.protocol=`ws:`),t.toString()}async function ce(e,t,n,r,i,a){await _(V(me(e,a?.signal),t),t,n,r,{serviceTier:a?.serviceTier,grammarToolInputProperties:i,resolveServiceTier:L,applyServiceTierPricing:(e,t)=>I(e,t,r)})}var z=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}},B=class extends Error{payload;constructor(e,t){super(e),this.name=`CodexProtocolError`,this.payload=t?.payload,this.cause=t?.cause}};function le(e){return e instanceof z||e instanceof B}function ue(e){return e instanceof z&&e.code===`websocket_connection_limit_reached`}function de(e){return e instanceof z&&e.code===`previous_response_not_found`}function fe(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*V(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}=fe(n);throw new z(`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 z(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:pe(e.status)};yield{...n,type:`response.completed`,response:r};return}yield n}}}function pe(e){if(typeof e==`string`)return D.has(e)?e:void 0}async function*me(e,n){if(!e.body)return;let r=e.body.getReader(),i=new TextDecoder,a=``,o=()=>{r.cancel().catch(()=>{})};n?.addEventListener(`abort`,o,{once:!0});try{for(;;){if(n?.aborted)throw Error(`Request was aborted`);let{done:e,value:o}=await r.read();if(n?.aborted)throw Error(`Request was aborted`);if(e)break;a+=i.decode(o,{stream:!0});let s=a.indexOf(`
|
|
3
|
+
|
|
4
|
+
`);for(;s!==-1;){let e=a.slice(0,s);a=a.slice(s+2);let n=e.split(`
|
|
5
|
+
`).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());if(n.length>0){let e=n.join(`
|
|
6
|
+
`).trim();if(e&&e!==`[DONE]`)try{yield JSON.parse(e)}catch(n){throw new B(`Invalid Codex SSE JSON: ${t(n)}`,{cause:n,payload:e})}}s=a.indexOf(`
|
|
7
|
+
|
|
8
|
+
`)}}}finally{n?.removeEventListener(`abort`,o);try{await r.cancel()}catch{}try{r.releaseLock()}catch{}}}const H=new Map,U=new Map,W=new Set;function G(e){let t=U.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},U.set(e,t)),t}function he(e){let t=U.get(e);return t?{...t}:void 0}function ge(e){if(e){U.delete(e),W.delete(e);return}U.clear(),W.clear()}function K(e){let t=e=>{e.idleTimer&&clearTimeout(e.idleTimer),Z(e.socket,1e3,`debug_close`)};if(e){for(let n of H.get(e)?.values()??[])t(n);H.delete(e);return}for(let e of H.values())for(let n of e.values())t(n);H.clear()}a(K);function q(e){return e?W.has(e):!1}function J(e){if(!e)return;let t=G(e);t.sseFallbacks++,t.websocketFallbackActive=q(e)}function _e(e,n){if(!e)return;W.add(e);let r=G(e);r.websocketFailures++,r.lastWebSocketError=t(n),r.websocketFallbackActive=!0}let Y=null;async function ve(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=w(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 ye=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 be(e){let t=e.readyState;return typeof t==`number`?t:void 0}function X(e){let t=be(e);return t===void 0||t===1}function xe(e){return Date.now()-e.createdAt>=33e5}function Z(e,t=1e3,n=`done`){try{e.close(t,n)}catch{}}function Se(e,t,n){n.idleTimer&&clearTimeout(n.idleTimer),n.idleTimer=setTimeout(()=>{if(n.busy)return;Z(n.socket,1e3,`idle_timeout`);let r=H.get(e);r?.get(t)===n&&r.delete(t),r?.size===0&&H.delete(e)},3e5)}async function Q(e,t,n,r=15e3,i){let a=await ve(i);if(!a)throw Error(`WebSocket transport is not available in this runtime`);let o=l(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($(e))},m=e=>{d(we(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 Ce(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=H.get(n),c=s?.get(r);if(c){if(c.idleTimer&&=(clearTimeout(c.idleTimer),void 0),!c.busy&&xe(c))Z(c.socket,1e3,`connection_age_limit`),s?.delete(r),s?.size===0&&H.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=H.get(n);e?.get(r)===c&&e.delete(r),e?.size===0&&H.delete(n);return}c.busy=!1,Se(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&&H.delete(n))}let l=await Q(e,t,i,a,o),u={socket:l,busy:!0,createdAt:Date.now()};return s=H.get(n),s||(s=new Map,H.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=H.get(n);e?.get(r)===u&&e.delete(r),e?.size===0&&H.delete(n);return}u.busy=!1,Se(n,r,u)}}}function $(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 we(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 ye(`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 Te(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*Ee(e,n,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 n=null;try{if(!e||typeof e!=`object`||!(`data`in e)||(n=await Te(e.data),!n))return;let t=JSON.parse(n),r=typeof t.type==`string`?t.type:``;(r===`response.completed`||r===`response.done`||r===`response.incomplete`)&&(c=!0,o=!0),i.push(t),l()}catch(e){s=new B(`Invalid Codex WebSocket JSON: ${t(e)}`,{cause:e,payload:n}),o=!0,l()}})()},d=e=>{s=$(e),o=!0,l()},f=e=>{if(c){o=!0,l();return}s||=we(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),n?.addEventListener(`abort`,p);try{for(;;){if(n?.aborted)throw Error(`Request was aborted`);if(i.length>0){yield i.shift();continue}if(o)break;let t;await new Promise((n,i)=>{a=n,r!==void 0&&r>0&&(t=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(()=>{t&&clearTimeout(t)})}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),n?.removeEventListener(`abort`,p)}}function De(e){let{input:t,previous_response_id:n,...r}=e;return r}function Oe(e,t){return JSON.stringify(e??[])===JSON.stringify(t??[])}function ke(e,t){return JSON.stringify(De(e))===JSON.stringify(De(t))}function Ae(e,t){if(!ke(e,t.lastRequestBody))return;let n=e.input??[],r=[...t.lastRequestBody.input??[],...t.lastResponseItems];if(!(n.length<r.length)&&Oe(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=Ae(t,n);return!r||!n.lastResponseId?(e.continuation=void 0,t):{...t,previous_response_id:n.lastResponseId,input:r}}async function*Me(e,t){let n=!1;for await(let r of e)n||(n=!0,t()),yield r}async function Ne(e,t,n,r,i,a,o,s,c,l,u,d,f){let{socket:p,entry:m,reused:h,release:g}=await Ce(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?G(l):void 0;C&&(C.requests++,h?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 _(Me(V(Ee(p,f?.signal,s),r),o),r,i,a,{serviceTier:f?.serviceTier,grammarToolInputProperties:d,resolveServiceTier:L,applyServiceTierPricing:(e,t)=>I(e,t,a)}),f?.signal?.aborted)y=!1;else if(b&&m&&r.responseId){let e=v(a,{messages:[r]},E,{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{g({keep:y})}}async function Pe(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 Fe(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 Ie(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`,u()),i}function Le(e,t,n,r,i){let a=Ie(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 Re(e,t,n,r,i){let a=Ie(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{K as closeOpenAICodexWebSocketSessions,he as getOpenAICodexWebSocketDebugStats,ge as resetOpenAICodexWebSocketDebugStats,N as stream,P as streamSimple};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{a as e}from"./diagnostics-B0j2bfEp.mjs";import{n as t,t as n}from"./models-BBd5zwn6.mjs";import{n as r}from"./json-parse-BzRcyI3e.mjs";import{t as i}from"./provider-env-CL5ShLlj.mjs";import{t as a}from"./headers-BvGum5dc.mjs";import{t as o}from"./provider-retry-wOYAq0sa.mjs";import{t as s}from"./sanitize-unicode-Byz9nlLd.mjs";import{c,d as l,f as u,i as d,l as f,n as p,o as m,s as h,t as g,u as _}from"./transform-messages-BHnJzowk.mjs";import{n as v,t as y}from"./github-copilot-headers-DCj7hJoC.mjs";import{n as b}from"./openai-CbFQ5q5I.mjs";import{n as x,t as S}from"./error-body-BBlqjbe7.mjs";import{t as C}from"./openai-prompt-cache-tVHrB8oW.mjs";import{t as w}from"./hash-DNYCELl4.mjs";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||(i(`PI_CACHE_RETENTION`,t)===`long`?`long`:`short`)}const I=(t,n,i)=>{let s=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 l=E(t.provider,i?.apiKey,i?.headers),u=$(t),d=c(n.tools,u.supportsOpenAIGrammarTools),f=F(i?.cacheRetention,i?.env),p=f===`none`?void 0:i?.sessionId,m=R(t,n,l,i?.headers,i?.fetch,p,u),g=z(t,n,i,u,f,d),_=await i?.onPayload?.(g,t);_!==void 0&&(g=_);let v={...i?.signal?{signal:i.signal}:{},...i?.timeoutMs===void 0?{}:{timeout:i.timeoutMs},maxRetries:0},{data:y,response:b}=await o(()=>m.chat.completions.create(g,v).withResponse(),{maxRetries:i?.maxRetries,maxRetryDelayMs:i?.maxRetryDelayMs,signal:i?.signal});await i?.onResponse?.({status:b.status,headers:a(b.headers)},t),s.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=h(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`)s.push({type:`text_end`,contentIndex:n,content:t.text,partial:e});else if(t.type===`thinking`)s.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&&s.push({type:`toolcall_delta`,contentIndex:n,delta:r,partial:e})}else t.arguments=r(t.partialArgs);delete t.partialArgs,delete t.customInput,delete t.streamIndex,s.push({type:`toolcall_end`,contentIndex:n,toolCall:t,partial:e})}}},N=()=>(x||(x={type:`text`,text:``},O.push(x),s.push({type:`text_start`,contentIndex:k(x),partial:e})),x),I=t=>(S||(S={type:`thinking`,thinking:``,thinkingSignature:t},O.push(S),s.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??``,i=n===void 0?void 0:w.get(n);if(!i&&t.id&&(i=T.get(t.id)),!i){let a=t.custom&&!t.function?d.get(r)??`input`:void 0,o=a!==void 0;i={type:`toolCall`,id:t.id||``,name:r,arguments:o?{[a]:``}:{},partialArgs:o?void 0:``,customInput:o?{property:a,jsonBuffer:{input:``,started:!1,closed:!1}}:void 0,streamIndex:n},n!==void 0&&w.set(n,i),t.id&&T.set(t.id,i),O.push(i),s.push({type:`toolcall_start`,contentIndex:k(i),partial:e})}if(n!==void 0&&i.streamIndex===void 0&&(i.streamIndex=n,w.set(n,i)),t.id&&T.set(t.id,i),!i.name&&r&&(i.name=r),t.custom&&!t.function&&!i.customInput){let e=d.get(i.name)??`input`;i.arguments={[e]:``},i.customInput={property:e,jsonBuffer:{input:``,started:!1,closed:!1}},delete i.partialArgs}return L(i),i};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 i=Array.isArray(n.choices)?n.choices[0]:void 0;if(i){if(!n.usage&&i.usage&&(e.usage=Q(i.usage,t)),i.finish_reason){e.rawStopReason=i.finish_reason;let t=ee(i.finish_reason);e.stopReason=t.stopReason,t.errorMessage&&(e.errorMessage=t.errorMessage),C=!0}if(i.delta){if(i.delta.content!==null&&i.delta.content!==void 0&&i.delta.content.length>0){let t=N();t.text+=i.delta.content,s.push({type:`text_delta`,contentIndex:k(t),delta:i.delta.content,partial:e})}let n=[`reasoning_content`,`reasoning`,`reasoning_text`],a=i.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,s.push({type:`thinking_delta`,contentIndex:k(r),delta:n,partial:e})}}if(i?.delta?.tool_calls)for(let t of i.delta.tool_calls){let n=B(t);!n.id&&t.id&&(n.id=t.id,T.set(t.id,n));let i=t.function?.name??t.custom?.name;!n.name&&i&&(n.name=i);let a=``;t.function?.arguments?(a=t.function.arguments,n.partialArgs=(n.partialArgs??``)+t.function.arguments,n.arguments=r(n.partialArgs)):t.custom?.input&&(a=j(n,A(n)+t.custom.input,!1)??``),s.push({type:`toolcall_delta`,contentIndex:k(n),delta:a,partial:e})}let c=i.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(i?.signal?.aborted||e.stopReason===`aborted`)throw Error(`Request was aborted`);if(!C&&!u.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(u.supportsFinishReason&&!C||e.stopReason===`pending`)throw Error(`Stream ended without finish_reason`);s.push({type:`done`,reason:e.stopReason,message:e}),s.end()}catch(t){for(let t of e.content)delete t.index,delete t.partialArgs,delete t.customInput,delete t.streamIndex;e.stopReason=i?.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}`),s.push({type:`error`,reason:e.stopReason,error:e}),s.end()}})(),s},L=(e,n,r)=>{E(e.provider,r?.apiKey,r?.headers);let i=d(e,n,r,r?.apiKey),a=r?.reasoning?t(e,r.reasoning):void 0,o=a===`off`?void 0:a,s=r?.toolChoice;return I(e,n,{...i,reasoningEffort:o,toolChoice:s,thinkingBudgets:r?.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,r=$(e),i=F(n?.cacheRetention,n?.env),a=c(t.tools,r.supportsOpenAIGrammarTools)){let o=X(e,t,r,{grammarToolInputProperties:a}),s=H(r,i),l={model:e.id,messages:o,stream:!0,prompt_cache_key:e.baseUrl.includes(`api.openai.com`)&&i!==`none`||i===`long`&&r.supportsLongCacheRetention?C(n?.sessionId):void 0,prompt_cache_retention:i===`long`&&r.supportsLongCacheRetention?`24h`:void 0};r.supportsUsageInStreaming!==!1&&(l.stream_options={include_usage:!0}),r.supportsStore&&(l.store=!1),n?.maxTokens&&(r.maxTokensField===`max_tokens`?l.max_tokens=n.maxTokens:l.max_completion_tokens=n.maxTokens),n?.temperature!==void 0&&(l.temperature=n.temperature);let u=r.deferredToolsMode===`kimi`?O(t.messages):new Set,d=t.tools?.filter(e=>!u.has(e.name));if(d&&d.length>0?(l.tools=Z(d,r),r.zaiToolStream&&(l.tool_stream=!0)):D(t.messages)&&(l.tools=[]),s&&U(o,l.tools,s),n?.toolChoice&&(l.tool_choice=n.toolChoice),r.thinkingFormat===`zai`&&e.reasoning){let t=l;if(t.thinking=n?.reasoningEffort?{type:`enabled`,clear_thinking:!1}:{type:`disabled`},n?.reasoningEffort&&r.supportsReasoningEffort){let r=e.thinkingLevelMap?.[n.reasoningEffort],i=r===void 0?n.reasoningEffort:r;typeof i==`string`&&(t.reasoning_effort=i)}}else if(r.thinkingFormat===`qwen`&&e.reasoning){if(l.enable_thinking=!!n?.reasoningEffort,n?.reasoningEffort&&r.supportsReasoningEffort){let t=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;typeof t==`string`&&(l.reasoning_effort=t)}}else if(r.thinkingFormat===`qwen-chat-template`&&e.reasoning)l.chat_template_kwargs={enable_thinking:!!n?.reasoningEffort,preserve_thinking:!0};else if(r.thinkingFormat===`chat-template`&&e.reasoning){let t=B(e,n,r.chatTemplateKwargs);t&&(l.chat_template_kwargs=t)}else if(r.thinkingFormat===`baseten`&&e.reasoning){let t=l,i=B(e,n,r.chatTemplateArgs);if(i&&(t.chat_template_args=i),r.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(r.thinkingFormat===`deepseek`&&e.reasoning)n?.reasoningEffort?l.thinking={type:`enabled`}:e.thinkingLevelMap?.off!==null&&(l.thinking={type:`disabled`}),n?.reasoningEffort&&r.supportsReasoningEffort&&(l.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort);else if(r.thinkingFormat===`openrouter`&&e.reasoning){let t=l;n?.reasoningEffort?t.reasoning={effort:e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort}:e.thinkingLevelMap?.off!==null&&(t.reasoning={effort:e.thinkingLevelMap?.off??`none`})}else if(r.thinkingFormat===`ant-ling`&&e.reasoning&&n?.reasoningEffort){let t=e.thinkingLevelMap?.[n.reasoningEffort];typeof t==`string`&&(l.reasoning={effort:t})}else if(r.thinkingFormat===`together`&&e.reasoning){let t=l;t.reasoning={enabled:!!n?.reasoningEffort},n?.reasoningEffort&&r.supportsReasoningEffort&&(t.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort)}else if(r.thinkingFormat===`string-thinking`&&e.reasoning){let t=l;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&&r.supportsReasoningEffort)l.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;else if(!n?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort){let t=e.thinkingLevelMap?.off;typeof t==`string`&&(l.reasoning_effort=t)}if(r.supportsThinkingTokenBudget&&n?.reasoningEffort&&e.reasoning){let t=m(n.reasoningEffort),r={minimal:1024,low:2048,medium:8192,high:16384,...n.thinkingBudgets},i=l.max_tokens??l.max_completion_tokens??e.maxTokens,a=Math.min(r[t],Math.max(0,i-p));a>0&&(l.thinking_token_budget=a)}if(e.compat?.openRouterRouting&&(l.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),l.providerOptions={gateway:e}}}return n?.samplingParams&&Object.assign(l,n.samplingParams),l}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?!1:(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},o=g(t.messages,e,e=>a(e));if(t.systemPrompt){let r=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;i.push({role:r,content:s(t.systemPrompt)})}let c=null;for(let a=0;a<o.length;a++){let l=o[a];if(n.requiresAssistantAfterToolResult&&c===`toolResult`&&l.role===`user`&&i.push({role:`assistant`,content:`I have processed the tool results.`}),l.role===`user`)if(typeof l.content==`string`)i.push({role:`user`,content:s(l.content)});else{let e=l.content.map(e=>e.type===`text`?{type:`text`,text:s(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(l.role===`assistant`){let t={role:`assistant`,content:n.requiresAssistantAfterToolResult?``:null},a=l.content.filter(A).filter(e=>e.text.trim().length>0).map(e=>({type:`text`,text:s(e.text)})),o=a.map(e=>e.text).join(``),c=l.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=>s(e.thinking)).join(`
|
|
3
|
+
|
|
4
|
+
`)},...a];else{o.length>0&&(t.content=o);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(`
|
|
5
|
+
`))}else o.length>0&&(t.content=o);let u=l.content.filter(M);if(u.length>0){t.tool_calls=u.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:s(f(e.name,e.arguments,t))}}});let e=u.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 d=t.content;if(!(d!=null&&d.length>0)&&!t.tool_calls)continue;i.push(t)}else if(l.role===`toolResult`){let r=[],l=new Set,u=a;for(;u<o.length&&o[u].role===`toolResult`;u++){let t=o[u],a=t.content.filter(A).map(e=>e.text).join(`
|
|
6
|
+
`),c=t.content.some(e=>e.type===`image`),d={role:`tool`,content:s(a.length>0?a:c?`(see attached image)`:`(no tool output)`),tool_call_id:t.toolCallId};if(n.requiresToolResultName&&t.toolName&&(d.name=t.toolName),i.push(d),n.deferredToolsMode===`kimi`)for(let e of t.addedToolNames??[])l.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=u-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`,l.size>0){let e=k(t.tools,l);if(e.length>0){let t={role:`system`,tools:Z(e,n)};i.push(t)}}continue}c=l.role}return i}function Z(e,t){return e.map(e=>{let n=l(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=u(e,t.supportsStrictMode!==!1);return{type:`function`,function:{name:e.name,description:e.description,parameters:_(e,r),...t.supportsStrictMode!==!1&&{strict:r??!1}}}})}function Q(e,t){let r=e.prompt_tokens||0,i=e.prompt_tokens_details?.cached_tokens??e.prompt_cache_hit_tokens??0,a=e.prompt_tokens_details?.cache_write_tokens||0,o=Math.max(0,r-i-a),s=e.completion_tokens||0,c={input:o,output:s,cacheRead:i,cacheWrite:a,reasoning:e.completion_tokens_details?.reasoning_tokens||0,totalTokens:o+s+i+a,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return n(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};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{a as e}from"./diagnostics-B0j2bfEp.mjs";import{n as t}from"./models-BBd5zwn6.mjs";import"./json-parse-BzRcyI3e.mjs";import{t as n}from"./provider-env-CL5ShLlj.mjs";import{t as r}from"./deferred-tools-D8j2Ra6f.mjs";import{t as i}from"./headers-BvGum5dc.mjs";import{t as a}from"./provider-retry-wOYAq0sa.mjs";import{c as o,i as s}from"./transform-messages-BHnJzowk.mjs";import{n as c,t as l}from"./github-copilot-headers-DCj7hJoC.mjs";import{n as u}from"./openai-CbFQ5q5I.mjs";import{n as d,t as f}from"./error-body-BBlqjbe7.mjs";import{t as p}from"./openai-prompt-cache-tVHrB8oW.mjs";import{n as m,r as h,t as g}from"./openai-responses-shared-DKseiGAg.mjs";const _=new Set([`openai`,`openai-codex`,`opencode`]);function v(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 y(e,t,n){if(t)return t;if(v(n,`authorization`)||v(n,`cf-aig-authorization`))return`unused`;throw Error(`No API key for provider: ${e}`)}function b(e){return e.provider===`openrouter`||e.baseUrl.includes(`openrouter.ai`)?`openrouter`:`openai`}function x(e,t){return e||(n(`PI_CACHE_RETENTION`,t)===`long`?`long`:`short`)}function S(e){return{supportsDeveloperRole:e.compat?.supportsDeveloperRole??!0,sessionAffinityFormat:e.compat?.sessionAffinityFormat??b(e),supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0,supportsStrictMode:e.compat?.supportsStrictMode??!1,supportsOpenAIGrammarTools:e.compat?.supportsOpenAIGrammarTools??!1,supportsAdditionalTools:e.compat?.supportsAdditionalTools??!1,supportsToolSearch:e.compat?.supportsToolSearch??!1,supportsExplicitPromptCacheMode:e.compat?.supportsExplicitPromptCacheMode??!1}}function C(e,t){return t===`long`&&e.supportsLongCacheRetention?`24h`:void 0}function w(e){return f(d(e),`OpenAI API error`)}const T=(t,n,r)=>{let s=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 c=y(t.provider,r?.apiKey,r?.headers),l=x(r?.cacheRetention,r?.env)===`none`?void 0:r?.sessionId,u=S(t),d=o(n.tools,u.supportsOpenAIGrammarTools),f=D(t,n,c,r?.headers,r?.fetch,l),p=O(t,n,r,u,d),m=await r?.onPayload?.(p,t);m!==void 0&&(p=m);let g={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs===void 0?{}:{timeout:r.timeoutMs},maxRetries:0},{data:_,response:v}=await a(()=>f.responses.create(p,g).withResponse(),{maxRetries:r?.maxRetries,maxRetryDelayMs:r?.maxRetryDelayMs,signal:r?.signal});if(await r?.onResponse?.({status:v.status,headers:i(v.headers)},t),s.push({type:`start`,partial:e}),await h(_,e,s,t,{serviceTier:r?.serviceTier,grammarToolInputProperties:d,applyServiceTierPricing:(e,n)=>A(e,n,t)}),r?.signal?.aborted)throw Error(`Request was aborted`);if(e.stopReason===`pending`)throw Error(`OpenAI Responses stream ended without a stop reason`);if(e.stopReason===`aborted`||e.stopReason===`error`)throw Error(e.errorMessage||`An unknown error occurred`);s.push({type:`done`,reason:e.stopReason,message:e}),s.end()}catch(t){for(let t of e.content)delete t.index,delete t.partialJson,delete t.customInput;e.stopReason=r?.signal?.aborted?`aborted`:`error`,e.errorMessage=w(t),s.push({type:`error`,reason:e.stopReason,error:e}),s.end()}})(),s},E=(e,n,r)=>{y(e.provider,r?.apiKey,r?.headers);let i=s(e,n,r,r?.apiKey),a=r?.reasoning?t(e,r.reasoning):void 0,o=a===`off`?void 0:a;return T(e,n,{...i,reasoningEffort:o})};function D(e,t,n,r,i,a){let o=S(e),s={...e.headers};if(e.provider===`github-copilot`){let e=c(t.messages),n=l({messages:t.messages,hasImages:e});Object.assign(s,n)}return a&&(o.sessionAffinityFormat===`openrouter`?s[`x-session-id`]=a:(o.sessionAffinityFormat===`openai`&&(s.session_id=a),s[`x-client-request-id`]=a)),r&&Object.assign(s,r),new u({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:i,defaultHeaders:s})}function O(e,t,n,i=S(e),a=o(t.tools,i.supportsOpenAIGrammarTools)){let s=i.supportsAdditionalTools?`additional-tools`:i.supportsToolSearch?`tool-search`:void 0,c=r(t,s!==void 0),l=g(e,t,_,{grammarToolInputProperties:a,deferredTools:c.deferred,deferredToolsMode:s,toolOptions:{supportsStrictMode:i.supportsStrictMode,supportsOpenAIGrammarTools:i.supportsOpenAIGrammarTools}}),u=x(n?.cacheRetention,n?.env),d=u===`none`&&i.supportsExplicitPromptCacheMode,f={model:e.id,input:l,stream:!0,prompt_cache_key:u===`none`?void 0:p(n?.sessionId),prompt_cache_retention:C(i,u),prompt_cache_options:d?{mode:`explicit`}:void 0,store:!1};return n?.maxTokens&&(f.max_output_tokens=Math.max(n.maxTokens,16)),n?.temperature!==void 0&&(f.temperature=n?.temperature),n?.serviceTier!==void 0&&(f.service_tier=n.serviceTier),c.immediate.length>0&&(f.tools=m(c.immediate,{supportsStrictMode:i.supportsStrictMode,supportsOpenAIGrammarTools:i.supportsOpenAIGrammarTools})),n?.toolChoice!==void 0&&(f.tool_choice=n.toolChoice),e.reasoning&&(n?.reasoningEffort||n?.reasoningSummary?(f.reasoning={effort:n?.reasoningEffort?e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort:`medium`,summary:n?.reasoningSummary||`auto`},f.include=[`reasoning.encrypted_content`]):e.provider!==`github-copilot`&&e.thinkingLevelMap?.off!==null&&(f.reasoning={effort:e.thinkingLevelMap?.off??`none`}),e.provider===`xai`&&(f.include=[`reasoning.encrypted_content`])),n?.samplingParams&&Object.assign(f,n.samplingParams),f}function k(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function A(e,t,n){let r=k(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)}export{T as stream,E as streamSimple};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{t as e}from"./models-BBd5zwn6.mjs";import{n as t}from"./json-parse-BzRcyI3e.mjs";import{t as n}from"./sanitize-unicode-Byz9nlLd.mjs";import{d as r,f as i,l as a,s as o,t as s,u as c}from"./transform-messages-BHnJzowk.mjs";import{t as l}from"./hash-DNYCELl4.mjs";function u(e,t){let n={v:1,id:e};return t&&(n.phase=t),JSON.stringify(n)}function d(e){if(e){if(e.startsWith(`{`))try{let t=JSON.parse(e);if(t.v===1&&typeof t.id==`string`)return t.phase===`commentary`||t.phase===`final_answer`?{id:t.id,phase:t.phase}:{id:t.id}}catch{}return{id:e}}}function f(e,t){let r=t.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
3
|
+
`),i=t.filter(e=>e.type===`image`),a=r.length>0;if(i.length===0||!e.input.includes(`image`))return n(a?r:i.length>0?`(see attached image)`:`(no tool output)`);let o=[];a&&o.push({type:`input_text`,text:n(r)});for(let e of i)o.push({type:`input_image`,detail:`auto`,image_url:`data:${e.mimeType};base64,${e.data}`});return o}function p(e,t,r,i){let o=[],c=new Set,u=e=>{let t=e.replace(/[^a-zA-Z0-9_-]/g,`_`);return(t.length>64?t.slice(0,64):t).replace(/_+$/,``)},p=e=>{let t=`fc_${l(e)}`;return t.length>64?t.slice(0,64):t},h=s(t.messages,e,(t,n,i)=>{if(!r.has(e.provider)||!t.includes(`|`))return u(t);let[a,o]=t.split(`|`),s=u(a),c=i.provider!==e.provider||i.api!==e.api?p(o):u(o);return c.startsWith(`fc_`)||(c=u(`fc_${c}`)),`${s}|${c}`});if((i?.includeSystemPrompt??!0)&&t.systemPrompt){let r=e.compat,i=e.reasoning&&r?.supportsDeveloperRole!==!1?`developer`:`system`;o.push({role:i,content:n(t.systemPrompt)})}let g=0;for(let t of h){if(t.role===`user`)if(typeof t.content==`string`)o.push({role:`user`,content:[{type:`input_text`,text:n(t.content)}]});else{let e=t.content.map(e=>e.type===`text`?{type:`input_text`,text:n(e.text)}:{type:`input_image`,detail:`auto`,image_url:`data:${e.mimeType};base64,${e.data}`});if(e.length===0)continue;o.push({role:`user`,content:e})}else if(t.role===`assistant`){let r=[],s=t,c=s.provider===e.provider&&s.api===e.api,u=c&&s.model===e.id,f=c&&s.model!==e.id,p=0;for(let e of t.content)if(e.type===`thinking`){if(e.thinkingSignature){let t=JSON.parse(e.thinkingSignature);r.push(t)}}else if(e.type===`text`){let t=e,i=d(t.textSignature),a=p===0?`msg_pi_${g}`:`msg_pi_${g}_${p}`;p++;let o=i?.id;o?o.length>64&&(o=`msg_${l(o)}`):o=a,r.push({type:`message`,role:`assistant`,content:[{type:`output_text`,text:n(t.text),annotations:[]}],status:`completed`,id:o,phase:i?.phase})}else if(e.type===`toolCall`){let t=e,[o,s]=t.id.split(`|`),c=i?.grammarToolInputProperties?.get(t.name),l=s;(f&&l?.startsWith(`fc_`)||c===void 0&&!l?.startsWith(`fc_`))&&(l=void 0);let d=u||i?.deferredTools?.has(t.name)===!0;c===void 0?r.push({type:`function_call`,id:l,call_id:o,name:t.name,arguments:JSON.stringify(t.arguments),...d&&t.namespace!==void 0?{namespace:t.namespace}:{}}):r.push({type:`custom_tool_call`,id:l,call_id:o,name:t.name,input:n(a(t.name,t.arguments,c)),...d&&t.namespace!==void 0?{namespace:t.namespace}:{}})}if(r.length===0)continue;o.push(...r)}else if(t.role===`toolResult`){let[n]=t.toolCallId.split(`|`),r=f(e,t.content);i?.grammarToolInputProperties?.has(t.toolName)?o.push({type:`custom_tool_call_output`,call_id:n,output:r}):o.push({type:`function_call_output`,call_id:n,output:r});let a=[];for(let e of t.addedToolNames??[]){let t=i?.deferredTools?.get(e);!t||c.has(e)||(c.add(e),a.push(t))}if(a.length>0&&i?.deferredToolsMode===`additional-tools`)o.push({type:`additional_tools`,role:`developer`,tools:m(a,i.toolOptions)});else if(a.length>0&&i?.deferredToolsMode===`tool-search`){let e=a.map(e=>e.name),n=`pi_tool_load_${l(`${t.toolCallId}:${e.join(`,`)}`)}`;o.push({type:`tool_search_call`,call_id:n,execution:`client`,status:`completed`,arguments:{query:e.join(` `),limit:e.length}}),o.push({type:`tool_search_output`,call_id:n,execution:`client`,status:`completed`,tools:m(a,{...i.toolOptions,deferLoading:!0})})}}g++}return o}function m(e,t){let n=t?.strict===void 0?!1:t.strict,a=t?.supportsStrictMode??!0,o=t?.supportsOpenAIGrammarTools??!1;return e.map(e=>{let s=r(e,o);if(s)return{type:`custom`,name:e.name,description:e.description,format:{type:`grammar`,syntax:s.format,definition:s.definition},...t?.deferLoading?{defer_loading:!0}:{}};let l=i(e,a)??n,u={type:`function`,name:e.name,description:e.description,parameters:c(e,l===!0),...t?.deferLoading?{defer_loading:!0}:{}};return a&&(u.strict=l),u})}function h(e){let t=e.customInput?.property;if(t===void 0)return``;let n=e.arguments[t];return typeof n==`string`?n:``}function g(e,t,n){let r=e.customInput;if(!r)return;let i=o(r.jsonBuffer,r.property,t,n);return e.arguments={[r.property]:t},i}async function _(n,r,i,a,o){let s=!1,c=new Map,l=new Map,d=e=>{e.type===`message`&&e.phase===`final_answer`&&(r.stopReason=`stop`)},f=(e,t)=>{let n=c.get(e);return n?.type===t?n:void 0},p=(e,t)=>{t!==void 0&&i.push({type:`toolcall_delta`,contentIndex:e.contentIndex,delta:t,partial:r})},m=(e,t)=>{if(t.type===`reasoning`){let t={type:`thinking`,thinking:``};r.content.push(t);let n={type:`thinking`,block:t,contentIndex:r.content.length-1};return c.set(e,n),i.push({type:`thinking_start`,contentIndex:n.contentIndex,partial:r}),n}if(t.type===`message`){d(t);let n={type:`text`,text:``};r.content.push(n);let a={type:`text`,block:n,contentIndex:r.content.length-1};return c.set(e,a),i.push({type:`text_start`,contentIndex:a.contentIndex,partial:r}),a}if(t.type===`function_call`){let n={type:`toolCall`,id:`${t.call_id}|${t.id}`,name:t.name,arguments:{},...t.namespace===void 0?{}:{namespace:t.namespace},partialJson:t.arguments||``};r.content.push(n);let a={type:`toolCall`,block:n,contentIndex:r.content.length-1};return c.set(e,a),i.push({type:`toolcall_start`,contentIndex:a.contentIndex,partial:r}),a}if(t.type===`custom_tool_call`){let n=o?.grammarToolInputProperties?.get(t.name)??`input`,a=t.input||``,s={type:`toolCall`,id:`${t.call_id}|${t.id}`,name:t.name,arguments:{[n]:a},...t.namespace===void 0?{}:{namespace:t.namespace},customInput:{property:n,jsonBuffer:{input:``,started:!1,closed:!1}}};r.content.push(s);let l={type:`toolCall`,block:s,contentIndex:r.content.length-1};return c.set(e,l),i.push({type:`toolcall_start`,contentIndex:l.contentIndex,partial:r}),l}},_=(e,t)=>c.get(e)??m(e,t),y=e=>{for(let t of e){if(t.type!==`reasoning`||!t.encrypted_content)continue;let e=l.get(t.id);if(!e?.thinkingSignature)continue;let n=JSON.parse(e.thinkingSignature);n.encrypted_content||(e.thinkingSignature=JSON.stringify({...n,encrypted_content:t.encrypted_content}))}},b=t=>{if(s=!0,y(t.output??[]),t?.id&&(r.responseId=t.id),t?.usage){let e=t.usage.input_tokens_details,n=e?.cached_tokens||0,i=e?.cache_write_tokens||0;r.usage={input:Math.max(0,(t.usage.input_tokens||0)-n-i),output:t.usage.output_tokens||0,cacheRead:n,cacheWrite:i,reasoning:t.usage.output_tokens_details?.reasoning_tokens||0,totalTokens:t.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(e(a,r.usage),o?.applyServiceTierPricing){let e=o.resolveServiceTier?o.resolveServiceTier(t?.service_tier,o.serviceTier):t?.service_tier??o.serviceTier;o.applyServiceTierPricing(r.usage,e)}let n=t?.status,i=t?.incomplete_details,c=typeof i?.reason==`string`?i.reason:void 0;r.rawStopReason=c?`${n}.${c}`:n;let l=v(n,c);r.stopReason=l.stopReason,r.errorMessage=l.errorMessage,r.content.some(e=>e.type===`toolCall`)&&r.stopReason===`stop`&&(r.stopReason=`toolUse`)};for await(let e of n)if(e.type===`response.created`)r.responseId=e.response.id;else if(e.type===`response.output_item.added`)m(e.output_index,e.item);else if(e.type===`response.reasoning_summary_text.delta`){let t=f(e.output_index,`thinking`);if(!t)continue;t.block.thinking+=e.delta,i.push({type:`thinking_delta`,contentIndex:t.contentIndex,delta:e.delta,partial:r})}else if(e.type===`response.reasoning_summary_part.done`){let t=f(e.output_index,`thinking`);if(!t)continue;t.block.thinking+=`
|
|
4
|
+
|
|
5
|
+
`,i.push({type:`thinking_delta`,contentIndex:t.contentIndex,delta:`
|
|
6
|
+
|
|
7
|
+
`,partial:r})}else if(e.type===`response.reasoning_text.delta`){let t=f(e.output_index,`thinking`);if(!t)continue;t.block.thinking+=e.delta,i.push({type:`thinking_delta`,contentIndex:t.contentIndex,delta:e.delta,partial:r})}else if(e.type===`response.output_text.delta`){let t=f(e.output_index,`text`);if(!t)continue;t.block.text+=e.delta,i.push({type:`text_delta`,contentIndex:t.contentIndex,delta:e.delta,partial:r})}else if(e.type===`response.refusal.delta`){let t=f(e.output_index,`text`);if(!t)continue;t.block.text+=e.delta,i.push({type:`text_delta`,contentIndex:t.contentIndex,delta:e.delta,partial:r})}else if(e.type===`response.function_call_arguments.delta`){let n=f(e.output_index,`toolCall`);if(!n||n.block.partialJson===void 0)continue;n.block.partialJson+=e.delta,n.block.arguments=t(n.block.partialJson),p(n,e.delta)}else if(e.type===`response.function_call_arguments.done`){let n=f(e.output_index,`toolCall`);if(!n||n.block.partialJson===void 0)continue;let r=n.block.partialJson;if(n.block.partialJson=e.arguments,n.block.arguments=t(n.block.partialJson),e.arguments.startsWith(r)){let t=e.arguments.slice(r.length);t.length>0&&p(n,t)}}else if(e.type===`response.custom_tool_call_input.delta`){let t=f(e.output_index,`toolCall`);if(!t||!t.block.customInput)continue;p(t,g(t.block,h(t.block)+e.delta,!1))}else if(e.type===`response.custom_tool_call_input.done`){let t=f(e.output_index,`toolCall`);if(!t||!t.block.customInput)continue;p(t,g(t.block,e.input,!0))}else if(e.type===`response.output_item.done`){let n=e.item;d(n);let a=_(e.output_index,n);if(n.type===`reasoning`&&a?.type===`thinking`){let t=n.summary?.map(e=>e.text).join(`
|
|
8
|
+
|
|
9
|
+
`)||``,o=n.content?.map(e=>e.text).join(`
|
|
10
|
+
|
|
11
|
+
`)||``;a.block.thinking=t||o||a.block.thinking,a.block.thinkingSignature=JSON.stringify(n),l.set(n.id,a.block),i.push({type:`thinking_end`,contentIndex:a.contentIndex,content:a.block.thinking,partial:r}),c.delete(e.output_index)}else n.type===`message`&&a?.type===`text`?(a.block.text=n.content?.map(e=>e.type===`output_text`?e.text:e.refusal).join(``)||``,a.block.textSignature=u(n.id,n.phase??void 0),i.push({type:`text_end`,contentIndex:a.contentIndex,content:a.block.text,partial:r}),c.delete(e.output_index)):n.type===`function_call`&&a?.type===`toolCall`&&a.block.partialJson!==void 0?(a.block.arguments=t(n.arguments||a.block.partialJson||`{}`),n.namespace!==void 0&&(a.block.namespace=n.namespace),delete a.block.partialJson,i.push({type:`toolcall_end`,contentIndex:a.contentIndex,toolCall:a.block,partial:r}),c.delete(e.output_index)):n.type===`custom_tool_call`&&a?.type===`toolCall`&&a.block.customInput&&(p(a,g(a.block,n.input??h(a.block),!0)),n.namespace!==void 0&&(a.block.namespace=n.namespace),delete a.block.customInput,i.push({type:`toolcall_end`,contentIndex:a.contentIndex,toolCall:a.block,partial:r}),c.delete(e.output_index))}else if(e.type===`response.completed`||e.type===`response.incomplete`)b(e.response);else if(e.type===`error`)throw Error(`Error Code ${e.code}: ${e.message}`||`Unknown error`);else if(e.type===`response.failed`){s=!0,r.rawStopReason=e.response?.status;let t=e.response?.error,n=e.response?.incomplete_details,i=t?`${t.code||`unknown`}: ${t.message||`no message`}`:n?.reason?`incomplete: ${n.reason}`:`Unknown error (no error details in response)`;throw Error(i)}if(!s)throw Error(`OpenAI Responses stream ended before a terminal response event`)}function v(e,t){if(!e)return{stopReason:`stop`};switch(e){case`completed`:return{stopReason:`stop`};case`incomplete`:return t===`max_output_tokens`?{stopReason:`length`}:{stopReason:`error`,errorMessage:t?`Response incomplete: ${t}`:`Response incomplete without a provider reason`};case`failed`:case`cancelled`:return{stopReason:`error`};case`in_progress`:case`queued`:return{stopReason:`stop`};default:{let t=e;throw Error(`Unhandled stop reason: ${t}`)}}}export{m as n,_ as r,p as t};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{n as e,t}from"./headers-BvGum5dc.mjs";import{t as n}from"./provider-retry-
|
|
2
|
+
import{n as e,t}from"./headers-BvGum5dc.mjs";import{t as n}from"./provider-retry-wOYAq0sa.mjs";import{t as r}from"./sanitize-unicode-Byz9nlLd.mjs";import{n as i}from"./openai-CbFQ5q5I.mjs";import{n as a,t as o}from"./error-body-BBlqjbe7.mjs";const s=async(e,r,i)=>{let s={api:e.api,provider:e.provider,model:e.id,output:[],stopReason:`stop`,timestamp:Date.now()};try{let a=i?.apiKey;if(!a)throw Error(`No API key for provider: ${e.provider}`);let o=c(e,a,i?.headers,i?.fetch),d=l(e,r),f=await i?.onPayload?.(d,e);f!==void 0&&(d=f);let p={...i?.signal?{signal:i.signal}:{},...i?.timeoutMs===void 0?{}:{timeout:i.timeoutMs},maxRetries:0},{data:m,response:h}=await n(()=>o.chat.completions.create(d,p).withResponse(),{maxRetries:i?.maxRetries,maxRetryDelayMs:i?.maxRetryDelayMs,signal:i?.signal});await i?.onResponse?.({status:h.status,headers:t(h.headers)},e);let g=m;s.responseId=g.id,g.usage&&(s.usage=u(g.usage,e));let _=g.choices[0];if(_){let e=_.message.content;typeof e==`string`&&e.length>0&&s.output.push({type:`text`,text:e});for(let e of _.message.images??[]){let t=typeof e.image_url==`string`?e.image_url:e.image_url?.url;if(!t?.startsWith(`data:`))continue;let n=t.match(/^data:([^;]+);base64,(.+)$/);n&&s.output.push({type:`image`,mimeType:n[1],data:n[2]})}}return s}catch(e){return s.stopReason=i?.signal?.aborted?`aborted`:`error`,s.errorMessage=o(a(e)),s}};function c(t,n,r,a){return new i({apiKey:n,baseURL:t.baseUrl,dangerouslyAllowBrowser:!0,fetch:a,defaultHeaders:e({...t.headers,...r})})}function l(e,t){let n=t.input.map(e=>e.type===`text`?{type:`text`,text:r(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}});return{model:e.id,messages:[{role:`user`,content:n}],stream:!1,modalities:e.output.includes(`text`)?[`image`,`text`]:[`image`]}}function u(e,t){let n=e.prompt_tokens||0,r=e.prompt_tokens_details?.cached_tokens||0,i=e.prompt_tokens_details?.cache_write_tokens||0,a=i>0?Math.max(0,r-i):r,o=Math.max(0,n-a-i),s=e.completion_tokens||0,c={input:o,output:s,cacheRead:a,cacheWrite:i,totalTokens:o+s+a+i,cost:{input:t.cost.input/1e6*o,output:t.cost.output/1e6*s,cacheRead:t.cost.cacheRead/1e6*a,cacheWrite:t.cost.cacheWrite/1e6*i,total:0}};return c.cost.total=c.cost.input+c.cost.output+c.cost.cacheRead+c.cost.cacheWrite,c}export{s as generateImages};
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|