@swifty.js/swifty 0.0.7 → 0.0.9

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.
@@ -1,27 +1,27 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __swiftyCreateRequire } from "node:module";
3
3
  const require = __swiftyCreateRequire(import.meta.url);
4
- import{g as Zs,h as en}from"./chunk-GS6BRESU.js";import{b as Gs,c as Xn,d as gs,e as Gn,f as Qn,g as Yn}from"./chunk-FZPTNGTU.js";import"./chunk-7MHXMDYC.js";import{I as Jn,J as Dr,K as Qs,L as ys,M as Ys,R as Vn}from"./chunk-ISXLT3QN.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";function x(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t}function c(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)}var He=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return He=s.randomUUID.bind(s),s.randomUUID();let e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function zr(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}var qr=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){let e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)};var g=class extends Error{},F=class s extends g{constructor(e,t,r,n){super(`${s.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,r){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new Se({message:r,cause:qr(t)});let o=t?.error;return e===400?new Pt(e,o,r,n):e===401?new xt(e,o,r,n):e===403?new Rt(e,o,r,n):e===404?new St(e,o,r,n):e===409?new Ct(e,o,r,n):e===422?new kt(e,o,r,n):e===429?new $t(e,o,r,n):e>=500?new Et(e,o,r,n):new s(e,o,r,n)}},M=class extends F{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Se=class extends F{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Ce=class extends Se{constructor({message:e}={}){super({message:e??"Request timed out."})}},Pt=class extends F{},xt=class extends F{},Rt=class extends F{},St=class extends F{},Ct=class extends F{},kt=class extends F{},$t=class extends F{},Et=class extends F{},Ot=class extends g{constructor(){super("Could not parse response content as the length limit was reached")}},vt=class extends g{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},pe=class extends Error{constructor(e){super(e)}},We=class extends F{constructor(e,t,r){let n="OAuth2 authentication error",o;if(t&&typeof t=="object"){let a=t;o=a.error;let l=a.error_description;l&&typeof l=="string"?n=l:o&&(n=o)}super(e,t,n,r),this.error_code=o}},Hr=class extends g{constructor(e,t,r){super(e),this.provider=t,this.cause=r}};var _i=/^[a-z][a-z0-9+.-]*:/i,Zn=s=>_i.test(s),X=s=>(X=Array.isArray,X(s)),tn=X;function As(s){return typeof s!="object"?{}:s??{}}function rn(s){if(!s)return!0;for(let e in s)return!1;return!0}function eo(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function Wr(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var to=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new g(`${s} must be an integer`);if(e<0)throw new g(`${s} must be a positive integer`);return e};var ro=s=>{try{return JSON.parse(s)}catch{return}};var de=s=>new Promise(e=>setTimeout(e,s));var ke="6.49.0";var io=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function yi(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var gi=()=>{let s=yi();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":no(Deno.build.os),"X-Stainless-Arch":so(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":ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":no(globalThis.process.platform??"unknown"),"X-Stainless-Arch":so(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Ai();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Ai(){if(typeof navigator>"u"||!navigator)return null;let s=[{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/}];for(let{key:e,pattern:t}of s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,o=r[2]||0,a=r[3]||0;return{browser:e,version:`${n}.${o}.${a}`}}}return null}var so=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",no=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),oo,ao=()=>oo??(oo=gi());function bs(){if(typeof fetch<"u")return fetch;throw new 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 sn(...s){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...s)}function Jr(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return sn({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function ws(s){if(s[Symbol.asyncIterator])return s;let e=s.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function nn(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}let e=s.getReader(),t=e.cancel();e.releaseLock(),await t}var co=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var on="RFC3986",an=s=>String(s),un={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:an},lo="RFC1738";var Is=(s,e)=>(Is=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Is(s,e)),me=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var cn=1024,po=(s,e,t,r,n)=>{if(s.length===0)return s;let o=s;if(typeof s=="symbol"?o=Symbol.prototype.toString.call(s):typeof s!="string"&&(o=String(s)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let a="";for(let l=0;l<o.length;l+=cn){let m=o.length>=cn?o.slice(l,l+cn):o,p=[];for(let _=0;_<m.length;++_){let f=m.charCodeAt(_);if(f===45||f===46||f===95||f===126||f>=48&&f<=57||f>=65&&f<=90||f>=97&&f<=122||n===lo&&(f===40||f===41)){p[p.length]=m.charAt(_);continue}if(f<128){p[p.length]=me[f];continue}if(f<2048){p[p.length]=me[192|f>>6]+me[128|f&63];continue}if(f<55296||f>=57344){p[p.length]=me[224|f>>12]+me[128|f>>6&63]+me[128|f&63];continue}_+=1,f=65536+((f&1023)<<10|m.charCodeAt(_)&1023),p[p.length]=me[240|f>>18]+me[128|f>>12&63]+me[128|f>>6&63]+me[128|f&63]}a+=p.join("")}return a};function mo(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function ln(s,e){if(X(s)){let t=[];for(let r=0;r<s.length;r+=1)t.push(e(s[r]));return t}return e(s)}var fo={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},_o=function(s,e){Array.prototype.push.apply(s,X(e)?e:[e])},ho,D={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:po,encodeValuesOnly:!1,format:on,formatter:an,indices:!1,serializeDate(s){return(ho??(ho=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function wi(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var pn={};function yo(s,e,t,r,n,o,a,l,m,p,_,f,d,b,I,A,w,k){let y=s,P=k,R=0,v=!1;for(;(P=P.get(pn))!==void 0&&!v;){let T=P.get(s);if(R+=1,typeof T<"u"){if(T===R)throw new RangeError("Cyclic object value");v=!0}typeof P.get(pn)>"u"&&(R=0)}if(typeof p=="function"?y=p(e,y):y instanceof Date?y=d?.(y):t==="comma"&&X(y)&&(y=ln(y,function(T){return T instanceof Date?d?.(T):T})),y===null){if(o)return m&&!A?m(e,D.encoder,w,"key",b):e;y=""}if(wi(y)||mo(y)){if(m){let T=A?e:m(e,D.encoder,w,"key",b);return[I?.(T)+"="+I?.(m(y,D.encoder,w,"value",b))]}return[I?.(e)+"="+I?.(String(y))]}let $=[];if(typeof y>"u")return $;let L;if(t==="comma"&&X(y))A&&m&&(y=ln(y,m)),L=[{value:y.length>0?y.join(",")||null:void 0}];else if(X(p))L=p;else{let T=Object.keys(y);L=_?T.sort(_):T}let j=l?String(e).replace(/\./g,"%2E"):String(e),N=r&&X(y)&&y.length===1?j+"[]":j;if(n&&X(y)&&y.length===0)return N+"[]";for(let T=0;T<L.length;++T){let W=L[T],It=typeof W=="object"&&typeof W.value<"u"?W.value:y[W];if(a&&It===null)continue;let J=f&&l?W.replace(/\./g,"%2E"):W,fs=X(y)?typeof t=="function"?t(N,J):N:N+(f?"."+J:"["+J+"]");k.set(s,R);let _s=new WeakMap;_s.set(pn,k),_o($,yo(It,fs,t,r,n,o,a,l,t==="comma"&&A&&X(y)?null:m,p,_,f,d,b,I,A,w,_s))}return $}function Ii(s=D){if(typeof s.allowEmptyArrays<"u"&&typeof s.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys<"u"&&typeof s.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder<"u"&&typeof s.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=s.charset||D.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=on;if(typeof s.format<"u"){if(!Is(un,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=un[t],n=D.filter;(typeof s.filter=="function"||X(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in fo?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=D.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:D.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:D.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:D.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:D.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?D.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:D.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:D.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:D.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:D.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:D.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:D.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:D.strictNullHandling}}function go(s,e={}){let t=s,r=Ii(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):X(r.filter)&&(o=r.filter,n=o);let a=[];if(typeof t!="object"||t===null)return"";let l=fo[r.arrayFormat],m=l==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let p=new WeakMap;for(let d=0;d<n.length;++d){let b=n[d];r.skipNulls&&t[b]===null||_o(a,yo(t[b],b,l,m,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,p))}let _=a.join(r.delimiter),f=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?f+="utf8=%26%2310003%3B&":f+="utf8=%E2%9C%93&"),_.length>0?f+_:""}function Ao(s){return go(s,{arrayFormat:"brackets"})}function Io(s){let e=0;for(let n of s)e+=n.length;let t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var bo;function ee(s){let e;return(bo??(e=new globalThis.TextEncoder,bo=e.encode.bind(e)))(s)}var wo;function dn(s){let e;return(wo??(e=new globalThis.TextDecoder,wo=e.decode.bind(e)))(s)}var te,re,Je=class{constructor(){te.set(this,void 0),re.set(this,void 0),x(this,te,new Uint8Array,"f"),x(this,re,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ee(e):e;x(this,te,Io([c(this,te,"f"),t]),"f");let r=[],n;for(;(n=xi(c(this,te,"f"),c(this,re,"f")))!=null;){if(n.carriage&&c(this,re,"f")==null){x(this,re,n.index,"f");continue}if(c(this,re,"f")!=null&&(n.index!==c(this,re,"f")+1||n.carriage)){r.push(dn(c(this,te,"f").subarray(0,c(this,re,"f")-1))),x(this,te,c(this,te,"f").subarray(c(this,re,"f")),"f"),x(this,re,null,"f");continue}let o=c(this,re,"f")!==null?n.preceding-1:n.preceding,a=dn(c(this,te,"f").subarray(0,o));r.push(a),x(this,te,c(this,te,"f").subarray(n.index),"f"),x(this,re,null,"f")}return r}flush(){return c(this,te,"f").length?this.decode(`
5
- `):[]}};te=new WeakMap,re=new WeakMap;Je.NEWLINE_CHARS=new Set([`
6
- `,"\r"]);Je.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function xi(s,e){for(let n=e??0;n<s.length;n++){if(s[n]===10)return{preceding:n,index:n+1,carriage:!1};if(s[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Po(s){for(let r=0;r<s.length-1;r++){if(s[r]===10&&s[r+1]===10||s[r]===13&&s[r+1]===13)return r+2;if(s[r]===13&&s[r+1]===10&&r+3<s.length&&s[r+2]===13&&s[r+3]===10)return r+4}return-1}var xs={off:0,error:200,warn:300,info:400,debug:500},mn=(s,e,t)=>{if(s){if(eo(xs,s))return s;K(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(xs))}`)}};function Vr(){}function Ps(s,e,t){return!e||xs[s]>xs[t]?Vr:e[s].bind(e)}var Ri={error:Vr,warn:Vr,info:Vr,debug:Vr},xo=new WeakMap;function K(s){let e=s.logger,t=s.logLevel??"off";if(!e)return Ri;let r=xo.get(e);if(r&&r[0]===t)return r[1];let n={error:Ps("error",e,t),warn:Ps("warn",e,t),info:Ps("info",e,t),debug:Ps("debug",e,t)};return xo.set(e,[t,n]),n}var ye=s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="x-amz-security-token"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s);var Xr,Z=class s{constructor(e,t,r){this.iterator=e,Xr.set(this,void 0),this.controller=t,x(this,Xr,r,"f")}static fromSSEResponse(e,t,r,n){let o=!1,a=r?K(r):console;async function*l(){if(o)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let m=!1;try{for await(let p of Si(e,t))if(!m){if(p.data.startsWith("[DONE]")){m=!0;continue}if(p.event===null||!p.event.startsWith("thread.")){let _;try{_=JSON.parse(p.data)}catch(f){throw a.error("Could not parse message into JSON:",p.data),a.error("From chunk:",p.raw),f}if(_&&_.error)throw new F(void 0,_.error,void 0,e.headers);yield n?{event:p.event,data:_}:_}else{let _;try{_=JSON.parse(p.data)}catch(f){throw console.error("Could not parse message into JSON:",p.data),console.error("From chunk:",p.raw),f}if(p.event=="error")throw new F(void 0,_.error,_.message,void 0);yield{event:p.event,data:_}}}m=!0}catch(p){if(zr(p))return;throw p}finally{m||t.abort()}}return new s(l,t,r)}static fromReadableStream(e,t,r){let n=!1;async function*o(){let l=new Je,m=e.getReader(),p=!1,_,f=()=>{_??(_=m.cancel()),_.catch(()=>{})};t.signal.addEventListener("abort",f,{once:!0});try{if(t.signal.aborted){f();return}for(;;){let{value:d,done:b}=await m.read();if(b){p=!0;break}if(t.signal.aborted)return;for(let I of l.decode(d)){if(t.signal.aborted)return;yield I}}if(t.signal.aborted)return;for(let d of l.flush()){if(t.signal.aborted)return;yield d}}finally{t.signal.removeEventListener("abort",f),p||f(),m.releaseLock()}}async function*a(){if(n)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let l=!1;try{for await(let m of o())l||m&&(yield JSON.parse(m));l=!0}catch(m){if(t.signal.aborted||zr(m))return;throw m}finally{l||t.abort()}}return new s(a,t,r)}[(Xr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=o=>({next:()=>{if(o.length===0){let a=r.next();e.push(a),t.push(a)}return o.shift()}});return[new s(()=>n(e),this.controller,c(this,Xr,"f")),new s(()=>n(t),this.controller,c(this,Xr,"f"))]}toReadableStream(){let e=this,t;return sn({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:n,done:o}=await t.next();if(o)return r.close();let a=ee(JSON.stringify(n)+`
7
- `);r.enqueue(a)}catch(n){r.error(n)}},async cancel(){await t.return?.()}})}};async function*Si(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new g("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 g("Attempted to iterate over a response with no body");let t=new hn,r=new Je,n=ws(s.body);for await(let o of Ci(n))for(let a of r.decode(o)){let l=t.decode(a);l&&(yield l)}for(let o of r.flush()){let a=t.decode(o);a&&(yield a)}}async function*Ci(s){let e=new Uint8Array;for await(let t of s){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?ee(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let o;for(;(o=Po(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var hn=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 o={event:this.event,data:this.data.join(`
8
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=ki(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function ki(s,e){let t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}async function Rs(s,e){let{response:t,requestLogID:r,retryOfRequestLogID:n,startTime:o}=e,a=await(async()=>{if(e.options.stream)return K(s).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,s,e.options.__synthesizeEventData):Z.fromSSEResponse(t,e.controller,s,e.options.__synthesizeEventData);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let m=t.headers.get("content-type")?.split(";")[0]?.trim();if(m?.includes("application/json")||m?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;let d=await t.json();return fn(d,t)}return await t.text()})();return K(s).debug(`[${r}] response parsed`,ye({retryOfRequestLogID:n,url:t.url,status:t.status,body:a,durationMs:Date.now()-o})),a}function fn(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Gr,Ve=class s extends Promise{constructor(e,t,r=Rs){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=r,Gr.set(this,void 0),x(this,Gr,e,"f")}_thenUnwrap(e){return new s(c(this,Gr,"f"),this.responsePromise,async(t,r)=>fn(e(await this.parseResponse(t,r),r),r.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.parsedPromise=this.responsePromise.then(e=>this.parseResponse(c(this,Gr,"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)}};Gr=new WeakMap;var Ss,Tt=class{constructor(e,t,r,n){Ss.set(this,void 0),x(this,Ss,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new g("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await c(this,Ss,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ss=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Qr=class extends Ve{constructor(e,t,r){super(e,t,async(n,o)=>new r(n,o.response,await Rs(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},G=class extends Tt{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},C=class extends Tt{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.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:{...As(this.options.query),after:t}}:null}},O=class extends Tt{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.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:{...As(this.options.query),after:e}}:null}},U=class extends Tt{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.next=r.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:{...As(this.options.query),after:e}}:null}};var Ei={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},Oi="urn:ietf:params:oauth:grant-type:token-exchange",Cs=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=t??bs()}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=await this.config.provider.getToken(),t={grant_type:Oi,subject_token:e,subject_token_type:Ei[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(t.client_id=this.config.clientId);let r=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let m=await r.text(),p;try{p=JSON.parse(m)}catch{}throw r.status===400||r.status===401||r.status===403?new We(r.status,p,r.headers):F.generate(r.status,p,`Token exchange failed with status ${r.status}`,r.headers)}let n=await r.json();if(typeof n!="object"||n===null||!("access_token"in n)||typeof n.access_token!="string"||n.access_token.trim().length===0)throw new g("Token exchange response missing 'access_token' field");let o=n.access_token,a=n.expires_in??3600,l=Date.now()+a*1e3;return this.cachedToken={token:o,expiresAt:l},o}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let r=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-r}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var Ro=Symbol("brand.privateNullableHeaders"),vi=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function*Ti(s){if(!s)return;if(Ro in s){let{values:r,nulls:n}=s;yield*r.entries();for(let o of n)yield[o,null];return}let e=!1,t;s instanceof Headers?t=s.entries():tn(s)?t=s:(e=!0,t=Object.entries(s??{}));for(let r of t){let n=r[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let o=tn(r[1])?r[1]:[r[1]],a=!1;for(let l of o)l!==void 0&&(e&&!a&&(a=!0,yield[n,null]),yield[n,l])}}var h=s=>{let e=new Headers,t=new Set;for(let r of s){let n=new Set;for(let[o,a]of Ti(r)){if(!vi.test(o))throw new TypeError(`Header name must be a valid HTTP token ["${o}"]`);let l=o.toLowerCase();n.has(l)||(e.delete(l),n.add(l)),a===null?(e.delete(l),t.add(l)):(e.append(l,a),t.delete(l))}}return{[Ro]:!0,values:e,nulls:t}};var Co=Symbol("brand.privateStreamingFile");function $s(s,e,t){if(!e)throw new TypeError("toStreamingFile requires a non-empty file name");return{[Co]:!0,data:s,name:e,...t?.type?{type:t.type}:{}}}var bn=()=>{if(typeof File>"u"){let{process:s}=globalThis,e=typeof s?.versions?.node=="string"&&parseInt(s.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Ft(s,e,t){return bn(),new File(s,e??"unknown_file",t)}function Nt(s){return(typeof s=="object"&&s!==null&&("name"in s&&s.name&&String(s.name)||"url"in s&&s.url&&String(s.url)||"filename"in s&&s.filename&&String(s.filename)||"path"in s&&s.path&&String(s.path))||"").split(/[\\/]/).pop()||void 0}var Lt=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",$e=async(s,e)=>yn(s.body)?ks(s.body)?$o(s):{...s,body:await ko(s.body,e)}:s,Q=async(s,e)=>ks(s.body)?$o(s):{...s,body:await ko(s.body,e)},So=new WeakMap;function ji(s){let e=typeof s=="function"?s:s.fetch,t=So.get(e);if(t)return t;let r=(async()=>{try{let n="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new n(o).text()}catch{return!0}})();return So.set(e,r),r}var ko=async(s,e)=>{if(!await ji(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let t=new FormData;return await Promise.all(Object.entries(s||{}).map(([r,n])=>An(t,r,n))),t},Es=s=>s instanceof Blob&&"name"in s,wn=s=>typeof s=="object"&&s!==null&&"getReader"in s&&typeof s.getReader=="function",Yr=s=>typeof s=="object"&&s!==null&&Co in s,In=s=>typeof s=="object"&&s!==null&&(s instanceof Response||Lt(s)||wn(s)||Yr(s)||Es(s)),ks=s=>{if(Yr(s)||Lt(s)||wn(s))return!0;if(Array.isArray(s))return s.some(ks);if(s&&typeof s=="object"&&!Es(s)&&!(s instanceof Response)){for(let e in s)if(ks(s[e]))return!0}return!1},yn=s=>{if(In(s))return!0;if(Array.isArray(s))return s.some(yn);if(s&&typeof s=="object"){for(let e in s)if(yn(s[e]))return!0}return!1},$o=s=>{let e=`openai-${Math.random().toString(36).slice(2)}`,t=Jr(Ni(s.body,e));return{...s,body:t,headers:h([{"content-type":`multipart/form-data; boundary=${e}`},s.headers])}};async function*Ni(s,e){for await(let{key:t,value:r}of Fi(s)){if(yield ee(`--${e}\r
9
- `),In(r)){let n=Li(r),o=Mi(r);yield ee(`Content-Disposition: form-data; name="${_n(t)}"; filename="${_n(n)}"\r
4
+ import{g as tn,h as rn}from"./chunk-OZOP4GVS.js";import{b as Zs,c as Gn,d as Is,e as Qn,f as Yn,g as Zn}from"./chunk-FZPTNGTU.js";import"./chunk-7MHXMDYC.js";import{I as Xn,J as qr,K as He,L as As,M as bs,N as en,S as xt}from"./chunk-XYSBNUNB.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";function x(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t}function c(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)}var We=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return We=s.randomUUID.bind(s),s.randomUUID();let e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function Hr(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}var Wr=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){let e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)};var g=class extends Error{},F=class s extends g{constructor(e,t,r,n){super(`${s.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,r){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new Se({message:r,cause:Wr(t)});let o=t?.error;return e===400?new Rt(e,o,r,n):e===401?new St(e,o,r,n):e===403?new Ct(e,o,r,n):e===404?new kt(e,o,r,n):e===409?new $t(e,o,r,n):e===422?new Et(e,o,r,n):e===429?new Ot(e,o,r,n):e>=500?new vt(e,o,r,n):new s(e,o,r,n)}},M=class extends F{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Se=class extends F{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Ce=class extends Se{constructor({message:e}={}){super({message:e??"Request timed out."})}},Rt=class extends F{},St=class extends F{},Ct=class extends F{},kt=class extends F{},$t=class extends F{},Et=class extends F{},Ot=class extends F{},vt=class extends F{},Tt=class extends g{constructor(){super("Could not parse response content as the length limit was reached")}},jt=class extends g{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},pe=class extends Error{constructor(e){super(e)}},Je=class extends F{constructor(e,t,r){let n="OAuth2 authentication error",o;if(t&&typeof t=="object"){let a=t;o=a.error;let l=a.error_description;l&&typeof l=="string"?n=l:o&&(n=o)}super(e,t,n,r),this.error_code=o}},Jr=class extends g{constructor(e,t,r){super(e),this.provider=t,this.cause=r}};var yi=/^[a-z][a-z0-9+.-]*:/i,eo=s=>yi.test(s),X=s=>(X=Array.isArray,X(s)),sn=X;function ws(s){return typeof s!="object"?{}:s??{}}function nn(s){if(!s)return!0;for(let e in s)return!1;return!0}function to(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function Vr(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var ro=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new g(`${s} must be an integer`);if(e<0)throw new g(`${s} must be a positive integer`);return e};var so=s=>{try{return JSON.parse(s)}catch{return}};var de=s=>new Promise(e=>setTimeout(e,s));var ke="6.49.0";var ao=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function gi(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var Ai=()=>{let s=gi();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":oo(Deno.build.os),"X-Stainless-Arch":no(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":ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":oo(globalThis.process.platform??"unknown"),"X-Stainless-Arch":no(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=bi();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function bi(){if(typeof navigator>"u"||!navigator)return null;let s=[{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/}];for(let{key:e,pattern:t}of s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,o=r[2]||0,a=r[3]||0;return{browser:e,version:`${n}.${o}.${a}`}}}return null}var no=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",oo=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),io,uo=()=>io??(io=Ai());function Ps(){if(typeof fetch<"u")return fetch;throw new 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 on(...s){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...s)}function Xr(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return on({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function xs(s){if(s[Symbol.asyncIterator])return s;let e=s.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function an(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}let e=s.getReader(),t=e.cancel();e.releaseLock(),await t}var lo=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var un="RFC3986",cn=s=>String(s),ln={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:cn},po="RFC1738";var Rs=(s,e)=>(Rs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Rs(s,e)),fe=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var pn=1024,fo=(s,e,t,r,n)=>{if(s.length===0)return s;let o=s;if(typeof s=="symbol"?o=Symbol.prototype.toString.call(s):typeof s!="string"&&(o=String(s)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let a="";for(let l=0;l<o.length;l+=pn){let f=o.length>=pn?o.slice(l,l+pn):o,p=[];for(let _=0;_<f.length;++_){let m=f.charCodeAt(_);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||n===po&&(m===40||m===41)){p[p.length]=f.charAt(_);continue}if(m<128){p[p.length]=fe[m];continue}if(m<2048){p[p.length]=fe[192|m>>6]+fe[128|m&63];continue}if(m<55296||m>=57344){p[p.length]=fe[224|m>>12]+fe[128|m>>6&63]+fe[128|m&63];continue}_+=1,m=65536+((m&1023)<<10|f.charCodeAt(_)&1023),p[p.length]=fe[240|m>>18]+fe[128|m>>12&63]+fe[128|m>>6&63]+fe[128|m&63]}a+=p.join("")}return a};function ho(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function dn(s,e){if(X(s)){let t=[];for(let r=0;r<s.length;r+=1)t.push(e(s[r]));return t}return e(s)}var _o={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},yo=function(s,e){Array.prototype.push.apply(s,X(e)?e:[e])},mo,D={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:fo,encodeValuesOnly:!1,format:un,formatter:cn,indices:!1,serializeDate(s){return(mo??(mo=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function wi(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var fn={};function go(s,e,t,r,n,o,a,l,f,p,_,m,d,b,w,A,I,k){let y=s,P=k,R=0,v=!1;for(;(P=P.get(fn))!==void 0&&!v;){let T=P.get(s);if(R+=1,typeof T<"u"){if(T===R)throw new RangeError("Cyclic object value");v=!0}typeof P.get(fn)>"u"&&(R=0)}if(typeof p=="function"?y=p(e,y):y instanceof Date?y=d?.(y):t==="comma"&&X(y)&&(y=dn(y,function(T){return T instanceof Date?d?.(T):T})),y===null){if(o)return f&&!A?f(e,D.encoder,I,"key",b):e;y=""}if(wi(y)||ho(y)){if(f){let T=A?e:f(e,D.encoder,I,"key",b);return[w?.(T)+"="+w?.(f(y,D.encoder,I,"value",b))]}return[w?.(e)+"="+w?.(String(y))]}let $=[];if(typeof y>"u")return $;let L;if(t==="comma"&&X(y))A&&f&&(y=dn(y,f)),L=[{value:y.length>0?y.join(",")||null:void 0}];else if(X(p))L=p;else{let T=Object.keys(y);L=_?T.sort(_):T}let j=l?String(e).replace(/\./g,"%2E"):String(e),N=r&&X(y)&&y.length===1?j+"[]":j;if(n&&X(y)&&y.length===0)return N+"[]";for(let T=0;T<L.length;++T){let W=L[T],Pt=typeof W=="object"&&typeof W.value<"u"?W.value:y[W];if(a&&Pt===null)continue;let J=m&&l?W.replace(/\./g,"%2E"):W,ys=X(y)?typeof t=="function"?t(N,J):N:N+(m?"."+J:"["+J+"]");k.set(s,R);let gs=new WeakMap;gs.set(fn,k),yo($,go(Pt,ys,t,r,n,o,a,l,t==="comma"&&A&&X(y)?null:f,p,_,m,d,b,w,A,I,gs))}return $}function Pi(s=D){if(typeof s.allowEmptyArrays<"u"&&typeof s.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys<"u"&&typeof s.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder<"u"&&typeof s.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=s.charset||D.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=un;if(typeof s.format<"u"){if(!Rs(ln,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=ln[t],n=D.filter;(typeof s.filter=="function"||X(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in _o?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=D.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:D.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:D.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:D.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:D.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?D.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:D.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:D.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:D.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:D.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:D.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:D.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:D.strictNullHandling}}function Ao(s,e={}){let t=s,r=Pi(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):X(r.filter)&&(o=r.filter,n=o);let a=[];if(typeof t!="object"||t===null)return"";let l=_o[r.arrayFormat],f=l==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let p=new WeakMap;for(let d=0;d<n.length;++d){let b=n[d];r.skipNulls&&t[b]===null||yo(a,go(t[b],b,l,f,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,p))}let _=a.join(r.delimiter),m=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?m+="utf8=%26%2310003%3B&":m+="utf8=%E2%9C%93&"),_.length>0?m+_:""}function bo(s){return Ao(s,{arrayFormat:"brackets"})}function Po(s){let e=0;for(let n of s)e+=n.length;let t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var Io;function ee(s){let e;return(Io??(e=new globalThis.TextEncoder,Io=e.encode.bind(e)))(s)}var wo;function hn(s){let e;return(wo??(e=new globalThis.TextDecoder,wo=e.decode.bind(e)))(s)}var te,re,Ve=class{constructor(){te.set(this,void 0),re.set(this,void 0),x(this,te,new Uint8Array,"f"),x(this,re,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ee(e):e;x(this,te,Po([c(this,te,"f"),t]),"f");let r=[],n;for(;(n=Ri(c(this,te,"f"),c(this,re,"f")))!=null;){if(n.carriage&&c(this,re,"f")==null){x(this,re,n.index,"f");continue}if(c(this,re,"f")!=null&&(n.index!==c(this,re,"f")+1||n.carriage)){r.push(hn(c(this,te,"f").subarray(0,c(this,re,"f")-1))),x(this,te,c(this,te,"f").subarray(c(this,re,"f")),"f"),x(this,re,null,"f");continue}let o=c(this,re,"f")!==null?n.preceding-1:n.preceding,a=hn(c(this,te,"f").subarray(0,o));r.push(a),x(this,te,c(this,te,"f").subarray(n.index),"f"),x(this,re,null,"f")}return r}flush(){return c(this,te,"f").length?this.decode(`
5
+ `):[]}};te=new WeakMap,re=new WeakMap;Ve.NEWLINE_CHARS=new Set([`
6
+ `,"\r"]);Ve.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ri(s,e){for(let n=e??0;n<s.length;n++){if(s[n]===10)return{preceding:n,index:n+1,carriage:!1};if(s[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function xo(s){for(let r=0;r<s.length-1;r++){if(s[r]===10&&s[r+1]===10||s[r]===13&&s[r+1]===13)return r+2;if(s[r]===13&&s[r+1]===10&&r+3<s.length&&s[r+2]===13&&s[r+3]===10)return r+4}return-1}var Cs={off:0,error:200,warn:300,info:400,debug:500},mn=(s,e,t)=>{if(s){if(to(Cs,s))return s;K(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(Cs))}`)}};function Gr(){}function Ss(s,e,t){return!e||Cs[s]>Cs[t]?Gr:e[s].bind(e)}var Si={error:Gr,warn:Gr,info:Gr,debug:Gr},Ro=new WeakMap;function K(s){let e=s.logger,t=s.logLevel??"off";if(!e)return Si;let r=Ro.get(e);if(r&&r[0]===t)return r[1];let n={error:Ss("error",e,t),warn:Ss("warn",e,t),info:Ss("info",e,t),debug:Ss("debug",e,t)};return Ro.set(e,[t,n]),n}var ye=s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="x-amz-security-token"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s);var Qr,Z=class s{constructor(e,t,r){this.iterator=e,Qr.set(this,void 0),this.controller=t,x(this,Qr,r,"f")}static fromSSEResponse(e,t,r,n){let o=!1,a=r?K(r):console;async function*l(){if(o)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let f=!1;try{for await(let p of Ci(e,t))if(!f){if(p.data.startsWith("[DONE]")){f=!0;continue}if(p.event===null||!p.event.startsWith("thread.")){let _;try{_=JSON.parse(p.data)}catch(m){throw a.error("Could not parse message into JSON:",p.data),a.error("From chunk:",p.raw),m}if(_&&_.error)throw new F(void 0,_.error,void 0,e.headers);yield n?{event:p.event,data:_}:_}else{let _;try{_=JSON.parse(p.data)}catch(m){throw console.error("Could not parse message into JSON:",p.data),console.error("From chunk:",p.raw),m}if(p.event=="error")throw new F(void 0,_.error,_.message,void 0);yield{event:p.event,data:_}}}f=!0}catch(p){if(Hr(p))return;throw p}finally{f||t.abort()}}return new s(l,t,r)}static fromReadableStream(e,t,r){let n=!1;async function*o(){let l=new Ve,f=e.getReader(),p=!1,_,m=()=>{_??(_=f.cancel()),_.catch(()=>{})};t.signal.addEventListener("abort",m,{once:!0});try{if(t.signal.aborted){m();return}for(;;){let{value:d,done:b}=await f.read();if(b){p=!0;break}if(t.signal.aborted)return;for(let w of l.decode(d)){if(t.signal.aborted)return;yield w}}if(t.signal.aborted)return;for(let d of l.flush()){if(t.signal.aborted)return;yield d}}finally{t.signal.removeEventListener("abort",m),p||m(),f.releaseLock()}}async function*a(){if(n)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let l=!1;try{for await(let f of o())l||f&&(yield JSON.parse(f));l=!0}catch(f){if(t.signal.aborted||Hr(f))return;throw f}finally{l||t.abort()}}return new s(a,t,r)}[(Qr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=o=>({next:()=>{if(o.length===0){let a=r.next();e.push(a),t.push(a)}return o.shift()}});return[new s(()=>n(e),this.controller,c(this,Qr,"f")),new s(()=>n(t),this.controller,c(this,Qr,"f"))]}toReadableStream(){let e=this,t;return on({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:n,done:o}=await t.next();if(o)return r.close();let a=ee(JSON.stringify(n)+`
7
+ `);r.enqueue(a)}catch(n){r.error(n)}},async cancel(){await t.return?.()}})}};async function*Ci(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new g("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 g("Attempted to iterate over a response with no body");let t=new _n,r=new Ve,n=xs(s.body);for await(let o of ki(n))for(let a of r.decode(o)){let l=t.decode(a);l&&(yield l)}for(let o of r.flush()){let a=t.decode(o);a&&(yield a)}}async function*ki(s){let e=new Uint8Array;for await(let t of s){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?ee(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let o;for(;(o=xo(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var _n=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 o={event:this.event,data:this.data.join(`
8
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=$i(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function $i(s,e){let t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}async function ks(s,e){let{response:t,requestLogID:r,retryOfRequestLogID:n,startTime:o}=e,a=await(async()=>{if(e.options.stream)return K(s).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,s,e.options.__synthesizeEventData):Z.fromSSEResponse(t,e.controller,s,e.options.__synthesizeEventData);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let f=t.headers.get("content-type")?.split(";")[0]?.trim();if(f?.includes("application/json")||f?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;let d=await t.json();return yn(d,t)}return await t.text()})();return K(s).debug(`[${r}] response parsed`,ye({retryOfRequestLogID:n,url:t.url,status:t.status,body:a,durationMs:Date.now()-o})),a}function yn(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Yr,Xe=class s extends Promise{constructor(e,t,r=ks){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=r,Yr.set(this,void 0),x(this,Yr,e,"f")}_thenUnwrap(e){return new s(c(this,Yr,"f"),this.responsePromise,async(t,r)=>yn(e(await this.parseResponse(t,r),r),r.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.parsedPromise=this.responsePromise.then(e=>this.parseResponse(c(this,Yr,"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)}};Yr=new WeakMap;var $s,Nt=class{constructor(e,t,r,n){$s.set(this,void 0),x(this,$s,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new g("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await c(this,$s,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[($s=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Zr=class extends Xe{constructor(e,t,r){super(e,t,async(n,o)=>new r(n,o.response,await ks(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},G=class extends Nt{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},C=class extends Nt{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.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:{...ws(this.options.query),after:t}}:null}},O=class extends Nt{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.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:{...ws(this.options.query),after:e}}:null}},B=class extends Nt{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.next=r.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:{...ws(this.options.query),after:e}}:null}};var Oi={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},vi="urn:ietf:params:oauth:grant-type:token-exchange",Es=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=t??Ps()}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=await this.config.provider.getToken(),t={grant_type:vi,subject_token:e,subject_token_type:Oi[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(t.client_id=this.config.clientId);let r=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let f=await r.text(),p;try{p=JSON.parse(f)}catch{}throw r.status===400||r.status===401||r.status===403?new Je(r.status,p,r.headers):F.generate(r.status,p,`Token exchange failed with status ${r.status}`,r.headers)}let n=await r.json();if(typeof n!="object"||n===null||!("access_token"in n)||typeof n.access_token!="string"||n.access_token.trim().length===0)throw new g("Token exchange response missing 'access_token' field");let o=n.access_token,a=n.expires_in??3600,l=Date.now()+a*1e3;return this.cachedToken={token:o,expiresAt:l},o}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let r=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-r}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var So=Symbol("brand.privateNullableHeaders"),Ti=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function*ji(s){if(!s)return;if(So in s){let{values:r,nulls:n}=s;yield*r.entries();for(let o of n)yield[o,null];return}let e=!1,t;s instanceof Headers?t=s.entries():sn(s)?t=s:(e=!0,t=Object.entries(s??{}));for(let r of t){let n=r[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let o=sn(r[1])?r[1]:[r[1]],a=!1;for(let l of o)l!==void 0&&(e&&!a&&(a=!0,yield[n,null]),yield[n,l])}}var h=s=>{let e=new Headers,t=new Set;for(let r of s){let n=new Set;for(let[o,a]of ji(r)){if(!Ti.test(o))throw new TypeError(`Header name must be a valid HTTP token ["${o}"]`);let l=o.toLowerCase();n.has(l)||(e.delete(l),n.add(l)),a===null?(e.delete(l),t.add(l)):(e.append(l,a),t.delete(l))}}return{[So]:!0,values:e,nulls:t}};var ko=Symbol("brand.privateStreamingFile");function vs(s,e,t){if(!e)throw new TypeError("toStreamingFile requires a non-empty file name");return{[ko]:!0,data:s,name:e,...t?.type?{type:t.type}:{}}}var wn=()=>{if(typeof File>"u"){let{process:s}=globalThis,e=typeof s?.versions?.node=="string"&&parseInt(s.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Mt(s,e,t){return wn(),new File(s,e??"unknown_file",t)}function Lt(s){return(typeof s=="object"&&s!==null&&("name"in s&&s.name&&String(s.name)||"url"in s&&s.url&&String(s.url)||"filename"in s&&s.filename&&String(s.filename)||"path"in s&&s.path&&String(s.path))||"").split(/[\\/]/).pop()||void 0}var Kt=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",$e=async(s,e)=>An(s.body)?Os(s.body)?Eo(s):{...s,body:await $o(s.body,e)}:s,Q=async(s,e)=>Os(s.body)?Eo(s):{...s,body:await $o(s.body,e)},Co=new WeakMap;function Ni(s){let e=typeof s=="function"?s:s.fetch,t=Co.get(e);if(t)return t;let r=(async()=>{try{let n="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new n(o).text()}catch{return!0}})();return Co.set(e,r),r}var $o=async(s,e)=>{if(!await Ni(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let t=new FormData;return await Promise.all(Object.entries(s||{}).map(([r,n])=>In(t,r,n))),t},Ts=s=>s instanceof Blob&&"name"in s,Pn=s=>typeof s=="object"&&s!==null&&"getReader"in s&&typeof s.getReader=="function",es=s=>typeof s=="object"&&s!==null&&ko in s,xn=s=>typeof s=="object"&&s!==null&&(s instanceof Response||Kt(s)||Pn(s)||es(s)||Ts(s)),Os=s=>{if(es(s)||Kt(s)||Pn(s))return!0;if(Array.isArray(s))return s.some(Os);if(s&&typeof s=="object"&&!Ts(s)&&!(s instanceof Response)){for(let e in s)if(Os(s[e]))return!0}return!1},An=s=>{if(xn(s))return!0;if(Array.isArray(s))return s.some(An);if(s&&typeof s=="object"){for(let e in s)if(An(s[e]))return!0}return!1},Eo=s=>{let e=`openai-${Math.random().toString(36).slice(2)}`,t=Xr(Fi(s.body,e));return{...s,body:t,headers:h([{"content-type":`multipart/form-data; boundary=${e}`},s.headers])}};async function*Fi(s,e){for await(let{key:t,value:r}of Li(s)){if(yield ee(`--${e}\r
9
+ `),xn(r)){let n=Mi(r),o=Ki(r);yield ee(`Content-Disposition: form-data; name="${gn(t)}"; filename="${gn(n)}"\r
10
10
  Content-Type: ${o}\r
11
11
  \r
12
- `),yield*jt(Ki(r))}else yield ee(`Content-Disposition: form-data; name="${_n(t)}"\r
12
+ `),yield*Ft(Bi(r))}else yield ee(`Content-Disposition: form-data; name="${gn(t)}"\r
13
13
  \r
14
14
  ${String(r)}`);yield ee(`\r
15
15
  `)}yield ee(`--${e}--\r
16
- `)}async function*Fi(s){if(!(!s||typeof s!="object"))for(let[e,t]of Object.entries(s))yield*gn(e,t)}async function*gn(s,e){if(e!==void 0){if(e==null)throw new TypeError(`Received null for "${s}"; to pass null in FormData, you must use the string 'null'`);if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||In(e))yield{key:s,value:e};else if(Array.isArray(e))for(let t of e)yield*gn(s+"[]",t);else if(typeof e=="object")for(let[t,r]of Object.entries(e))yield*gn(`${s}[${t}]`,r);else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${e} instead`)}}function Li(s){return Yr(s)?s.name:Nt(s)??"unknown_file"}function Mi(s){return Yr(s)?s.type||"application/octet-stream":Es(s)&&s.type?s.type:s instanceof Response&&s.headers.get("content-type")||"application/octet-stream"}function Ki(s){return Yr(s)?s.data:s}async function*jt(s){if(typeof s=="string")yield ee(s);else if(ArrayBuffer.isView(s))yield new Uint8Array(s.buffer,s.byteOffset,s.byteLength);else if(s instanceof ArrayBuffer)yield new Uint8Array(s);else if(s instanceof Response)s.body?yield*jt(s.body):yield*jt(await s.blob());else if(s instanceof Blob)typeof s.stream=="function"?yield*jt(s.stream()):yield new Uint8Array(await s.arrayBuffer());else if(wn(s))for await(let e of ws(s))yield*jt(e);else if(Lt(s))for await(let e of s)yield*jt(e);else throw new TypeError(`Invalid streaming file chunk: ${String(s)}`)}function _n(s){return s.replace(/["\\\r\n]/g,e=>encodeURIComponent(e))}var An=async(s,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")s.append(e,String(t));else if(t instanceof Response)s.append(e,Ft([await t.blob()],Nt(t)));else if(Lt(t))s.append(e,Ft([await new Response(Jr(t)).blob()],Nt(t)));else if(Es(t))s.append(e,t,Nt(t));else if(Array.isArray(t))await Promise.all(t.map(r=>An(s,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,n])=>An(s,`${e}[${r}]`,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var Eo=s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function",Ui=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&Eo(s),Bi=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function Os(s,e,t){if(bn(),s=await s,Ui(s))return s instanceof File?s:Ft([await s.arrayBuffer()],s.name);if(Bi(s)){let n=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),Ft(await Pn(n),e,t)}let r=await Pn(s);if(e||(e=Nt(s)),!t?.type){let n=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(t={...t,type:n})}return Ft(r,e,t)}async function Pn(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(Eo(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(Lt(s))for await(let t of s)e.push(...await Pn(t));else{let t=s?.constructor?.name;throw new Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${Di(s)}`)}return e}function Di(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}var u=class{constructor(e){this._client=e}};function vo(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Oo=Object.freeze(Object.create(null)),qi=(s=vo)=>function(t,...r){if(t.length===1)return t[0];let n=!1,o=[],a=t.reduce((_,f,d)=>{/[?#]/.test(f)&&(n=!0);let b=r[d],I=(n?encodeURIComponent:s)(""+b);return d!==r.length&&(b==null||typeof b=="object"&&b.toString===Object.getPrototypeOf(Object.getPrototypeOf(b.hasOwnProperty??Oo)??Oo)?.toString)&&(I=b+"",o.push({start:_.length+f.length,length:I.length,error:`Value of type ${Object.prototype.toString.call(b).slice(8,-1)} is not a valid path parameter`})),_+f+(d===r.length?"":I)},""),l=a.split(/[?#]/,1)[0],m=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,p;for(;(p=m.exec(l))!==null;)o.push({start:p.index,length:p[0].length,error:`Value "${p[0]}" can't be safely passed as a path parameter`});if(o.sort((_,f)=>_.start-f.start),o.length>0){let _=0,f=o.reduce((d,b)=>{let I=" ".repeat(b.start-_),A="^".repeat(b.length);return _=b.start+b.length,d+I+A},"");throw new g(`Path parameters result in path with invalid segments:
16
+ `)}async function*Li(s){if(!(!s||typeof s!="object"))for(let[e,t]of Object.entries(s))yield*bn(e,t)}async function*bn(s,e){if(e!==void 0){if(e==null)throw new TypeError(`Received null for "${s}"; to pass null in FormData, you must use the string 'null'`);if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||xn(e))yield{key:s,value:e};else if(Array.isArray(e))for(let t of e)yield*bn(s+"[]",t);else if(typeof e=="object")for(let[t,r]of Object.entries(e))yield*bn(`${s}[${t}]`,r);else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${e} instead`)}}function Mi(s){return es(s)?s.name:Lt(s)??"unknown_file"}function Ki(s){return es(s)?s.type||"application/octet-stream":Ts(s)&&s.type?s.type:s instanceof Response&&s.headers.get("content-type")||"application/octet-stream"}function Bi(s){return es(s)?s.data:s}async function*Ft(s){if(typeof s=="string")yield ee(s);else if(ArrayBuffer.isView(s))yield new Uint8Array(s.buffer,s.byteOffset,s.byteLength);else if(s instanceof ArrayBuffer)yield new Uint8Array(s);else if(s instanceof Response)s.body?yield*Ft(s.body):yield*Ft(await s.blob());else if(s instanceof Blob)typeof s.stream=="function"?yield*Ft(s.stream()):yield new Uint8Array(await s.arrayBuffer());else if(Pn(s))for await(let e of xs(s))yield*Ft(e);else if(Kt(s))for await(let e of s)yield*Ft(e);else throw new TypeError(`Invalid streaming file chunk: ${String(s)}`)}function gn(s){return s.replace(/["\\\r\n]/g,e=>encodeURIComponent(e))}var In=async(s,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")s.append(e,String(t));else if(t instanceof Response)s.append(e,Mt([await t.blob()],Lt(t)));else if(Kt(t))s.append(e,Mt([await new Response(Xr(t)).blob()],Lt(t)));else if(Ts(t))s.append(e,t,Lt(t));else if(Array.isArray(t))await Promise.all(t.map(r=>In(s,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,n])=>In(s,`${e}[${r}]`,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var Oo=s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function",Ui=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&Oo(s),Di=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function js(s,e,t){if(wn(),s=await s,Ui(s))return s instanceof File?s:Mt([await s.arrayBuffer()],s.name);if(Di(s)){let n=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),Mt(await Rn(n),e,t)}let r=await Rn(s);if(e||(e=Lt(s)),!t?.type){let n=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(t={...t,type:n})}return Mt(r,e,t)}async function Rn(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(Oo(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(Kt(s))for await(let t of s)e.push(...await Rn(t));else{let t=s?.constructor?.name;throw new Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${zi(s)}`)}return e}function zi(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}var u=class{constructor(e){this._client=e}};function To(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var vo=Object.freeze(Object.create(null)),Hi=(s=To)=>function(t,...r){if(t.length===1)return t[0];let n=!1,o=[],a=t.reduce((_,m,d)=>{/[?#]/.test(m)&&(n=!0);let b=r[d],w=(n?encodeURIComponent:s)(""+b);return d!==r.length&&(b==null||typeof b=="object"&&b.toString===Object.getPrototypeOf(Object.getPrototypeOf(b.hasOwnProperty??vo)??vo)?.toString)&&(w=b+"",o.push({start:_.length+m.length,length:w.length,error:`Value of type ${Object.prototype.toString.call(b).slice(8,-1)} is not a valid path parameter`})),_+m+(d===r.length?"":w)},""),l=a.split(/[?#]/,1)[0],f=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,p;for(;(p=f.exec(l))!==null;)o.push({start:p.index,length:p[0].length,error:`Value "${p[0]}" can't be safely passed as a path parameter`});if(o.sort((_,m)=>_.start-m.start),o.length>0){let _=0,m=o.reduce((d,b)=>{let w=" ".repeat(b.start-_),A="^".repeat(b.length);return _=b.start+b.length,d+w+A},"");throw new g(`Path parameters result in path with invalid segments:
17
17
  ${o.map(d=>d.error).join(`
18
18
  `)}
19
19
  ${a}
20
- ${f}`)}return a},i=qi(vo);var Xe=class extends u{list(e,t={},r){return this._client.getAPIList(i`/chat/completions/${e}/messages`,C,{query:t,...r,__security:{bearerAuth:!0}})}};function Zr(s){return s!==void 0&&"function"in s&&s.function!==void 0}function es(s){return s?.$brand==="auto-parseable-response-format"}function Ge(s){return s?.$brand==="auto-parseable-tool"}function jo(s,e){return!e||!xn(e)?{...s,choices:s.choices.map(t=>(Fo(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:ts(s,e)}function ts(s,e){let t=s.choices.map(r=>{if(r.finish_reason==="length")throw new Ot;if(r.finish_reason==="content_filter")throw new vt;return Fo(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(n=>Ji(e,n))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Wi(e,r.message.content):null}}});return{...s,choices:t}}function Wi(s,e){return s.response_format?.type!=="json_schema"?null:s.response_format?.type==="json_schema"?"$parseRaw"in s.response_format?s.response_format.$parseRaw(e):JSON.parse(e):null}function Ji(s,e){let t=s.tools?.find(r=>Zr(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ge(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function No(s,e){if(!s||!("tools"in s)||!s.tools)return!1;let t=s.tools?.find(r=>Zr(r)&&r.function?.name===e.function.name);return Zr(t)&&(Ge(t)||t?.function.strict||!1)}function xn(s){return es(s.response_format)?!0:s.tools?.some(e=>Ge(e)||e.type==="function"&&e.function.strict===!0)??!1}function Fo(s){for(let e of s||[])if(e.type!=="function")throw new g(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Lo(s){for(let e of s??[]){if(e.type!=="function")throw new g(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new g(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var ge=s=>s?.role==="assistant",rs=s=>s?.role==="tool";var ss,vs,Ts,ns,os,js,is,Ae,Ns,as,Fs,Ls,Mt,Mo,Rn,Ee=class{constructor(){ss.add(this),this.controller=new AbortController,vs.set(this,void 0),Ts.set(this,()=>{}),ns.set(this,()=>{}),os.set(this,void 0),js.set(this,()=>{}),is.set(this,()=>{}),Ae.set(this,{}),Ns.set(this,[]),as.set(this,!1),Fs.set(this,!1),Ls.set(this,!1),Mt.set(this,!1),x(this,vs,new Promise((e,t)=>{x(this,Ts,e,"f"),x(this,ns,t,"f")}),"f"),x(this,os,new Promise((e,t)=>{x(this,js,e,"f"),x(this,is,t,"f")}),"f"),c(this,vs,"f").catch(()=>{}),c(this,os,"f").catch(()=>{})}_run(e){setTimeout(()=>{Promise.resolve().then(e).then(()=>{try{this._emitFinal()}catch(t){c(this,ss,"m",Rn).call(this,t);return}this._emit("end")},c(this,ss,"m",Rn).bind(this))},0)}_connected(){this.ended||(c(this,Ts,"f").call(this),this._emit("connect"))}get ended(){return c(this,as,"f")}get errored(){return c(this,Fs,"f")}get aborted(){return c(this,Ls,"f")}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let t=()=>this.controller.abort();e.addEventListener("abort",t,{once:!0}),c(this,Ns,"f").push({signal:e,listener:t})}on(e,t){return(c(this,Ae,"f")[e]||(c(this,Ae,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=c(this,Ae,"f")[e];if(!r)return this;let n=r.findIndex(o=>o.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(c(this,Ae,"f")[e]||(c(this,Ae,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{x(this,Mt,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}events(e){let t=[],r=[],n=this.ended,o,a=!1,l=()=>({value:void 0,done:!0}),m=()=>{for(;r.length;)r.shift().resolve(l())},p=()=>{!o||a||!r.length||(a=!0,r.shift().reject(o))},_=()=>{this.off(e,f),this.off("end",b),e!=="error"&&this.off("error",d),e!=="abort"&&this.off("abort",d)},f=(...I)=>{if(n)return;let A=r.shift();A?A.resolve({value:I,done:!1}):t.push(I)},d=I=>{o=I,t.length||p()},b=()=>{n=!0,_(),t.length||(p(),m())};return n||(this.on(e,f),this.on("end",b),e!=="error"&&this.on("error",d),e!=="abort"&&this.on("abort",d)),{next:()=>{let I=t.shift();return I?Promise.resolve({value:I,done:!1}):o&&!a?(a=!0,Promise.reject(o)):n?Promise.resolve(l()):new Promise((A,w)=>{r.push({resolve:A,reject:w})})},return:()=>(n=!0,t.length=0,_(),m(),Promise.resolve(l())),[Symbol.asyncIterator](){return this}}}async done(){x(this,Mt,!0,"f"),await c(this,os,"f")}_emit(e,...t){if(c(this,as,"f"))return;e==="end"&&(c(this,ss,"m",Mo).call(this),x(this,as,!0,"f"),c(this,js,"f").call(this));let r=c(this,Ae,"f")[e];if(r&&(c(this,Ae,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!c(this,Mt,"f")&&!r?.length&&Promise.reject(n),c(this,ns,"f").call(this,n),c(this,is,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!c(this,Mt,"f")&&!r?.length&&Promise.reject(n),c(this,ns,"f").call(this,n),c(this,is,"f").call(this,n),this._emit("end")}}_emitFinal(){}};vs=new WeakMap,Ts=new WeakMap,ns=new WeakMap,os=new WeakMap,js=new WeakMap,is=new WeakMap,Ae=new WeakMap,Ns=new WeakMap,as=new WeakMap,Fs=new WeakMap,Ls=new WeakMap,Mt=new WeakMap,ss=new WeakSet,Mo=function(){for(let{signal:e,listener:t}of c(this,Ns,"f").splice(0))e.removeEventListener("abort",t)},Rn=function(e){if(x(this,Fs,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new M),e instanceof M)return x(this,Ls,!0,"f"),this._emit("abort",e);if(e instanceof g)return this._emit("error",e);if(e instanceof Error){let t=new g(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new g(String(e)))};function Ko(s){return typeof s.parse=="function"}var Y,Sn,Ms,Cn,kn,$n,Uo,Bo,Vi=10;function Xi(s){for(let e of s.choices)for(let t of e.message.tool_calls??[])t.id||(t.id=`call_${He()}`)}function Gi(s){if(!ge(s))return s;let e={role:"assistant"};return s.audio!=null&&(e.audio={id:s.audio.id}),s.content!==void 0&&(e.content=s.content),s.function_call!=null&&(e.function_call=s.function_call),s.name!==void 0&&(e.name=s.name),s.refusal!=null&&(e.refusal=s.refusal),s.tool_calls!==void 0&&(e.tool_calls=s.tool_calls.map(t=>t.type==="custom"?{id:t.id,type:t.type,custom:{input:t.custom.input,name:t.custom.name}}:{id:t.id,type:t.type,function:{arguments:t.function.arguments,name:t.function.name}})),e}var Kt=class extends Ee{constructor(){super(...arguments),Y.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){Xi(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),rs(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(ge(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new g("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),c(this,Y,"m",Sn).call(this)}async finalMessage(){return await this.done(),c(this,Y,"m",Ms).call(this)}async finalFunctionToolCall(){return await this.done(),c(this,Y,"m",Cn).call(this)}async finalFunctionToolCallResult(){return await this.done(),c(this,Y,"m",kn).call(this)}async totalUsage(){return await this.done(),c(this,Y,"m",$n).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=c(this,Y,"m",Ms).call(this);t&&this._emit("finalMessage",t);let r=c(this,Y,"m",Sn).call(this);r&&this._emit("finalContent",r);let n=c(this,Y,"m",Cn).call(this);n&&this._emit("finalFunctionToolCall",n);let o=c(this,Y,"m",kn).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",c(this,Y,"m",$n).call(this))}async _createChatCompletion(e,t,r){this._listenForAbort(r?.signal),c(this,Y,"m",Uo).call(this,t);let n=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(ts(n,t))}async _runChatCompletion(e,t,r){for(let n of t.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r,n){let o="tool",{tool_choice:a="auto",stream:l,toolContext:m,...p}=t,_=m,f=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:d=Vi,afterCompletion:b}=n||{},I=t.tools.map(y=>{if(Ge(y)){if(!y.$callback)throw new g("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:y.$callback,name:y.function.name,description:y.function.description||"",parameters:y.function.parameters,parse:y.$parseRaw,strict:!0}}}return y}),A={};for(let y of I)y.type==="function"&&(A[y.function.name||y.function.function.name]=y.function);let w="tools"in t?I.map(y=>y.type==="function"?{type:"function",function:{name:y.function.name||y.function.function.name,parameters:y.function.parameters,description:y.function.description,strict:y.function.strict}}:y):void 0;for(let y of t.messages)this._addMessage(y,!1);let k=async y=>{if(y.type!=="function")return{message:void 0,functionCalled:!1};let P=y.id,{name:R,arguments:v}=y.function,$=A[R];if(!$){let N=`Invalid tool_call: ${JSON.stringify(R)}. Available options are: ${Object.keys(A).map(T=>JSON.stringify(T)).join(", ")}. Please try again`;return{message:{role:o,tool_call_id:P,content:N},functionCalled:!1}}if(f&&f!==R){let N=`Invalid tool_call: ${JSON.stringify(R)}. ${JSON.stringify(f)} requested. Please try again`;return{message:{role:o,tool_call_id:P,content:N},functionCalled:!1}}let L;if(Ko($)){let N;try{N=await $.parse(v)}catch(T){let W=T instanceof Error?T.message:String(T);return{message:{role:o,tool_call_id:P,content:W},functionCalled:!1}}L=await $.function(N,r,_)}else L=await $.function(v,r,_);let j=c(this,Y,"m",Bo).call(this,L);return{message:{role:o,tool_call_id:P,content:j},functionCalled:!0}};for(let y=0;y<d;++y){let P=await this._createChatCompletion(e,{...p,tool_choice:a,tools:w,messages:this.messages.map(Gi)},n),R=P.choices[0]?.message;if(!R)throw new g("missing message in ChatCompletion response");if(!R.tool_calls?.length){await b?.(P,r);return}if(f||t.parallel_tool_calls===!1)for(let v of R.tool_calls){let $=await k(v);if($.message&&this._addMessage($.message),f&&$.functionCalled){await b?.(P,r);return}}else{let v=await Promise.allSettled(R.tool_calls.map(k));for(let $ of v)if($.status==="rejected")throw $.reason;for(let $ of v)$.status==="fulfilled"&&$.value.message&&this._addMessage($.value.message)}await b?.(P,r)}}};Y=new WeakSet,Sn=function(){return c(this,Y,"m",Ms).call(this).content??null},Ms=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(ge(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new g("stream ended without producing a ChatCompletionMessage with role=assistant")},Cn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(ge(t)&&t?.tool_calls?.length)for(let r=t.tool_calls.length-1;r>=0;r--){let n=t.tool_calls[r];if(n?.type==="function")return n.function}}},kn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(rs(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(n=>n.type==="function"&&n.id===t.tool_call_id)))return t.content}},$n=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},Uo=function(e){if(e.n!=null&&e.n>1)throw new g("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Bo=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var us=class s extends Kt{static runTools(e,t,r){let n=new s,o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,n,o)),n}_addMessage(e,t=!0){super._addMessage(e,t),ge(e)&&e.content&&this._emit("content",e.content)}};var z={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},En=class extends Error{},On=class extends Error{};function Qi(s,e=z.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return Yi(s.trim(),e)}var Yi=(s,e)=>{let t=s.length,r=0,n=d=>{throw new En(`${d} at position ${r}`)},o=d=>{throw new On(`${d} at position ${r}`)},a=()=>(f(),r>=t&&n("Unexpected end of input"),s[r]==='"'?l():s[r]==="{"?m():s[r]==="["?p():s.substring(r,r+4)==="null"||z.NULL&e&&t-r<4&&"null".startsWith(s.substring(r))?(r+=4,null):s.substring(r,r+4)==="true"||z.BOOL&e&&t-r<4&&"true".startsWith(s.substring(r))?(r+=4,!0):s.substring(r,r+5)==="false"||z.BOOL&e&&t-r<5&&"false".startsWith(s.substring(r))?(r+=5,!1):s.substring(r,r+8)==="Infinity"||z.INFINITY&e&&t-r<8&&"Infinity".startsWith(s.substring(r))?(r+=8,1/0):s.substring(r,r+9)==="-Infinity"||z.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(s.substring(r))?(r+=9,-1/0):s.substring(r,r+3)==="NaN"||z.NAN&e&&t-r<3&&"NaN".startsWith(s.substring(r))?(r+=3,NaN):_()),l=()=>{let d=r,b=!1;for(r++;r<t&&(s[r]!=='"'||b&&s[r-1]==="\\");)b=s[r]==="\\"?!b:!1,r++;if(s.charAt(r)=='"')try{return JSON.parse(s.substring(d,++r-Number(b)))}catch(I){o(String(I))}else if(z.STR&e)try{return JSON.parse(s.substring(d,r-Number(b))+'"')}catch{return JSON.parse(s.substring(d,s.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},m=()=>{r++,f();let d={};try{for(;s[r]!=="}";){if(f(),r>=t&&z.OBJ&e)return d;let b=l();f(),r++;try{let I=a();Object.defineProperty(d,b,{value:I,writable:!0,enumerable:!0,configurable:!0})}catch(I){if(z.OBJ&e)return d;throw I}f(),s[r]===","&&r++}}catch{if(z.OBJ&e)return d;n("Expected '}' at end of object")}return r++,d},p=()=>{r++;let d=[];try{for(;s[r]!=="]";)d.push(a()),f(),s[r]===","&&r++}catch{if(z.ARR&e)return d;n("Expected ']' at end of array")}return r++,d},_=()=>{if(r===0){s==="-"&&z.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s)}catch(b){if(z.NUM&e)try{return s[s.length-1]==="."?JSON.parse(s.substring(0,s.lastIndexOf("."))):JSON.parse(s.substring(0,s.lastIndexOf("e")))}catch{}o(String(b))}}let d=r;for(s[r]==="-"&&r++;s[r]&&!",]}".includes(s[r]);)r++;r==t&&!(z.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(s.substring(d,r))}catch{s.substring(d,r)==="-"&&z.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s.substring(d,s.lastIndexOf("e")))}catch(I){o(String(I))}}},f=()=>{for(;r<t&&`
21
- \r `.includes(s[r]);)r++};return a()},vn=s=>Qi(s,z.ALL^z.NUM);var B,be,Oe,Ut,ae,Tn,Ks,jn,Nn,Fn,cs,Ln,Do,Kn="chat.completion.chunk.message:";function zo(s,e,t){let r={type:"message",message:e,...t?{tool_call_ids:t}:{}};return{id:s.id,choices:[],created:s.created,model:s.model,object:`${Kn}${JSON.stringify(r)}`}}function Zi(s){return"type"in s&&s.type==="message"&&"message"in s||"object"in s&&typeof s.object=="string"&&s.object.startsWith(Kn)}function ea(s){return"type"in s?s:JSON.parse(s.object.slice(Kn.length))}var Qe=class s extends Kt{constructor(e){super(),B.add(this),be.set(this,void 0),Oe.set(this,void 0),Ut.set(this,void 0),ae.set(this,void 0),x(this,be,e,"f"),x(this,Oe,new Set,"f"),x(this,Ut,[],"f")}get currentChatCompletionSnapshot(){return c(this,ae,"f")}static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let n=new s(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,r){super._createChatCompletion,this._listenForAbort(r?.signal),c(this,B,"m",Tn).call(this);let n=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let o of n)c(this,B,"m",jn).call(this,o);if(n.controller.signal?.aborted)throw new M;return this._addChatCompletion(c(this,B,"m",cs).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),c(this,B,"m",Tn).call(this),this._connected();let r=Z.fromReadableStream(e,this.controller),n;for await(let a of r){if(Zi(a)){let m=ea(a);if(c(this,ae,"f")){let p=c(this,ae,"f").choices[0]?.message.tool_calls;for(let[_,f]of m.tool_call_ids?.entries()??[]){let d=p?.[_];d&&f&&(d.id=f)}this._addChatCompletion(c(this,B,"m",cs).call(this)),n=void 0}this._addMessage(m.message);continue}let l=a;n&&l.id&&n!==l.id&&this._addChatCompletion(c(this,B,"m",cs).call(this)),c(this,B,"m",jn).call(this,l),l.id&&(n=l.id)}if(r.controller.signal?.aborted)throw new M;if(c(this,ae,"f"))return this._addChatCompletion(c(this,B,"m",cs).call(this));let o=this._chatCompletions[this._chatCompletions.length-1];if(o)return o;throw new g("request ended without sending any chunks")}[(be=new WeakMap,Oe=new WeakMap,Ut=new WeakMap,ae=new WeakMap,B=new WeakSet,Tn=function(){this.ended||(x(this,Oe,new Set,"f"),x(this,ae,void 0,"f"))},Ks=function(t){let r=c(this,Ut,"f")[t.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},c(this,Ut,"f")[t.index]=r,r)},jn=function(t){if(this.ended)return;let r=c(this,B,"m",Do).call(this,t);this._emit("chunk",t,r);for(let n of t.choices){let o=r.choices[n.index],{delta:a}=n;a?.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",a.content,o.message.content),this._emit("content.delta",{delta:a.content,snapshot:o.message.content,parsed:o.message.parsed})),a?.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:a.refusal,snapshot:o.message.refusal}),n.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:o.logprobs?.content??[]}),n.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let l=c(this,B,"m",Ks).call(this,o);o.finish_reason&&(c(this,B,"m",Fn).call(this,o),l.current_tool_call_index!=null&&c(this,B,"m",Nn).call(this,o,l.current_tool_call_index));for(let m of a?.tool_calls??[])l.current_tool_call_index!==m.index&&(c(this,B,"m",Fn).call(this,o),l.current_tool_call_index!=null&&c(this,B,"m",Nn).call(this,o,l.current_tool_call_index)),l.current_tool_call_index=m.index;for(let m of a?.tool_calls??[]){let p=o.message.tool_calls?.[m.index];p?.type&&(p?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:p.function?.name,index:m.index,arguments:p.function.arguments,parsed_arguments:p.function.parsed_arguments,arguments_delta:m.function?.arguments??""}):(p?.type,void 0))}}},Nn=function(t,r){if(c(this,B,"m",Ks).call(this,t).done_tool_calls.has(r))return;let o=t.message.tool_calls?.[r];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let a=c(this,be,"f")?.tools?.find(l=>Zr(l)&&l.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:r,arguments:o.function.arguments,parsed_arguments:Ge(a)?a.$parseRaw(o.function.arguments):a?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},Fn=function(t){let r=c(this,B,"m",Ks).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let n=c(this,B,"m",Ln).call(this);this._emit("content.done",{content:t.message.content,parsed:n?n.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},cs=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");let t=c(this,ae,"f");if(!t)throw new g("request ended without sending any chunks");let r=c(this,Oe,"f");return x(this,Oe,new Set,"f"),x(this,ae,void 0,"f"),x(this,Ut,[],"f"),ta(t,c(this,be,"f"),r)},Ln=function(){let t=c(this,be,"f")?.response_format;return es(t)?t:null},Do=function(t){var r,n,o,a,l;let m=c(this,ae,"f"),{choices:p,..._}=t;m?t.id&&Object.assign(m,_):m=x(this,ae,{..._,choices:[]},"f");for(let{delta:f,finish_reason:d,index:b,logprobs:I=null,...A}of t.choices){let w=m.choices[b];if(w||(w=m.choices[b]={finish_reason:d,index:b,message:{},logprobs:I,...A}),I)if(!w.logprobs)w.logprobs=Object.assign({},I);else{let{content:j,refusal:N,...T}=I;Object.assign(w.logprobs,T),j&&((r=w.logprobs).content??(r.content=[]),w.logprobs.content.push(...j)),N&&((n=w.logprobs).refusal??(n.refusal=[]),w.logprobs.refusal.push(...N))}if(d&&(w.finish_reason=d,c(this,be,"f")&&xn(c(this,be,"f")))){if(d==="length")throw new Ot;if(d==="content_filter")throw new vt}if(Object.assign(w,A),!f)continue;c(this,Oe,"f").delete(b);let{audio:k,content:y,refusal:P,function_call:R,role:v,tool_calls:$,...L}=f;if(Object.assign(w.message,L),k?.expires_at!=null&&k.id==null&&k.data==null&&k.transcript==null&&y==null&&P==null&&R==null&&v==null&&$==null&&Object.keys(L).length===0&&c(this,Oe,"f").add(b),P&&(w.message.refusal=(w.message.refusal||"")+P),v&&(w.message.role=v),k){let j=(o=w.message).audio??(o.audio={});k.id!=null&&(j.id=k.id),k.data!=null&&(j.data=(j.data??"")+k.data),k.transcript!=null&&(j.transcript=(j.transcript??"")+k.transcript),k.expires_at!=null&&(j.expires_at=k.expires_at)}if(R&&(w.message.function_call?(R.name&&(w.message.function_call.name=R.name),R.arguments&&((a=w.message.function_call).arguments??(a.arguments=""),w.message.function_call.arguments+=R.arguments)):w.message.function_call=R),y&&(w.message.content=(w.message.content||"")+y,!w.message.refusal&&c(this,B,"m",Ln).call(this)&&(w.message.parsed=w.message.content.trim()?vn(w.message.content):null)),$){w.message.tool_calls||(w.message.tool_calls=[]);for(let{index:j,id:N,type:T,function:W,...It}of $){let J=(l=w.message.tool_calls)[j]??(l[j]={});Object.assign(J,It),N&&(J.id=N),T&&(J.type=T),W&&(J.function??(J.function={name:W.name??"",arguments:""})),W?.name&&(J.function.name=W.name),W?.arguments&&(J.function.arguments+=W.arguments,No(c(this,be,"f"),J)&&(J.function.parsed_arguments=vn(J.function.arguments)))}}}return m},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Z(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function ta(s,e,t){let{id:r,choices:n,created:o,model:a,system_fingerprint:l,...m}=s,p={...m,id:r,choices:n.map(({message:_,finish_reason:f,index:d,logprobs:b,...I})=>{let{content:A=null,function_call:w,tool_calls:k,audio:y,...P}=_,R=f??(t.has(d)&&ra(y)?"stop":null);if(!R)throw new g(`missing finish_reason for choice ${d}`);let v=y?{audio:y}:{},$=_.role;if(!$)throw new g(`missing role for choice ${d}`);if(w){let{arguments:L,name:j}=w;if(L==null)throw new g(`missing function_call.arguments for choice ${d}`);if(!j)throw new g(`missing function_call.name for choice ${d}`);return{...I,message:{...v,content:A,function_call:{arguments:L,name:j},role:$,refusal:_.refusal??null},finish_reason:R,index:d,logprobs:b}}return k?{...I,index:d,finish_reason:R,logprobs:b,message:{...P,...v,role:$,content:A,refusal:_.refusal??null,tool_calls:k.map((L,j)=>{let{function:N,type:T,id:W,...It}=L,{arguments:J,name:fs,..._s}=N||{};if(T==null)throw new g(`missing choices[${d}].tool_calls[${j}].type
22
- ${Mn(s)}`);if(fs==null)throw new g(`missing choices[${d}].tool_calls[${j}].function.name
23
- ${Mn(s)}`);if(J==null)throw new g(`missing choices[${d}].tool_calls[${j}].function.arguments
24
- ${Mn(s)}`);return{...It,id:W||`call_${He()}`,type:T,function:{..._s,name:fs,arguments:J}}})}}:{...I,message:{...P,...v,content:A,role:$,refusal:_.refusal??null},finish_reason:R,index:d,logprobs:b}}),created:o,model:a,object:"chat.completion",...l?{system_fingerprint:l}:{}};return jo(p,e)}function ra(s){return s?.id!=null&&s.data!=null&&s.transcript!=null&&s.expires_at!=null}function Mn(s){return JSON.stringify(s)}var ls=class s extends Qe{static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}toReadableStream(){let e=[],t=[],r=!1,n,o,a=p=>{let _=t.shift();_?_.resolve(p):e.push(p)};this.on("chunk",p=>{n=p,a(p)}),this.on("message",p=>{if(ge(p)){o=p.tool_calls?.map(_=>_.id);return}if(rs(p)){if(!n)throw new g("cannot serialize a tool message before receiving any chunks");a(zo(n,p,o))}}),this.on("end",()=>{r=!0;for(let p of t)p.resolve(void 0);t.length=0}),this.on("abort",p=>{r=!0;for(let _ of t)_.reject(p);t.length=0}),this.on("error",p=>{r=!0;for(let _ of t)_.reject(p);t.length=0});let l=()=>({next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise((_,f)=>t.push({resolve:_,reject:f})).then(_=>_?{value:_,done:!1}:{value:void 0,done:!0});let p=e.shift();return p?{value:p,done:!1}:{value:void 0,done:!0}},return:async()=>(this.abort(),{value:void 0,done:!0})});return new Z(l,this.controller).toReadableStream()}static runTools(e,t,r){let n=new s(t),o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,n,o)),n}};var we=class extends u{constructor(){super(...arguments),this.messages=new Xe(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(i`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/chat/completions/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chat/completions",C,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return Lo(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>ts(r,e))}runTools(e,t){return e.stream?ls.runTools(this._client,e,t):us.runTools(this._client,e,t)}stream(e,t){return Qe.createChatCompletion(this._client,e,t)}};we.Messages=Xe;var ve=class extends u{constructor(){super(...arguments),this.completions=new we(this._client)}};ve.Completions=we;var Bt=class extends u{create(e,t){return this._client.post("/organization/admin_api_keys",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/admin_api_keys",C,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Dt=class extends u{list(e={},t){return this._client.getAPIList("/organization/audit_logs",O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}};var zt=class extends u{create(e,t){return this._client.post("/organization/certificates",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},r){return this._client.get(i`/organization/certificates/${e}`,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/certificates/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/certificates",O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList("/organization/certificates/activate",G,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList("/organization/certificates/deactivate",G,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}};var qt=class extends u{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}})}};var Ht=class extends u{create(e,t){return this._client.post("/organization/invites",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/invites",O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Wt=class extends u{create(e,t){return this._client.post("/organization/roles",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/roles/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/roles",U,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Jt=class extends u{create(e,t){return this._client.post("/organization/spend_alerts",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/spend_alerts/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/spend_alerts",O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Vt=class extends u{retrieve(e){return this._client.get("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post("/organization/spend_limit",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e){return this._client.delete("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}};var Xt=class extends u{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}})}};var Gt=class extends u{create(e,t,r){return this._client.post(i`/organization/groups/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{group_id:n}=t;return this._client.get(i`/organization/groups/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/groups/${e}/roles`,U,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{group_id:n}=t;return this._client.delete(i`/organization/groups/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Qt=class extends u{create(e,t,r){return this._client.post(i`/organization/groups/${e}/users`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{group_id:n}=t;return this._client.get(i`/organization/groups/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/groups/${e}/users`,U,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{group_id:n}=t;return this._client.delete(i`/organization/groups/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Te=class extends u{constructor(){super(...arguments),this.users=new Qt(this._client),this.roles=new Gt(this._client)}create(e,t){return this._client.post("/organization/groups",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/groups/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/groups",U,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};Te.Users=Qt;Te.Roles=Gt;var Yt=class extends u{retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/api_keys`,O,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Zt=class extends u{list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/certificates`,O,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}activate(e,t,r){return this._client.getAPIList(i`/organization/projects/${e}/certificates/activate`,G,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,r){return this._client.getAPIList(i`/organization/projects/${e}/certificates/deactivate`,G,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var er=class extends u{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/data_retention`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}};var tr=class extends u{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}};var rr=class extends u{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/model_permissions`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}};var sr=class extends u{listRateLimits(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/rate_limits`,O,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/rate_limits/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}};var nr=class extends u{create(e,t,r){return this._client.post(i`/projects/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/projects/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/roles/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/projects/${e}/roles`,U,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/projects/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var or=class extends u{create(e,t,r){return this._client.post(i`/organization/projects/${e}/spend_alerts`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/spend_alerts/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/spend_alerts`,O,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var ir=class extends u{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/spend_limit`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}};var ar=class extends u{create(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/groups/${e}/roles`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n,group_id:o}=t;return this._client.get(i`/projects/${n}/groups/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t,r){let{project_id:n,...o}=t;return this._client.getAPIList(i`/projects/${n}/groups/${e}/roles`,U,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n,group_id:o}=t;return this._client.delete(i`/projects/${n}/groups/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Ye=class extends u{constructor(){super(...arguments),this.roles=new ar(this._client)}create(e,t,r){return this._client.post(i`/organization/projects/${e}/groups`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n,...o}=t;return this._client.get(i`/organization/projects/${n}/groups/${e}`,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/groups`,U,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Ye.Roles=ar;var ur=class extends u{create(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/service_accounts/${e}/api_keys`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}};var Ze=class extends u{constructor(){super(...arguments),this.apiKeys=new ur(this._client)}create(e,t,r){return this._client.post(i`/organization/projects/${e}/service_accounts`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/service_accounts/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/service_accounts`,O,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Ze.APIKeys=ur;var cr=class extends u{create(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/users/${e}/roles`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n,user_id:o}=t;return this._client.get(i`/projects/${n}/users/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t,r){let{project_id:n,...o}=t;return this._client.getAPIList(i`/projects/${n}/users/${e}/roles`,U,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n,user_id:o}=t;return this._client.delete(i`/projects/${n}/users/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var et=class extends u{constructor(){super(...arguments),this.roles=new cr(this._client)}create(e,t,r){return this._client.post(i`/organization/projects/${e}/users`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/users/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/users`,O,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};et.Roles=cr;var q=class extends u{constructor(){super(...arguments),this.users=new et(this._client),this.serviceAccounts=new Ze(this._client),this.apiKeys=new Yt(this._client),this.rateLimits=new sr(this._client),this.modelPermissions=new rr(this._client),this.hostedToolPermissions=new tr(this._client),this.groups=new Ye(this._client),this.roles=new nr(this._client),this.dataRetention=new er(this._client),this.spendLimit=new ir(this._client),this.spendAlerts=new or(this._client),this.certificates=new Zt(this._client)}create(e,t){return this._client.post("/organization/projects",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/projects",O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(i`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};q.Users=et;q.ServiceAccounts=Ze;q.APIKeys=Yt;q.RateLimits=sr;q.ModelPermissions=rr;q.HostedToolPermissions=tr;q.Groups=Ye;q.Roles=nr;q.DataRetention=er;q.SpendLimit=ir;q.SpendAlerts=or;q.Certificates=Zt;var lr=class extends u{create(e,t,r){return this._client.post(i`/organization/users/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{user_id:n}=t;return this._client.get(i`/organization/users/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/users/${e}/roles`,U,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{user_id:n}=t;return this._client.delete(i`/organization/users/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var tt=class extends u{constructor(){super(...arguments),this.roles=new lr(this._client)}retrieve(e,t){return this._client.get(i`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/users/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/users",O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};tt.Roles=lr;var H=class extends u{constructor(){super(...arguments),this.auditLogs=new Dt(this._client),this.adminAPIKeys=new Bt(this._client),this.usage=new Xt(this._client),this.invites=new Ht(this._client),this.users=new tt(this._client),this.groups=new Te(this._client),this.roles=new Wt(this._client),this.dataRetention=new qt(this._client),this.spendLimit=new Vt(this._client),this.spendAlerts=new Jt(this._client),this.certificates=new zt(this._client),this.projects=new q(this._client)}};H.AuditLogs=Dt;H.AdminAPIKeys=Bt;H.Usage=Xt;H.Invites=Ht;H.Users=tt;H.Groups=Te;H.Roles=Wt;H.DataRetention=qt;H.SpendLimit=Vt;H.SpendAlerts=Jt;H.Certificates=zt;H.Projects=q;var je=class extends u{constructor(){super(...arguments),this.organization=new H(this._client)}};je.Organization=H;var pr=class extends u{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:h([{Accept:"application/octet-stream"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var dr=class extends u{create(e,t){return this._client.post("/audio/transcriptions",Q({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var mr=class extends u{create(e,t){return this._client.post("/audio/translations",Q({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var he=class extends u{constructor(){super(...arguments),this.transcriptions=new dr(this._client),this.translations=new mr(this._client),this.speech=new pr(this._client)}};he.Transcriptions=dr;he.Translations=mr;he.Speech=pr;var rt=class extends u{create(e,t){return this._client.post("/batches",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/batches",C,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}};var hr=class extends u{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/assistants/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/assistants",C,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var fr=class extends u{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var _r=class extends u{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var Ne=class extends u{constructor(){super(...arguments),this.sessions=new fr(this._client),this.transcriptionSessions=new _r(this._client)}};Ne.Sessions=fr;Ne.TranscriptionSessions=_r;var yr=class extends u{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/chatkit/sessions/${e}/cancel`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}};var gr=class extends u{retrieve(e,t){return this._client.get(i`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chatkit/threads",O,{query:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},r){return this._client.getAPIList(i`/chatkit/threads/${e}/items`,O,{query:t,...r,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var Fe=class extends u{constructor(){super(...arguments),this.sessions=new yr(this._client),this.threads=new gr(this._client)}};Fe.Sessions=yr;Fe.Threads=gr;var Ar=class extends u{list(e,t={},r){let{betas:n,...o}=t??{};return this._client.getAPIList(i`/responses/${e}/input_items?beta=true`,C,{query:o,...r,headers:h([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}};var br=class extends u{count(e={},t){let{betas:r,...n}=e??{};return this._client.post("/responses/input_tokens?beta=true",{body:n,...t,headers:h([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}};var Le=class extends u{constructor(){super(...arguments),this.inputItems=new Ar(this._client),this.inputTokens=new br(this._client)}create(e,t){let{betas:r,...n}=e;return this._client.post("/responses?beta=true",{body:n,...t,headers:h([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t={},r){let{betas:n,...o}=t??{};return this._client.get(i`/responses/${e}?beta=true`,{query:o,...r,headers:h([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})}delete(e,t={},r){let{betas:n}=t??{};return this._client.delete(i`/responses/${e}?beta=true`,{...r,headers:h([{Accept:"*/*",...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t={},r){let{betas:n}=t??{};return this._client.post(i`/responses/${e}/cancel?beta=true`,{...r,headers:h([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}compact(e,t){let{betas:r,...n}=e;return this._client.post("/responses/compact?beta=true",{body:n,...t,headers:h([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}};Le.InputItems=Ar;Le.InputTokens=br;var wr=class extends u{create(e,t,r){return this._client.post(i`/threads/${e}/messages`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(i`/threads/${n}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(i`/threads/${n}/messages/${e}`,{body:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/threads/${e}/messages`,C,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){let{thread_id:n}=t;return this._client.delete(i`/threads/${n}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Ir=class extends u{retrieve(e,t,r){let{thread_id:n,run_id:o,...a}=t;return this._client.get(i`/threads/${n}/runs/${o}/steps/${e}`,{query:a,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t,r){let{thread_id:n,...o}=t;return this._client.getAPIList(i`/threads/${n}/runs/${e}/steps`,C,{query:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var qo=s=>{if(typeof Buffer<"u"){let e=Buffer.from(s,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(s),t=e.length,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);return Array.from(new Float32Array(r.buffer))}};var ue=s=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[s]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(s)?.trim()||void 0};var V,nt,Un,fe,Us,ce,ot,Pr,st,zs,se,Bs,Ds,ms,ps,ds,Ho,Wo,Jo,Vo,Xo,Go,Qo,Ie=class extends Ee{constructor(){super(...arguments),V.add(this),Un.set(this,[]),fe.set(this,{}),Us.set(this,{}),ce.set(this,void 0),ot.set(this,void 0),Pr.set(this,void 0),st.set(this,void 0),zs.set(this,void 0),se.set(this,void 0),Bs.set(this,void 0),Ds.set(this,void 0),ms.set(this,void 0)}[(Un=new WeakMap,fe=new WeakMap,Us=new WeakMap,ce=new WeakMap,ot=new WeakMap,Pr=new WeakMap,st=new WeakMap,zs=new WeakMap,se=new WeakMap,Bs=new WeakMap,Ds=new WeakMap,ms=new WeakMap,V=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=structuredClone(n),a=t.shift();a?a.resolve(o):e.push(o)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new nt;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let r=Z.fromReadableStream(e,this.controller);for await(let n of r)c(this,V,"m",ps).call(this,n);if(r.controller.signal?.aborted)throw new M;return this._addRun(c(this,V,"m",ds).call(this))}toReadableStream(){return new Z(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n){let o=new nt;return o._run(()=>o._runToolAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,n){this._listenForAbort(n?.signal);let o={...r,stream:!0},a=await e.submitToolOutputs(t,o,{...n,signal:this.controller.signal});this._connected();for await(let l of a)c(this,V,"m",ps).call(this,l);if(a.controller.signal?.aborted)throw new M;return this._addRun(c(this,V,"m",ds).call(this))}static createThreadAssistantStream(e,t,r){let n=new nt;return n._run(()=>n._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,r,n){let o=new nt;return o._run(()=>o._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return c(this,Bs,"f")}currentRun(){return c(this,Ds,"f")}currentMessageSnapshot(){return c(this,ce,"f")}currentRunStepSnapshot(){return c(this,ms,"f")}async finalRunSteps(){return await this.done(),Object.values(c(this,fe,"f"))}async finalMessages(){return await this.done(),Object.values(c(this,Us,"f"))}async finalRun(){if(await this.done(),!c(this,ot,"f"))throw Error("Final run was not received.");return c(this,ot,"f")}async _createThreadAssistantStream(e,t,r){this._listenForAbort(r?.signal);let n={...t,stream:!0},o=await e.createAndRun(n,{...r,signal:this.controller.signal});this._connected();for await(let a of o)c(this,V,"m",ps).call(this,a);if(o.controller.signal?.aborted)throw new M;return this._addRun(c(this,V,"m",ds).call(this))}async _createAssistantStream(e,t,r,n){this._listenForAbort(n?.signal);let o={...r,stream:!0},a=await e.create(t,o,{...n,signal:this.controller.signal});this._connected();for await(let l of a)c(this,V,"m",ps).call(this,l);if(a.controller.signal?.aborted)throw new M;return this._addRun(c(this,V,"m",ds).call(this))}static accumulateDelta(e,t){for(let[r,n]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=n;continue}let o=e[r];if(o==null){e[r]=n;continue}if(r==="index"||r==="type"){e[r]=n;continue}if(typeof o=="string"&&typeof n=="string")o+=n;else if(typeof o=="number"&&typeof n=="number")o+=n;else if(Wr(o)&&Wr(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(a=>typeof a=="string"||typeof a=="number")){o.push(...n);continue}for(let a of n){if(!Wr(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);let l=a.index;if(l==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);let m=o[l];m==null?o[l]=a:o[l]=this.accumulateDelta(m,a)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${n}, accValue: ${o}`);e[r]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n){return await this._createToolAssistantStream(t,e,r,n)}};nt=Ie,ps=function(e){if(!this.ended)switch(x(this,Bs,e,"f"),c(this,V,"m",Jo).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":c(this,V,"m",Qo).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":c(this,V,"m",Wo).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":c(this,V,"m",Ho).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},ds=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");if(!c(this,ot,"f"))throw Error("Final run has not been received");return c(this,ot,"f")},Ho=function(e){let[t,r]=c(this,V,"m",Xo).call(this,e,c(this,ce,"f"));x(this,ce,t,"f"),c(this,Us,"f")[t.id]=t;for(let n of r){let o=t.content[n.index];o?.type=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,a=t.content[n.index];if(a&&a.type=="text")this._emit("textDelta",o,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=c(this,Pr,"f")){if(c(this,st,"f"))switch(c(this,st,"f").type){case"text":this._emit("textDone",c(this,st,"f").text,c(this,ce,"f"));break;case"image_file":this._emit("imageFileDone",c(this,st,"f").image_file,c(this,ce,"f"));break}x(this,Pr,n.index,"f")}x(this,st,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(c(this,Pr,"f")!==void 0){let n=e.data.content[c(this,Pr,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,c(this,ce,"f"));break;case"text":this._emit("textDone",n.text,c(this,ce,"f"));break}}c(this,ce,"f")&&this._emit("messageDone",e.data),x(this,ce,void 0,"f")}},Wo=function(e){let t=c(this,V,"m",Vo).call(this,e);switch(x(this,ms,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of r.step_details.tool_calls)o.index==c(this,zs,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(c(this,se,"f")&&this._emit("toolCallDone",c(this,se,"f")),x(this,zs,o.index,"f"),x(this,se,t.step_details.tool_calls[o.index],"f"),c(this,se,"f")&&this._emit("toolCallCreated",c(this,se,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":x(this,ms,void 0,"f"),e.data.step_details.type=="tool_calls"&&c(this,se,"f")&&(this._emit("toolCallDone",c(this,se,"f")),x(this,se,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},Jo=function(e){c(this,Un,"f").push(e),this._emit("event",e)},Vo=function(e){switch(e.event){case"thread.run.step.created":return c(this,fe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=c(this,fe,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let n=nt.accumulateDelta(t,r.delta);c(this,fe,"f")[e.data.id]=n}return c(this,fe,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":c(this,fe,"f")[e.data.id]=e.data;break}if(c(this,fe,"f")[e.data.id])return c(this,fe,"f")[e.data.id];throw new Error("No snapshot available")},Xo=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in t.content){let a=t.content[o.index];t.content[o.index]=c(this,V,"m",Go).call(this,o,a)}else t.content[o.index]=o,r.push(o);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Go=function(e,t){return nt.accumulateDelta(t,e)},Qo=function(e){switch(x(this,Ds,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":x(this,ot,e.data,"f"),c(this,se,"f")&&(this._emit("toolCallDone",c(this,se,"f")),x(this,se,void 0,"f"));break;case"thread.run.cancelling":break}};var it=class extends u{constructor(){super(...arguments),this.steps=new Ir(this._client)}create(e,t,r){let{include:n,...o}=t;return this._client.post(i`/threads/${e}/runs`,{query:{include:n},body:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(i`/threads/${n}/runs/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(i`/threads/${n}/runs/${e}`,{body:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/threads/${e}/runs`,C,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,r){let{thread_id:n}=t;return this._client.post(i`/threads/${n}/runs/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(n.id,{thread_id:e},r)}createAndStream(e,t,r){return Ie.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let n=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:a}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let m=a.headers.get("openai-poll-after-ms");if(m){let p=parseInt(m);isNaN(p)||(l=p)}}await de(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return Ie.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:n,...o}=t;return this._client.post(i`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,r){let n=await this.submitToolOutputs(e,t,r);return await this.poll(n.id,t,r)}submitToolOutputsStream(e,t,r){return Ie.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};it.Steps=Ir;var Me=class extends u{constructor(){super(...arguments),this.runs=new it(this._client),this.messages=new wr(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/threads/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return Ie.createThreadAssistantStream(e,this._client.beta.threads,t)}};Me.Runs=it;Me.Messages=wr;var oe=class extends u{constructor(){super(...arguments),this.realtime=new Ne(this._client),this.responses=new Le(this._client),this.chatkit=new Fe(this._client),this.assistants=new hr(this._client),this.threads=new Me(this._client)}};oe.Realtime=Ne;oe.Responses=Le;oe.ChatKit=Fe;oe.Assistants=hr;oe.Threads=Me;var at=class extends u{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var xr=class extends u{retrieve(e,t,r){let{container_id:n}=t;return this._client.get(i`/containers/${n}/files/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var ut=class extends u{constructor(){super(...arguments),this.content=new xr(this._client)}create(e,t,r){return this._client.post(i`/containers/${e}/files`,$e({body:t,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,r){let{container_id:n}=t;return this._client.get(i`/containers/${n}/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/containers/${e}/files`,C,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{container_id:n}=t;return this._client.delete(i`/containers/${n}/files/${e}`,{...r,headers:h([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};ut.Content=xr;var Ke=class extends u{constructor(){super(...arguments),this.files=new ut(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/containers",C,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/containers/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}};Ke.Files=ut;var Rr=class extends u{create(e,t,r){let{include:n,...o}=t;return this._client.post(i`/conversations/${e}/items`,{query:{include:n},body:o,...r,__security:{bearerAuth:!0}})}retrieve(e,t,r){let{conversation_id:n,...o}=t;return this._client.get(i`/conversations/${n}/items/${e}`,{query:o,...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/conversations/${e}/items`,O,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{conversation_id:n}=t;return this._client.delete(i`/conversations/${n}/items/${e}`,{...r,__security:{bearerAuth:!0}})}};var Ue=class extends u{constructor(){super(...arguments),this.items=new Rr(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/conversations/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};Ue.Items=Rr;var ct=class extends u{create(e,t){let r=!!e.encoding_format,n=r?e.encoding_format:"base64";r&&K(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t,__security:{bearerAuth:!0}});return r?o:(K(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(a=>(a&&a.data&&a.data.forEach(l=>{let m=l.embedding;l.embedding=qo(m)}),a)))}};var Sr=class extends u{retrieve(e,t,r){let{eval_id:n,run_id:o}=t;return this._client.get(i`/evals/${n}/runs/${o}/output_items/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t,r){let{eval_id:n,...o}=t;return this._client.getAPIList(i`/evals/${n}/runs/${e}/output_items`,C,{query:o,...r,__security:{bearerAuth:!0}})}};var lt=class extends u{constructor(){super(...arguments),this.outputItems=new Sr(this._client)}create(e,t,r){return this._client.post(i`/evals/${e}/runs`,{body:t,...r,__security:{bearerAuth:!0}})}retrieve(e,t,r){let{eval_id:n}=t;return this._client.get(i`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/evals/${e}/runs`,C,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{eval_id:n}=t;return this._client.delete(i`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}cancel(e,t,r){let{eval_id:n}=t;return this._client.post(i`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}};lt.OutputItems=Sr;var Be=class extends u{constructor(){super(...arguments),this.runs=new lt(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/evals/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/evals",C,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};Be.Runs=lt;var pt=class extends u{create(e,t){return this._client.post("/files",Q({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(i`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/files",C,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(i`/files/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=1800*1e3}={}){let n=new Set(["processed","error","deleted"]),o=Date.now(),a=await this.retrieve(e);for(;!a.status||!n.has(a.status);)if(await de(t),a=await this.retrieve(e),Date.now()-o>r)throw new Ce({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return a}};var Cr=class extends u{};var kr=class extends u{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}})}};var dt=class extends u{constructor(){super(...arguments),this.graders=new kr(this._client)}};dt.Graders=kr;var $r=class extends u{create(e,t,r){return this._client.getAPIList(i`/fine_tuning/checkpoints/${e}/permissions`,G,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},r){return this._client.get(i`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/fine_tuning/checkpoints/${e}/permissions`,O,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{fine_tuned_model_checkpoint:n}=t;return this._client.delete(i`/fine_tuning/checkpoints/${n}/permissions/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var mt=class extends u{constructor(){super(...arguments),this.permissions=new $r(this._client)}};mt.Permissions=$r;var Er=class extends u{list(e,t={},r){return this._client.getAPIList(i`/fine_tuning/jobs/${e}/checkpoints`,C,{query:t,...r,__security:{bearerAuth:!0}})}};var ht=class extends u{constructor(){super(...arguments),this.checkpoints=new Er(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(i`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",C,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},r){return this._client.getAPIList(i`/fine_tuning/jobs/${e}/events`,C,{query:t,...r,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(i`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(i`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}};ht.Checkpoints=Er;var le=class extends u{constructor(){super(...arguments),this.methods=new Cr(this._client),this.jobs=new ht(this._client),this.checkpoints=new mt(this._client),this.alpha=new dt(this._client)}};le.Methods=Cr;le.Jobs=ht;le.Checkpoints=mt;le.Alpha=dt;var Or=class extends u{};var De=class extends u{constructor(){super(...arguments),this.graderModels=new Or(this._client)}};De.GraderModels=Or;var ft=class extends u{createVariation(e,t){return this._client.post("/images/variations",Q({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post("/images/edits",Q({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}})}};var _t=class extends u{retrieve(e,t){return this._client.get(i`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",G,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/models/${e}`,{...t,__security:{bearerAuth:!0}})}};var yt=class extends u{create(e,t){return this._client.post("/moderations",{body:e,...t,__security:{bearerAuth:!0}})}};var vr=class extends u{accept(e,t,r){return this._client.post(i`/realtime/calls/${e}/accept`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(i`/realtime/calls/${e}/hangup`,{...t,headers:h([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,r){return this._client.post(i`/realtime/calls/${e}/refer`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},r){return this._client.post(i`/realtime/calls/${e}/reject`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};var Tr=class extends u{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t,__security:{bearerAuth:!0}})}};var Pe=class extends u{constructor(){super(...arguments),this.clientSecrets=new Tr(this._client),this.calls=new vr(this._client)}};Pe.ClientSecrets=Tr;Pe.Calls=vr;function Yo(s,e){if(!e||!hu(e)){let t={...s,output_parsed:null,output:s.output.map(r=>r.type==="function_call"?{...r,parsed_arguments:null}:r.type==="message"?{...r,content:r.content.map(n=>({...n,parsed:null}))}:r)};return ei(s,t)&&ne(t),t}return Bn(s,e)}function Bn(s,e){let t=!s.status||s.status==="completed",r=s.output.map(o=>{if(o.type==="function_call")return t?_u(e,o):{...o,parsed_arguments:null};if(o.type==="message"){let a=o.content.map(l=>l.type==="output_text"?{...l,parsed:t?mu(e,l.text):null}:l);return{...o,content:a}}return o}),n=Object.assign({},s,{output:r});return ei(s,n)&&ne(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let o of n.output)if(o.type==="message"){for(let a of o.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function mu(s,e){return s.text?.format?.type!=="json_schema"?null:"$parseRaw"in s.text?.format?(s.text?.format).$parseRaw(e):JSON.parse(e)}function hu(s){return es(s.text?.format)?!0:Array.isArray(s.tools)&&s.tools.some(e=>Zo(e)||e.type==="function"&&e.strict===!0)}function Zo(s){return s?.$brand==="auto-parseable-tool"}function fu(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function _u(s,e){let t=fu(s.tools??[],e.name);return{...e,...e,parsed_arguments:Zo(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function ei(s,e){return!Object.getOwnPropertyDescriptor(s,"output_text")||e.output_text==null}function ne(s){let e=[];for(let t of s.output)if(t.type==="message")for(let r of t.content)r.type==="output_text"&&e.push(r.text);s.output_text=e.join("")}function ri(s,e){if(!e){if(s.type!=="response.created")throw new g(`When snapshot hasn't been set yet, expected 'response.created' event, got ${s.type}`);return ti(s.response)}switch(s.type){case"response.output_item.added":{e.output.push(structuredClone(s.item)),s.item.type==="message"&&ne(e);break}case"response.output_item.done":{E(e,s.output_index),e.output[s.output_index]=structuredClone(s.item),s.item.type==="message"&&ne(e);break}case"response.content_part.added":{let t=E(e,s.output_index),r=t.type,n=s.part;r==="message"&&n.type!=="reasoning_text"?(t.content.push(structuredClone(n)),n.type==="output_text"&&ne(e)):r==="reasoning"&&n.type==="reasoning_text"&&(t.content||(t.content=[]),t.content.push(structuredClone(n)));break}case"response.content_part.done":{let t=E(e,s.output_index),r=s.part;if(t.type==="message"&&r.type!=="reasoning_text")ie(t.content,s.content_index),t.content[s.content_index]=structuredClone(r),r.type==="output_text"&&ne(e);else if(t.type==="reasoning"&&r.type==="reasoning_text"){let n=t.content;if(!n)throw new g(`missing content at index ${s.content_index}`);ie(n,s.content_index),n[s.content_index]=structuredClone(r)}break}case"response.output_text.delta":{let t=E(e,s.output_index);if(t.type==="message"){let r=ie(t.content,s.content_index);if(r.type!=="output_text")throw new g(`expected content to be 'output_text', got ${r.type}`);r.text+=s.delta,e.output_text+=s.delta}break}case"response.output_text.done":{let t=E(e,s.output_index);if(t.type==="message"){let r=ie(t.content,s.content_index);if(r.type!=="output_text")throw new g(`expected content to be 'output_text', got ${r.type}`);r.text=s.text,ne(e)}break}case"response.output_text.annotation.added":{let t=E(e,s.output_index);if(t.type==="message"){let r=ie(t.content,s.content_index);if(r.type!=="output_text")throw new g(`expected content to be 'output_text', got ${r.type}`);r.annotations[s.annotation_index]=structuredClone(s.annotation)}break}case"response.refusal.delta":{let t=E(e,s.output_index);if(t.type==="message"){let r=ie(t.content,s.content_index);if(r.type!=="refusal")throw new g(`expected content to be 'refusal', got ${r.type}`);r.refusal+=s.delta}break}case"response.refusal.done":{let t=E(e,s.output_index);if(t.type==="message"){let r=ie(t.content,s.content_index);if(r.type!=="refusal")throw new g(`expected content to be 'refusal', got ${r.type}`);r.refusal=s.refusal}break}case"response.function_call_arguments.delta":{let t=E(e,s.output_index);t.type==="function_call"&&(t.arguments+=s.delta);break}case"response.function_call_arguments.done":{let t=E(e,s.output_index);t.type==="function_call"&&(t.arguments=s.arguments);break}case"response.reasoning_text.delta":{let t=E(e,s.output_index);if(t.type==="reasoning"){if(!t.content)throw new g(`missing content at index ${s.content_index}`);let r=ie(t.content,s.content_index);if(r.type!=="reasoning_text")throw new g(`expected content to be 'reasoning_text', got ${r.type}`);r.text+=s.delta}break}case"response.reasoning_text.done":{let t=E(e,s.output_index);if(t.type==="reasoning"){if(!t.content)throw new g(`missing content at index ${s.content_index}`);let r=ie(t.content,s.content_index);if(r.type!=="reasoning_text")throw new g(`expected content to be 'reasoning_text', got ${r.type}`);r.text=s.text}break}case"response.reasoning_summary_part.added":{let t=E(e,s.output_index);t.type==="reasoning"&&t.summary.push(structuredClone(s.part));break}case"response.reasoning_summary_part.done":{let t=E(e,s.output_index);t.type==="reasoning"&&(ie(t.summary,s.summary_index),t.summary[s.summary_index]=structuredClone(s.part));break}case"response.reasoning_summary_text.delta":{let t=E(e,s.output_index);if(t.type==="reasoning"){let r=ie(t.summary,s.summary_index);r.text+=s.delta}break}case"response.reasoning_summary_text.done":{let t=E(e,s.output_index);if(t.type==="reasoning"){let r=ie(t.summary,s.summary_index);r.text=s.text}break}case"response.custom_tool_call_input.delta":{let t=E(e,s.output_index);t.type==="custom_tool_call"&&(t.input+=s.delta);break}case"response.custom_tool_call_input.done":{let t=E(e,s.output_index);t.type==="custom_tool_call"&&(t.input=s.input);break}case"response.mcp_call_arguments.delta":{let t=E(e,s.output_index);t.type==="mcp_call"&&(t.arguments+=s.delta);break}case"response.mcp_call_arguments.done":{let t=E(e,s.output_index);t.type==="mcp_call"&&(t.arguments=s.arguments);break}case"response.code_interpreter_call_code.delta":{let t=E(e,s.output_index);t.type==="code_interpreter_call"&&(t.code=(t.code??"")+s.delta);break}case"response.code_interpreter_call_code.done":{let t=E(e,s.output_index);t.type==="code_interpreter_call"&&(t.code=s.code);break}case"response.code_interpreter_call.in_progress":{let t=E(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="in_progress");break}case"response.code_interpreter_call.interpreting":{let t=E(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="interpreting");break}case"response.code_interpreter_call.completed":{let t=E(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="completed");break}case"response.file_search_call.in_progress":{let t=E(e,s.output_index);t.type==="file_search_call"&&(t.status="in_progress");break}case"response.file_search_call.searching":{let t=E(e,s.output_index);t.type==="file_search_call"&&(t.status="searching");break}case"response.file_search_call.completed":{let t=E(e,s.output_index);t.type==="file_search_call"&&(t.status="completed");break}case"response.web_search_call.in_progress":{let t=E(e,s.output_index);t.type==="web_search_call"&&(t.status="in_progress");break}case"response.web_search_call.searching":{let t=E(e,s.output_index);t.type==="web_search_call"&&(t.status="searching");break}case"response.web_search_call.completed":{let t=E(e,s.output_index);t.type==="web_search_call"&&(t.status="completed");break}case"response.image_generation_call.in_progress":{let t=E(e,s.output_index);t.type==="image_generation_call"&&(t.status="in_progress");break}case"response.image_generation_call.generating":{let t=E(e,s.output_index);t.type==="image_generation_call"&&(t.status="generating");break}case"response.image_generation_call.completed":{let t=E(e,s.output_index);t.type==="image_generation_call"&&(t.status="completed");break}case"response.mcp_call.in_progress":{let t=E(e,s.output_index);t.type==="mcp_call"&&(t.status="in_progress");break}case"response.mcp_call.completed":{let t=E(e,s.output_index);t.type==="mcp_call"&&(t.status="completed");break}case"response.mcp_call.failed":{let t=E(e,s.output_index);t.type==="mcp_call"&&(t.status="failed");break}case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":{e=ti(s.response);break}case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.image_generation_call.partial_image":case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":case"keepalive":case"error":break;default:yu(s)}return e}function ti(s){let e=structuredClone(s);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&ne(e),e}function E(s,e){let t=s.output[e];if(!t)throw new g(`missing output at index ${e}`);return t}function ie(s,e){let t=s[e];if(!t)throw new g(`missing content at index ${e}`);return t}function yu(s){throw new g(`Unhandled response stream event: ${JSON.stringify(s)}`)}var ze,qs,gt,Hs,Dn,zn,qn,Ws=class s extends Ee{constructor(e){super(),ze.add(this),qs.set(this,void 0),gt.set(this,void 0),Hs.set(this,void 0),x(this,qs,e,"f")}static createResponse(e,t,r){let n=new s(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}async _createOrRetrieveResponse(e,t,r){this._listenForAbort(r?.signal),c(this,ze,"m",Dn).call(this);let n,o=null;"response_id"in t?(n=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=t.starting_after??null):n=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let a of n)c(this,ze,"m",zn).call(this,a,o);if(n.controller.signal?.aborted)throw new M;return c(this,ze,"m",qn).call(this)}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),c(this,ze,"m",Dn).call(this),this._connected();let r=Z.fromReadableStream(e,this.controller);for await(let n of r)c(this,ze,"m",zn).call(this,n,null);if(r.controller.signal?.aborted)throw new M;return c(this,ze,"m",qn).call(this)}[(qs=new WeakMap,gt=new WeakMap,Hs=new WeakMap,ze=new WeakSet,Dn=function(){this.ended||x(this,gt,void 0,"f")},zn=function(t,r){if(this.ended)return;let n=(a,l)=>{(r==null||l.sequence_number>r)&&this._emit(a,l)},o=ri(t,c(this,gt,"f"));switch(x(this,gt,o,"f"),n("event",t),t.type){case"response.output_text.delta":{let a=o.output[t.output_index];if(!a)throw new g(`missing output at index ${t.output_index}`);if(a.type==="message"){let l=a.content[t.content_index];if(!l)throw new g(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new g(`expected content to be 'output_text', got ${l.type}`);n("response.output_text.delta",{...t,snapshot:l.text})}break}case"response.function_call_arguments.delta":{let a=o.output[t.output_index];if(!a)throw new g(`missing output at index ${t.output_index}`);a.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:a.arguments});break}default:n(t.type,t);break}},qn=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");let t=c(this,gt,"f");if(!t)throw new g("request ended without sending any events");x(this,gt,void 0,"f");let r=gu(t,c(this,qs,"f"));return x(this,Hs,r,"f"),r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=c(this,Hs,"f");if(!e)throw new g("stream ended without producing a ChatCompletion");return e}};function gu(s,e){return Yo(s,e)}var jr=class extends u{list(e,t={},r){return this._client.getAPIList(i`/responses/${e}/input_items`,C,{query:t,...r,__security:{bearerAuth:!0}})}};var Nr=class extends u{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t,__security:{bearerAuth:!0}})}};var _e=class extends u{constructor(){super(...arguments),this.inputItems=new jr(this._client),this.inputTokens=new Nr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(r=>("object"in r&&r.object==="response"&&ne(r),r))}retrieve(e,t={},r){return this._client.get(i`/responses/${e}`,{query:t,...r,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&ne(n),n))}delete(e,t){return this._client.delete(i`/responses/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>Bn(r,e))}stream(e,t){return Ws.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(i`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post("/responses/compact",{body:e,...t,__security:{bearerAuth:!0}})}};_e.InputItems=jr;_e.InputTokens=Nr;var Fr=class extends u{retrieve(e,t){return this._client.get(i`/skills/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Lr=class extends u{retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(i`/skills/${n}/versions/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var At=class extends u{constructor(){super(...arguments),this.content=new Lr(this._client)}create(e,t={},r){return this._client.post(i`/skills/${e}/versions`,$e({body:t,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(i`/skills/${n}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/skills/${e}/versions`,C,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{skill_id:n}=t;return this._client.delete(i`/skills/${n}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}};At.Content=Lr;var xe=class extends u{constructor(){super(...arguments),this.content=new Fr(this._client),this.versions=new At(this._client)}create(e={},t){return this._client.post("/skills",$e({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(i`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/skills/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/skills",C,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};xe.Content=Fr;xe.Versions=At;var Mr=class extends u{create(e,t,r){return this._client.post(i`/uploads/${e}/parts`,Q({body:t,...r,__security:{bearerAuth:!0}},this._client))}};var qe=class extends u{constructor(){super(...arguments),this.parts=new Mr(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,r){return this._client.post(i`/uploads/${e}/complete`,{body:t,...r,__security:{bearerAuth:!0}})}};qe.Parts=Mr;var si=async s=>{let e=await Promise.allSettled(s),t=e.filter(n=>n.status==="rejected");if(t.length){for(let n of t)console.error(n.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let r=[];for(let n of e)n.status==="fulfilled"&&r.push(n.value);return r};var Kr=class extends u{create(e,t,r){return this._client.post(i`/vector_stores/${e}/file_batches`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(i`/vector_stores/${n}/file_batches/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,r){let{vector_store_id:n}=t;return this._client.post(i`/vector_stores/${n}/file_batches/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){let n=await this.create(e,t);return await this.poll(e,n.id,r)}listFiles(e,t,r){let{vector_store_id:n,...o}=t;return this._client.getAPIList(i`/vector_stores/${n}/file_batches/${e}/files`,C,{query:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,r){let n=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:a}=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse();switch(o.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let m=a.headers.get("openai-poll-after-ms");if(m){let p=parseInt(m);isNaN(p)||(l=p)}}await de(l);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},n){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=n?.maxConcurrency??5,a=Math.min(o,t.length),l=this._client,m=t.values(),p=[...r];async function _(d){for(let b of d){let I=await l.files.create({file:b,purpose:"assistants"},n);p.push(I.id)}}let f=Array(a).fill(m).map(_);return await si(f),await this.createAndPoll(e,{file_ids:p})}};var Ur=class extends u{create(e,t,r){return this._client.post(i`/vector_stores/${e}/files`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(i`/vector_stores/${n}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{vector_store_id:n,...o}=t;return this._client.post(i`/vector_stores/${n}/files/${e}`,{body:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/vector_stores/${e}/files`,C,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){let{vector_store_id:n}=t;return this._client.delete(i`/vector_stores/${n}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){let n=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse(),a=o.data;switch(a.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let m=o.response.headers.get("openai-poll-after-ms");if(m){let p=parseInt(m);isNaN(p)||(l=p)}}await de(l);break;case"failed":case"completed":return a}}}async upload(e,t,r){let n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){let n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}content(e,t,r){let{vector_store_id:n}=t;return this._client.getAPIList(i`/vector_stores/${n}/files/${e}/content`,G,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Re=class extends u{constructor(){super(...arguments),this.files=new Ur(this._client),this.fileBatches=new Kr(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/vector_stores/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vector_stores",C,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,r){return this._client.getAPIList(i`/vector_stores/${e}/search`,G,{body:t,method:"post",...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};Re.Files=Ur;Re.FileBatches=Kr;var bt=class extends u{create(e,t){return this._client.post("/videos",Q({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(i`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/videos",O,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post("/videos/characters",Q({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},r){return this._client.get(i`/videos/${e}/content`,{query:t,...r,headers:h([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post("/videos/edits",Q({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post("/videos/extensions",Q({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(i`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,r){return this._client.post(i`/videos/${e}/remix`,$e({body:t,...r,__security:{bearerAuth:!0}},this._client))}};var Br,ni,Js,wt=class extends u{constructor(){super(...arguments),Br.add(this)}async unwrap(e,t,r=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,r,n),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,n=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");c(this,Br,"m",ni).call(this,r);let o=h([t]).values,a=c(this,Br,"m",Js).call(this,o,"webhook-signature"),l=c(this,Br,"m",Js).call(this,o,"webhook-timestamp"),m=c(this,Br,"m",Js).call(this,o,"webhook-id"),p=parseInt(l,10);if(isNaN(p))throw new pe("Invalid webhook timestamp format");let _=Math.floor(Date.now()/1e3);if(_-p>n)throw new pe("Webhook timestamp is too old");if(p>_+n)throw new pe("Webhook timestamp is too new");let f=a.split(" ").map(A=>A.startsWith("v1,")?A.substring(3):A),d=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),b=m?`${m}.${l}.${e}`:`${l}.${e}`,I=await crypto.subtle.importKey("raw",d,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let A of f)try{let w=Buffer.from(A,"base64");if(await crypto.subtle.verify("HMAC",I,w,new TextEncoder().encode(b)))return}catch{continue}throw new pe("The given webhook signature does not match the expected signature")}};Br=new WeakSet,ni=function(e){if(typeof e!="string"||e.length===0)throw new 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")},Js=function(e,t){if(!e)throw new Error("Headers are required");let r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var ii=Symbol.for("openai.node.providerDefinitions.v1"),ai=globalThis,ui=ai[ii],ci=ui??new WeakMap;ui||Object.defineProperty(ai,ii,{value:ci});function li(s){let e=ci.get(s);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var Hn,Wn,hs,pi,Cu="workload-identity-auth",S=class{constructor(e={}){Hn.add(this),hs.set(this,void 0),this.completions=new at(this),this.chat=new ve(this),this.embeddings=new ct(this),this.files=new pt(this),this.images=new ft(this),this.audio=new he(this),this.moderations=new yt(this),this.models=new _t(this),this.fineTuning=new le(this),this.graders=new De(this),this.vectorStores=new Re(this),this.webhooks=new wt(this),this.beta=new oe(this),this.batches=new rt(this),this.uploads=new qe(this),this.admin=new je(this),this.responses=new _e(this),this.realtime=new Pe(this),this.conversations=new Ue(this),this.evals=new Be(this),this.containers=new Ke(this),this.skills=new xe(this),this.videos=new bt(this);let t=e.provider;if(t){let A=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(w=>e[w]!=null);if(A.length)throw new g(`The \`provider\` option cannot be used with ${A.map(w=>`\`${w}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:r=t?null:ue("OPENAI_BASE_URL"),apiKey:n=t?null:ue("OPENAI_API_KEY")??null,adminAPIKey:o=t?null:ue("OPENAI_ADMIN_KEY")??null,organization:a=t?null:ue("OPENAI_ORG_ID")??null,project:l=t?null:ue("OPENAI_PROJECT_ID")??null,webhookSecret:m=ue("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:p,..._}=e,f=t?li(t):void 0,d={apiKey:n,adminAPIKey:o,organization:a,project:l,webhookSecret:m,workloadIdentity:p,provider:t,..._,baseURL:f?.baseURL??(r||"https://api.openai.com/v1")};if(n&&p)throw new g("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!f&&!n&&!o&&!p)throw new g("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!d.dangerouslyAllowBrowser&&io())throw new g(`It looks like you're running in a browser-like environment.
20
+ ${m}`)}return a},i=Hi(To);var Ge=class extends u{list(e,t={},r){return this._client.getAPIList(i`/chat/completions/${e}/messages`,C,{query:t,...r,__security:{bearerAuth:!0}})}};function ts(s){return s!==void 0&&"function"in s&&s.function!==void 0}function rs(s){return s?.$brand==="auto-parseable-response-format"}function Qe(s){return s?.$brand==="auto-parseable-tool"}function No(s,e){return!e||!Sn(e)?{...s,choices:s.choices.map(t=>(Lo(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:ss(s,e)}function ss(s,e){let t=s.choices.map(r=>{if(r.finish_reason==="length")throw new Tt;if(r.finish_reason==="content_filter")throw new jt;return Lo(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(n=>Vi(e,n))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Ji(e,r.message.content):null}}});return{...s,choices:t}}function Ji(s,e){return s.response_format?.type!=="json_schema"?null:s.response_format?.type==="json_schema"?"$parseRaw"in s.response_format?s.response_format.$parseRaw(e):JSON.parse(e):null}function Vi(s,e){let t=s.tools?.find(r=>ts(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Qe(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function Fo(s,e){if(!s||!("tools"in s)||!s.tools)return!1;let t=s.tools?.find(r=>ts(r)&&r.function?.name===e.function.name);return ts(t)&&(Qe(t)||t?.function.strict||!1)}function Sn(s){return rs(s.response_format)?!0:s.tools?.some(e=>Qe(e)||e.type==="function"&&e.function.strict===!0)??!1}function Lo(s){for(let e of s||[])if(e.type!=="function")throw new g(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Mo(s){for(let e of s??[]){if(e.type!=="function")throw new g(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new g(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var ge=s=>s?.role==="assistant",ns=s=>s?.role==="tool";var os,Ns,Fs,is,as,Ls,us,Ae,Ms,cs,Ks,Bs,Bt,Ko,Cn,Ee=class{constructor(){os.add(this),this.controller=new AbortController,Ns.set(this,void 0),Fs.set(this,()=>{}),is.set(this,()=>{}),as.set(this,void 0),Ls.set(this,()=>{}),us.set(this,()=>{}),Ae.set(this,{}),Ms.set(this,[]),cs.set(this,!1),Ks.set(this,!1),Bs.set(this,!1),Bt.set(this,!1),x(this,Ns,new Promise((e,t)=>{x(this,Fs,e,"f"),x(this,is,t,"f")}),"f"),x(this,as,new Promise((e,t)=>{x(this,Ls,e,"f"),x(this,us,t,"f")}),"f"),c(this,Ns,"f").catch(()=>{}),c(this,as,"f").catch(()=>{})}_run(e){setTimeout(()=>{Promise.resolve().then(e).then(()=>{try{this._emitFinal()}catch(t){c(this,os,"m",Cn).call(this,t);return}this._emit("end")},c(this,os,"m",Cn).bind(this))},0)}_connected(){this.ended||(c(this,Fs,"f").call(this),this._emit("connect"))}get ended(){return c(this,cs,"f")}get errored(){return c(this,Ks,"f")}get aborted(){return c(this,Bs,"f")}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let t=()=>this.controller.abort();e.addEventListener("abort",t,{once:!0}),c(this,Ms,"f").push({signal:e,listener:t})}on(e,t){return(c(this,Ae,"f")[e]||(c(this,Ae,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=c(this,Ae,"f")[e];if(!r)return this;let n=r.findIndex(o=>o.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(c(this,Ae,"f")[e]||(c(this,Ae,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{x(this,Bt,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}events(e){let t=[],r=[],n=this.ended,o,a=!1,l=()=>({value:void 0,done:!0}),f=()=>{for(;r.length;)r.shift().resolve(l())},p=()=>{!o||a||!r.length||(a=!0,r.shift().reject(o))},_=()=>{this.off(e,m),this.off("end",b),e!=="error"&&this.off("error",d),e!=="abort"&&this.off("abort",d)},m=(...w)=>{if(n)return;let A=r.shift();A?A.resolve({value:w,done:!1}):t.push(w)},d=w=>{o=w,t.length||p()},b=()=>{n=!0,_(),t.length||(p(),f())};return n||(this.on(e,m),this.on("end",b),e!=="error"&&this.on("error",d),e!=="abort"&&this.on("abort",d)),{next:()=>{let w=t.shift();return w?Promise.resolve({value:w,done:!1}):o&&!a?(a=!0,Promise.reject(o)):n?Promise.resolve(l()):new Promise((A,I)=>{r.push({resolve:A,reject:I})})},return:()=>(n=!0,t.length=0,_(),f(),Promise.resolve(l())),[Symbol.asyncIterator](){return this}}}async done(){x(this,Bt,!0,"f"),await c(this,as,"f")}_emit(e,...t){if(c(this,cs,"f"))return;e==="end"&&(c(this,os,"m",Ko).call(this),x(this,cs,!0,"f"),c(this,Ls,"f").call(this));let r=c(this,Ae,"f")[e];if(r&&(c(this,Ae,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!c(this,Bt,"f")&&!r?.length&&Promise.reject(n),c(this,is,"f").call(this,n),c(this,us,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!c(this,Bt,"f")&&!r?.length&&Promise.reject(n),c(this,is,"f").call(this,n),c(this,us,"f").call(this,n),this._emit("end")}}_emitFinal(){}};Ns=new WeakMap,Fs=new WeakMap,is=new WeakMap,as=new WeakMap,Ls=new WeakMap,us=new WeakMap,Ae=new WeakMap,Ms=new WeakMap,cs=new WeakMap,Ks=new WeakMap,Bs=new WeakMap,Bt=new WeakMap,os=new WeakSet,Ko=function(){for(let{signal:e,listener:t}of c(this,Ms,"f").splice(0))e.removeEventListener("abort",t)},Cn=function(e){if(x(this,Ks,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new M),e instanceof M)return x(this,Bs,!0,"f"),this._emit("abort",e);if(e instanceof g)return this._emit("error",e);if(e instanceof Error){let t=new g(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new g(String(e)))};function Bo(s){return typeof s.parse=="function"}var Y,kn,Us,$n,En,On,Uo,Do,Xi=10;function Gi(s){for(let e of s.choices)for(let t of e.message.tool_calls??[])t.id||(t.id=`call_${We()}`)}function Qi(s){if(!ge(s))return s;let e={role:"assistant"};return s.audio!=null&&(e.audio={id:s.audio.id}),s.content!==void 0&&(e.content=s.content),s.function_call!=null&&(e.function_call=s.function_call),s.name!==void 0&&(e.name=s.name),s.refusal!=null&&(e.refusal=s.refusal),s.tool_calls!==void 0&&(e.tool_calls=s.tool_calls.map(t=>t.type==="custom"?{id:t.id,type:t.type,custom:{input:t.custom.input,name:t.custom.name}}:{id:t.id,type:t.type,function:{arguments:t.function.arguments,name:t.function.name}})),e}var Ut=class extends Ee{constructor(){super(...arguments),Y.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){Gi(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),ns(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(ge(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new g("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),c(this,Y,"m",kn).call(this)}async finalMessage(){return await this.done(),c(this,Y,"m",Us).call(this)}async finalFunctionToolCall(){return await this.done(),c(this,Y,"m",$n).call(this)}async finalFunctionToolCallResult(){return await this.done(),c(this,Y,"m",En).call(this)}async totalUsage(){return await this.done(),c(this,Y,"m",On).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=c(this,Y,"m",Us).call(this);t&&this._emit("finalMessage",t);let r=c(this,Y,"m",kn).call(this);r&&this._emit("finalContent",r);let n=c(this,Y,"m",$n).call(this);n&&this._emit("finalFunctionToolCall",n);let o=c(this,Y,"m",En).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",c(this,Y,"m",On).call(this))}async _createChatCompletion(e,t,r){this._listenForAbort(r?.signal),c(this,Y,"m",Uo).call(this,t);let n=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(ss(n,t))}async _runChatCompletion(e,t,r){for(let n of t.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r,n){let o="tool",{tool_choice:a="auto",stream:l,toolContext:f,...p}=t,_=f,m=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:d=Xi,afterCompletion:b}=n||{},w=t.tools.map(y=>{if(Qe(y)){if(!y.$callback)throw new g("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:y.$callback,name:y.function.name,description:y.function.description||"",parameters:y.function.parameters,parse:y.$parseRaw,strict:!0}}}return y}),A={};for(let y of w)y.type==="function"&&(A[y.function.name||y.function.function.name]=y.function);let I="tools"in t?w.map(y=>y.type==="function"?{type:"function",function:{name:y.function.name||y.function.function.name,parameters:y.function.parameters,description:y.function.description,strict:y.function.strict}}:y):void 0;for(let y of t.messages)this._addMessage(y,!1);let k=async y=>{if(y.type!=="function")return{message:void 0,functionCalled:!1};let P=y.id,{name:R,arguments:v}=y.function,$=A[R];if(!$){let N=`Invalid tool_call: ${JSON.stringify(R)}. Available options are: ${Object.keys(A).map(T=>JSON.stringify(T)).join(", ")}. Please try again`;return{message:{role:o,tool_call_id:P,content:N},functionCalled:!1}}if(m&&m!==R){let N=`Invalid tool_call: ${JSON.stringify(R)}. ${JSON.stringify(m)} requested. Please try again`;return{message:{role:o,tool_call_id:P,content:N},functionCalled:!1}}let L;if(Bo($)){let N;try{N=await $.parse(v)}catch(T){let W=T instanceof Error?T.message:String(T);return{message:{role:o,tool_call_id:P,content:W},functionCalled:!1}}L=await $.function(N,r,_)}else L=await $.function(v,r,_);let j=c(this,Y,"m",Do).call(this,L);return{message:{role:o,tool_call_id:P,content:j},functionCalled:!0}};for(let y=0;y<d;++y){let P=await this._createChatCompletion(e,{...p,tool_choice:a,tools:I,messages:this.messages.map(Qi)},n),R=P.choices[0]?.message;if(!R)throw new g("missing message in ChatCompletion response");if(!R.tool_calls?.length){await b?.(P,r);return}if(m||t.parallel_tool_calls===!1)for(let v of R.tool_calls){let $=await k(v);if($.message&&this._addMessage($.message),m&&$.functionCalled){await b?.(P,r);return}}else{let v=await Promise.allSettled(R.tool_calls.map(k));for(let $ of v)if($.status==="rejected")throw $.reason;for(let $ of v)$.status==="fulfilled"&&$.value.message&&this._addMessage($.value.message)}await b?.(P,r)}}};Y=new WeakSet,kn=function(){return c(this,Y,"m",Us).call(this).content??null},Us=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(ge(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new g("stream ended without producing a ChatCompletionMessage with role=assistant")},$n=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(ge(t)&&t?.tool_calls?.length)for(let r=t.tool_calls.length-1;r>=0;r--){let n=t.tool_calls[r];if(n?.type==="function")return n.function}}},En=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(ns(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(n=>n.type==="function"&&n.id===t.tool_call_id)))return t.content}},On=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},Uo=function(e){if(e.n!=null&&e.n>1)throw new g("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Do=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var ls=class s extends Ut{static runTools(e,t,r){let n=new s,o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,n,o)),n}_addMessage(e,t=!0){super._addMessage(e,t),ge(e)&&e.content&&this._emit("content",e.content)}};var z={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},vn=class extends Error{},Tn=class extends Error{};function Yi(s,e=z.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return Zi(s.trim(),e)}var Zi=(s,e)=>{let t=s.length,r=0,n=d=>{throw new vn(`${d} at position ${r}`)},o=d=>{throw new Tn(`${d} at position ${r}`)},a=()=>(m(),r>=t&&n("Unexpected end of input"),s[r]==='"'?l():s[r]==="{"?f():s[r]==="["?p():s.substring(r,r+4)==="null"||z.NULL&e&&t-r<4&&"null".startsWith(s.substring(r))?(r+=4,null):s.substring(r,r+4)==="true"||z.BOOL&e&&t-r<4&&"true".startsWith(s.substring(r))?(r+=4,!0):s.substring(r,r+5)==="false"||z.BOOL&e&&t-r<5&&"false".startsWith(s.substring(r))?(r+=5,!1):s.substring(r,r+8)==="Infinity"||z.INFINITY&e&&t-r<8&&"Infinity".startsWith(s.substring(r))?(r+=8,1/0):s.substring(r,r+9)==="-Infinity"||z.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(s.substring(r))?(r+=9,-1/0):s.substring(r,r+3)==="NaN"||z.NAN&e&&t-r<3&&"NaN".startsWith(s.substring(r))?(r+=3,NaN):_()),l=()=>{let d=r,b=!1;for(r++;r<t&&(s[r]!=='"'||b&&s[r-1]==="\\");)b=s[r]==="\\"?!b:!1,r++;if(s.charAt(r)=='"')try{return JSON.parse(s.substring(d,++r-Number(b)))}catch(w){o(String(w))}else if(z.STR&e)try{return JSON.parse(s.substring(d,r-Number(b))+'"')}catch{return JSON.parse(s.substring(d,s.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},f=()=>{r++,m();let d={};try{for(;s[r]!=="}";){if(m(),r>=t&&z.OBJ&e)return d;let b=l();m(),r++;try{let w=a();Object.defineProperty(d,b,{value:w,writable:!0,enumerable:!0,configurable:!0})}catch(w){if(z.OBJ&e)return d;throw w}m(),s[r]===","&&r++}}catch{if(z.OBJ&e)return d;n("Expected '}' at end of object")}return r++,d},p=()=>{r++;let d=[];try{for(;s[r]!=="]";)d.push(a()),m(),s[r]===","&&r++}catch{if(z.ARR&e)return d;n("Expected ']' at end of array")}return r++,d},_=()=>{if(r===0){s==="-"&&z.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s)}catch(b){if(z.NUM&e)try{return s[s.length-1]==="."?JSON.parse(s.substring(0,s.lastIndexOf("."))):JSON.parse(s.substring(0,s.lastIndexOf("e")))}catch{}o(String(b))}}let d=r;for(s[r]==="-"&&r++;s[r]&&!",]}".includes(s[r]);)r++;r==t&&!(z.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(s.substring(d,r))}catch{s.substring(d,r)==="-"&&z.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s.substring(d,s.lastIndexOf("e")))}catch(w){o(String(w))}}},m=()=>{for(;r<t&&`
21
+ \r `.includes(s[r]);)r++};return a()},jn=s=>Yi(s,z.ALL^z.NUM);var U,be,Oe,Dt,ae,Nn,Ds,Fn,Ln,Mn,ps,Kn,zo,Un="chat.completion.chunk.message:";function qo(s,e,t){let r={type:"message",message:e,...t?{tool_call_ids:t}:{}};return{id:s.id,choices:[],created:s.created,model:s.model,object:`${Un}${JSON.stringify(r)}`}}function ea(s){return"type"in s&&s.type==="message"&&"message"in s||"object"in s&&typeof s.object=="string"&&s.object.startsWith(Un)}function ta(s){return"type"in s?s:JSON.parse(s.object.slice(Un.length))}var Ye=class s extends Ut{constructor(e){super(),U.add(this),be.set(this,void 0),Oe.set(this,void 0),Dt.set(this,void 0),ae.set(this,void 0),x(this,be,e,"f"),x(this,Oe,new Set,"f"),x(this,Dt,[],"f")}get currentChatCompletionSnapshot(){return c(this,ae,"f")}static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let n=new s(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,r){super._createChatCompletion,this._listenForAbort(r?.signal),c(this,U,"m",Nn).call(this);let n=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let o of n)c(this,U,"m",Fn).call(this,o);if(n.controller.signal?.aborted)throw new M;return this._addChatCompletion(c(this,U,"m",ps).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),c(this,U,"m",Nn).call(this),this._connected();let r=Z.fromReadableStream(e,this.controller),n;for await(let a of r){if(ea(a)){let f=ta(a);if(c(this,ae,"f")){let p=c(this,ae,"f").choices[0]?.message.tool_calls;for(let[_,m]of f.tool_call_ids?.entries()??[]){let d=p?.[_];d&&m&&(d.id=m)}this._addChatCompletion(c(this,U,"m",ps).call(this)),n=void 0}this._addMessage(f.message);continue}let l=a;n&&l.id&&n!==l.id&&this._addChatCompletion(c(this,U,"m",ps).call(this)),c(this,U,"m",Fn).call(this,l),l.id&&(n=l.id)}if(r.controller.signal?.aborted)throw new M;if(c(this,ae,"f"))return this._addChatCompletion(c(this,U,"m",ps).call(this));let o=this._chatCompletions[this._chatCompletions.length-1];if(o)return o;throw new g("request ended without sending any chunks")}[(be=new WeakMap,Oe=new WeakMap,Dt=new WeakMap,ae=new WeakMap,U=new WeakSet,Nn=function(){this.ended||(x(this,Oe,new Set,"f"),x(this,ae,void 0,"f"))},Ds=function(t){let r=c(this,Dt,"f")[t.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},c(this,Dt,"f")[t.index]=r,r)},Fn=function(t){if(this.ended)return;let r=c(this,U,"m",zo).call(this,t);this._emit("chunk",t,r);for(let n of t.choices){let o=r.choices[n.index],{delta:a}=n;a?.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",a.content,o.message.content),this._emit("content.delta",{delta:a.content,snapshot:o.message.content,parsed:o.message.parsed})),a?.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:a.refusal,snapshot:o.message.refusal}),n.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:o.logprobs?.content??[]}),n.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let l=c(this,U,"m",Ds).call(this,o);o.finish_reason&&(c(this,U,"m",Mn).call(this,o),l.current_tool_call_index!=null&&c(this,U,"m",Ln).call(this,o,l.current_tool_call_index));for(let f of a?.tool_calls??[])l.current_tool_call_index!==f.index&&(c(this,U,"m",Mn).call(this,o),l.current_tool_call_index!=null&&c(this,U,"m",Ln).call(this,o,l.current_tool_call_index)),l.current_tool_call_index=f.index;for(let f of a?.tool_calls??[]){let p=o.message.tool_calls?.[f.index];p?.type&&(p?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:p.function?.name,index:f.index,arguments:p.function.arguments,parsed_arguments:p.function.parsed_arguments,arguments_delta:f.function?.arguments??""}):(p?.type,void 0))}}},Ln=function(t,r){if(c(this,U,"m",Ds).call(this,t).done_tool_calls.has(r))return;let o=t.message.tool_calls?.[r];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let a=c(this,be,"f")?.tools?.find(l=>ts(l)&&l.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:r,arguments:o.function.arguments,parsed_arguments:Qe(a)?a.$parseRaw(o.function.arguments):a?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},Mn=function(t){let r=c(this,U,"m",Ds).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let n=c(this,U,"m",Kn).call(this);this._emit("content.done",{content:t.message.content,parsed:n?n.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},ps=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");let t=c(this,ae,"f");if(!t)throw new g("request ended without sending any chunks");let r=c(this,Oe,"f");return x(this,Oe,new Set,"f"),x(this,ae,void 0,"f"),x(this,Dt,[],"f"),ra(t,c(this,be,"f"),r)},Kn=function(){let t=c(this,be,"f")?.response_format;return rs(t)?t:null},zo=function(t){var r,n,o,a,l;let f=c(this,ae,"f"),{choices:p,..._}=t;f?t.id&&Object.assign(f,_):f=x(this,ae,{..._,choices:[]},"f");for(let{delta:m,finish_reason:d,index:b,logprobs:w=null,...A}of t.choices){let I=f.choices[b];if(I||(I=f.choices[b]={finish_reason:d,index:b,message:{},logprobs:w,...A}),w)if(!I.logprobs)I.logprobs=Object.assign({},w);else{let{content:j,refusal:N,...T}=w;Object.assign(I.logprobs,T),j&&((r=I.logprobs).content??(r.content=[]),I.logprobs.content.push(...j)),N&&((n=I.logprobs).refusal??(n.refusal=[]),I.logprobs.refusal.push(...N))}if(d&&(I.finish_reason=d,c(this,be,"f")&&Sn(c(this,be,"f")))){if(d==="length")throw new Tt;if(d==="content_filter")throw new jt}if(Object.assign(I,A),!m)continue;c(this,Oe,"f").delete(b);let{audio:k,content:y,refusal:P,function_call:R,role:v,tool_calls:$,...L}=m;if(Object.assign(I.message,L),k?.expires_at!=null&&k.id==null&&k.data==null&&k.transcript==null&&y==null&&P==null&&R==null&&v==null&&$==null&&Object.keys(L).length===0&&c(this,Oe,"f").add(b),P&&(I.message.refusal=(I.message.refusal||"")+P),v&&(I.message.role=v),k){let j=(o=I.message).audio??(o.audio={});k.id!=null&&(j.id=k.id),k.data!=null&&(j.data=(j.data??"")+k.data),k.transcript!=null&&(j.transcript=(j.transcript??"")+k.transcript),k.expires_at!=null&&(j.expires_at=k.expires_at)}if(R&&(I.message.function_call?(R.name&&(I.message.function_call.name=R.name),R.arguments&&((a=I.message.function_call).arguments??(a.arguments=""),I.message.function_call.arguments+=R.arguments)):I.message.function_call=R),y&&(I.message.content=(I.message.content||"")+y,!I.message.refusal&&c(this,U,"m",Kn).call(this)&&(I.message.parsed=I.message.content.trim()?jn(I.message.content):null)),$){I.message.tool_calls||(I.message.tool_calls=[]);for(let{index:j,id:N,type:T,function:W,...Pt}of $){let J=(l=I.message.tool_calls)[j]??(l[j]={});Object.assign(J,Pt),N&&(J.id=N),T&&(J.type=T),W&&(J.function??(J.function={name:W.name??"",arguments:""})),W?.name&&(J.function.name=W.name),W?.arguments&&(J.function.arguments+=W.arguments,Fo(c(this,be,"f"),J)&&(J.function.parsed_arguments=jn(J.function.arguments)))}}}return f},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Z(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function ra(s,e,t){let{id:r,choices:n,created:o,model:a,system_fingerprint:l,...f}=s,p={...f,id:r,choices:n.map(({message:_,finish_reason:m,index:d,logprobs:b,...w})=>{let{content:A=null,function_call:I,tool_calls:k,audio:y,...P}=_,R=m??(t.has(d)&&sa(y)?"stop":null);if(!R)throw new g(`missing finish_reason for choice ${d}`);let v=y?{audio:y}:{},$=_.role;if(!$)throw new g(`missing role for choice ${d}`);if(I){let{arguments:L,name:j}=I;if(L==null)throw new g(`missing function_call.arguments for choice ${d}`);if(!j)throw new g(`missing function_call.name for choice ${d}`);return{...w,message:{...v,content:A,function_call:{arguments:L,name:j},role:$,refusal:_.refusal??null},finish_reason:R,index:d,logprobs:b}}return k?{...w,index:d,finish_reason:R,logprobs:b,message:{...P,...v,role:$,content:A,refusal:_.refusal??null,tool_calls:k.map((L,j)=>{let{function:N,type:T,id:W,...Pt}=L,{arguments:J,name:ys,...gs}=N||{};if(T==null)throw new g(`missing choices[${d}].tool_calls[${j}].type
22
+ ${Bn(s)}`);if(ys==null)throw new g(`missing choices[${d}].tool_calls[${j}].function.name
23
+ ${Bn(s)}`);if(J==null)throw new g(`missing choices[${d}].tool_calls[${j}].function.arguments
24
+ ${Bn(s)}`);return{...Pt,id:W||`call_${We()}`,type:T,function:{...gs,name:ys,arguments:J}}})}}:{...w,message:{...P,...v,content:A,role:$,refusal:_.refusal??null},finish_reason:R,index:d,logprobs:b}}),created:o,model:a,object:"chat.completion",...l?{system_fingerprint:l}:{}};return No(p,e)}function sa(s){return s?.id!=null&&s.data!=null&&s.transcript!=null&&s.expires_at!=null}function Bn(s){return JSON.stringify(s)}var ds=class s extends Ye{static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}toReadableStream(){let e=[],t=[],r=!1,n,o,a=p=>{let _=t.shift();_?_.resolve(p):e.push(p)};this.on("chunk",p=>{n=p,a(p)}),this.on("message",p=>{if(ge(p)){o=p.tool_calls?.map(_=>_.id);return}if(ns(p)){if(!n)throw new g("cannot serialize a tool message before receiving any chunks");a(qo(n,p,o))}}),this.on("end",()=>{r=!0;for(let p of t)p.resolve(void 0);t.length=0}),this.on("abort",p=>{r=!0;for(let _ of t)_.reject(p);t.length=0}),this.on("error",p=>{r=!0;for(let _ of t)_.reject(p);t.length=0});let l=()=>({next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise((_,m)=>t.push({resolve:_,reject:m})).then(_=>_?{value:_,done:!1}:{value:void 0,done:!0});let p=e.shift();return p?{value:p,done:!1}:{value:void 0,done:!0}},return:async()=>(this.abort(),{value:void 0,done:!0})});return new Z(l,this.controller).toReadableStream()}static runTools(e,t,r){let n=new s(t),o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,n,o)),n}};var Ie=class extends u{constructor(){super(...arguments),this.messages=new Ge(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(i`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/chat/completions/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chat/completions",C,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return Mo(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>ss(r,e))}runTools(e,t){return e.stream?ds.runTools(this._client,e,t):ls.runTools(this._client,e,t)}stream(e,t){return Ye.createChatCompletion(this._client,e,t)}};Ie.Messages=Ge;var ve=class extends u{constructor(){super(...arguments),this.completions=new Ie(this._client)}};ve.Completions=Ie;var zt=class extends u{create(e,t){return this._client.post("/organization/admin_api_keys",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/admin_api_keys",C,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var qt=class extends u{list(e={},t){return this._client.getAPIList("/organization/audit_logs",O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}};var Ht=class extends u{create(e,t){return this._client.post("/organization/certificates",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},r){return this._client.get(i`/organization/certificates/${e}`,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/certificates/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/certificates",O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList("/organization/certificates/activate",G,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList("/organization/certificates/deactivate",G,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}};var Wt=class extends u{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}})}};var Jt=class extends u{create(e,t){return this._client.post("/organization/invites",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/invites",O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Vt=class extends u{create(e,t){return this._client.post("/organization/roles",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/roles/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/roles",B,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Xt=class extends u{create(e,t){return this._client.post("/organization/spend_alerts",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/spend_alerts/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/spend_alerts",O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Gt=class extends u{retrieve(e){return this._client.get("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post("/organization/spend_limit",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e){return this._client.delete("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}};var Qt=class extends u{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}})}};var Yt=class extends u{create(e,t,r){return this._client.post(i`/organization/groups/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{group_id:n}=t;return this._client.get(i`/organization/groups/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/groups/${e}/roles`,B,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{group_id:n}=t;return this._client.delete(i`/organization/groups/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Zt=class extends u{create(e,t,r){return this._client.post(i`/organization/groups/${e}/users`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{group_id:n}=t;return this._client.get(i`/organization/groups/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/groups/${e}/users`,B,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{group_id:n}=t;return this._client.delete(i`/organization/groups/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Te=class extends u{constructor(){super(...arguments),this.users=new Zt(this._client),this.roles=new Yt(this._client)}create(e,t){return this._client.post("/organization/groups",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/groups/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/groups",B,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};Te.Users=Zt;Te.Roles=Yt;var er=class extends u{retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/api_keys`,O,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var tr=class extends u{list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/certificates`,O,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}activate(e,t,r){return this._client.getAPIList(i`/organization/projects/${e}/certificates/activate`,G,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,r){return this._client.getAPIList(i`/organization/projects/${e}/certificates/deactivate`,G,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var rr=class extends u{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/data_retention`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}};var sr=class extends u{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}};var nr=class extends u{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/model_permissions`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}};var or=class extends u{listRateLimits(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/rate_limits`,O,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/rate_limits/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}};var ir=class extends u{create(e,t,r){return this._client.post(i`/projects/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/projects/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/roles/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/projects/${e}/roles`,B,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/projects/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var ar=class extends u{create(e,t,r){return this._client.post(i`/organization/projects/${e}/spend_alerts`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/spend_alerts/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/spend_alerts`,O,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var ur=class extends u{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/spend_limit`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}};var cr=class extends u{create(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/groups/${e}/roles`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n,group_id:o}=t;return this._client.get(i`/projects/${n}/groups/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t,r){let{project_id:n,...o}=t;return this._client.getAPIList(i`/projects/${n}/groups/${e}/roles`,B,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n,group_id:o}=t;return this._client.delete(i`/projects/${n}/groups/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Ze=class extends u{constructor(){super(...arguments),this.roles=new cr(this._client)}create(e,t,r){return this._client.post(i`/organization/projects/${e}/groups`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n,...o}=t;return this._client.get(i`/organization/projects/${n}/groups/${e}`,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/groups`,B,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Ze.Roles=cr;var lr=class extends u{create(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/service_accounts/${e}/api_keys`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}};var et=class extends u{constructor(){super(...arguments),this.apiKeys=new lr(this._client)}create(e,t,r){return this._client.post(i`/organization/projects/${e}/service_accounts`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/service_accounts/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/service_accounts`,O,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};et.APIKeys=lr;var pr=class extends u{create(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/users/${e}/roles`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n,user_id:o}=t;return this._client.get(i`/projects/${n}/users/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t,r){let{project_id:n,...o}=t;return this._client.getAPIList(i`/projects/${n}/users/${e}/roles`,B,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n,user_id:o}=t;return this._client.delete(i`/projects/${n}/users/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var tt=class extends u{constructor(){super(...arguments),this.roles=new pr(this._client)}create(e,t,r){return this._client.post(i`/organization/projects/${e}/users`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/users/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/users`,O,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};tt.Roles=pr;var q=class extends u{constructor(){super(...arguments),this.users=new tt(this._client),this.serviceAccounts=new et(this._client),this.apiKeys=new er(this._client),this.rateLimits=new or(this._client),this.modelPermissions=new nr(this._client),this.hostedToolPermissions=new sr(this._client),this.groups=new Ze(this._client),this.roles=new ir(this._client),this.dataRetention=new rr(this._client),this.spendLimit=new ur(this._client),this.spendAlerts=new ar(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(i`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/projects",O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(i`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};q.Users=tt;q.ServiceAccounts=et;q.APIKeys=er;q.RateLimits=or;q.ModelPermissions=nr;q.HostedToolPermissions=sr;q.Groups=Ze;q.Roles=ir;q.DataRetention=rr;q.SpendLimit=ur;q.SpendAlerts=ar;q.Certificates=tr;var dr=class extends u{create(e,t,r){return this._client.post(i`/organization/users/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{user_id:n}=t;return this._client.get(i`/organization/users/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/users/${e}/roles`,B,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{user_id:n}=t;return this._client.delete(i`/organization/users/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var rt=class extends u{constructor(){super(...arguments),this.roles=new dr(this._client)}retrieve(e,t){return this._client.get(i`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/users/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/users",O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};rt.Roles=dr;var H=class extends u{constructor(){super(...arguments),this.auditLogs=new qt(this._client),this.adminAPIKeys=new zt(this._client),this.usage=new Qt(this._client),this.invites=new Jt(this._client),this.users=new rt(this._client),this.groups=new Te(this._client),this.roles=new Vt(this._client),this.dataRetention=new Wt(this._client),this.spendLimit=new Gt(this._client),this.spendAlerts=new Xt(this._client),this.certificates=new Ht(this._client),this.projects=new q(this._client)}};H.AuditLogs=qt;H.AdminAPIKeys=zt;H.Usage=Qt;H.Invites=Jt;H.Users=rt;H.Groups=Te;H.Roles=Vt;H.DataRetention=Wt;H.SpendLimit=Gt;H.SpendAlerts=Xt;H.Certificates=Ht;H.Projects=q;var je=class extends u{constructor(){super(...arguments),this.organization=new H(this._client)}};je.Organization=H;var fr=class extends u{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:h([{Accept:"application/octet-stream"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var hr=class extends u{create(e,t){return this._client.post("/audio/transcriptions",Q({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var mr=class extends u{create(e,t){return this._client.post("/audio/translations",Q({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var he=class extends u{constructor(){super(...arguments),this.transcriptions=new hr(this._client),this.translations=new mr(this._client),this.speech=new fr(this._client)}};he.Transcriptions=hr;he.Translations=mr;he.Speech=fr;var st=class extends u{create(e,t){return this._client.post("/batches",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/batches",C,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}};var _r=class extends u{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/assistants/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/assistants",C,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var yr=class extends u{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var gr=class extends u{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var Ne=class extends u{constructor(){super(...arguments),this.sessions=new yr(this._client),this.transcriptionSessions=new gr(this._client)}};Ne.Sessions=yr;Ne.TranscriptionSessions=gr;var Ar=class extends u{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/chatkit/sessions/${e}/cancel`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}};var br=class extends u{retrieve(e,t){return this._client.get(i`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chatkit/threads",O,{query:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},r){return this._client.getAPIList(i`/chatkit/threads/${e}/items`,O,{query:t,...r,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var Fe=class extends u{constructor(){super(...arguments),this.sessions=new Ar(this._client),this.threads=new br(this._client)}};Fe.Sessions=Ar;Fe.Threads=br;var Ir=class extends u{list(e,t={},r){let{betas:n,...o}=t??{};return this._client.getAPIList(i`/responses/${e}/input_items?beta=true`,C,{query:o,...r,headers:h([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}};var wr=class extends u{count(e={},t){let{betas:r,...n}=e??{};return this._client.post("/responses/input_tokens?beta=true",{body:n,...t,headers:h([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}};var Le=class extends u{constructor(){super(...arguments),this.inputItems=new Ir(this._client),this.inputTokens=new wr(this._client)}create(e,t){let{betas:r,...n}=e;return this._client.post("/responses?beta=true",{body:n,...t,headers:h([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t={},r){let{betas:n,...o}=t??{};return this._client.get(i`/responses/${e}?beta=true`,{query:o,...r,headers:h([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})}delete(e,t={},r){let{betas:n}=t??{};return this._client.delete(i`/responses/${e}?beta=true`,{...r,headers:h([{Accept:"*/*",...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t={},r){let{betas:n}=t??{};return this._client.post(i`/responses/${e}/cancel?beta=true`,{...r,headers:h([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}compact(e,t){let{betas:r,...n}=e;return this._client.post("/responses/compact?beta=true",{body:n,...t,headers:h([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}};Le.InputItems=Ir;Le.InputTokens=wr;var Pr=class extends u{create(e,t,r){return this._client.post(i`/threads/${e}/messages`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(i`/threads/${n}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(i`/threads/${n}/messages/${e}`,{body:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/threads/${e}/messages`,C,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){let{thread_id:n}=t;return this._client.delete(i`/threads/${n}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var xr=class extends u{retrieve(e,t,r){let{thread_id:n,run_id:o,...a}=t;return this._client.get(i`/threads/${n}/runs/${o}/steps/${e}`,{query:a,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t,r){let{thread_id:n,...o}=t;return this._client.getAPIList(i`/threads/${n}/runs/${e}/steps`,C,{query:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Ho=s=>{if(typeof Buffer<"u"){let e=Buffer.from(s,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(s),t=e.length,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);return Array.from(new Float32Array(r.buffer))}};var ue=s=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[s]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(s)?.trim()||void 0};var V,ot,Dn,me,zs,ce,it,Rr,nt,Ws,se,qs,Hs,ms,fs,hs,Wo,Jo,Vo,Xo,Go,Qo,Yo,we=class extends Ee{constructor(){super(...arguments),V.add(this),Dn.set(this,[]),me.set(this,{}),zs.set(this,{}),ce.set(this,void 0),it.set(this,void 0),Rr.set(this,void 0),nt.set(this,void 0),Ws.set(this,void 0),se.set(this,void 0),qs.set(this,void 0),Hs.set(this,void 0),ms.set(this,void 0)}[(Dn=new WeakMap,me=new WeakMap,zs=new WeakMap,ce=new WeakMap,it=new WeakMap,Rr=new WeakMap,nt=new WeakMap,Ws=new WeakMap,se=new WeakMap,qs=new WeakMap,Hs=new WeakMap,ms=new WeakMap,V=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=structuredClone(n),a=t.shift();a?a.resolve(o):e.push(o)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new ot;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let r=Z.fromReadableStream(e,this.controller);for await(let n of r)c(this,V,"m",fs).call(this,n);if(r.controller.signal?.aborted)throw new M;return this._addRun(c(this,V,"m",hs).call(this))}toReadableStream(){return new Z(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n){let o=new ot;return o._run(()=>o._runToolAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,n){this._listenForAbort(n?.signal);let o={...r,stream:!0},a=await e.submitToolOutputs(t,o,{...n,signal:this.controller.signal});this._connected();for await(let l of a)c(this,V,"m",fs).call(this,l);if(a.controller.signal?.aborted)throw new M;return this._addRun(c(this,V,"m",hs).call(this))}static createThreadAssistantStream(e,t,r){let n=new ot;return n._run(()=>n._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,r,n){let o=new ot;return o._run(()=>o._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return c(this,qs,"f")}currentRun(){return c(this,Hs,"f")}currentMessageSnapshot(){return c(this,ce,"f")}currentRunStepSnapshot(){return c(this,ms,"f")}async finalRunSteps(){return await this.done(),Object.values(c(this,me,"f"))}async finalMessages(){return await this.done(),Object.values(c(this,zs,"f"))}async finalRun(){if(await this.done(),!c(this,it,"f"))throw Error("Final run was not received.");return c(this,it,"f")}async _createThreadAssistantStream(e,t,r){this._listenForAbort(r?.signal);let n={...t,stream:!0},o=await e.createAndRun(n,{...r,signal:this.controller.signal});this._connected();for await(let a of o)c(this,V,"m",fs).call(this,a);if(o.controller.signal?.aborted)throw new M;return this._addRun(c(this,V,"m",hs).call(this))}async _createAssistantStream(e,t,r,n){this._listenForAbort(n?.signal);let o={...r,stream:!0},a=await e.create(t,o,{...n,signal:this.controller.signal});this._connected();for await(let l of a)c(this,V,"m",fs).call(this,l);if(a.controller.signal?.aborted)throw new M;return this._addRun(c(this,V,"m",hs).call(this))}static accumulateDelta(e,t){for(let[r,n]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=n;continue}let o=e[r];if(o==null){e[r]=n;continue}if(r==="index"||r==="type"){e[r]=n;continue}if(typeof o=="string"&&typeof n=="string")o+=n;else if(typeof o=="number"&&typeof n=="number")o+=n;else if(Vr(o)&&Vr(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(a=>typeof a=="string"||typeof a=="number")){o.push(...n);continue}for(let a of n){if(!Vr(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);let l=a.index;if(l==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);let f=o[l];f==null?o[l]=a:o[l]=this.accumulateDelta(f,a)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${n}, accValue: ${o}`);e[r]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n){return await this._createToolAssistantStream(t,e,r,n)}};ot=we,fs=function(e){if(!this.ended)switch(x(this,qs,e,"f"),c(this,V,"m",Vo).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":c(this,V,"m",Yo).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":c(this,V,"m",Jo).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":c(this,V,"m",Wo).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},hs=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");if(!c(this,it,"f"))throw Error("Final run has not been received");return c(this,it,"f")},Wo=function(e){let[t,r]=c(this,V,"m",Go).call(this,e,c(this,ce,"f"));x(this,ce,t,"f"),c(this,zs,"f")[t.id]=t;for(let n of r){let o=t.content[n.index];o?.type=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,a=t.content[n.index];if(a&&a.type=="text")this._emit("textDelta",o,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=c(this,Rr,"f")){if(c(this,nt,"f"))switch(c(this,nt,"f").type){case"text":this._emit("textDone",c(this,nt,"f").text,c(this,ce,"f"));break;case"image_file":this._emit("imageFileDone",c(this,nt,"f").image_file,c(this,ce,"f"));break}x(this,Rr,n.index,"f")}x(this,nt,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(c(this,Rr,"f")!==void 0){let n=e.data.content[c(this,Rr,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,c(this,ce,"f"));break;case"text":this._emit("textDone",n.text,c(this,ce,"f"));break}}c(this,ce,"f")&&this._emit("messageDone",e.data),x(this,ce,void 0,"f")}},Jo=function(e){let t=c(this,V,"m",Xo).call(this,e);switch(x(this,ms,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of r.step_details.tool_calls)o.index==c(this,Ws,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(c(this,se,"f")&&this._emit("toolCallDone",c(this,se,"f")),x(this,Ws,o.index,"f"),x(this,se,t.step_details.tool_calls[o.index],"f"),c(this,se,"f")&&this._emit("toolCallCreated",c(this,se,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":x(this,ms,void 0,"f"),e.data.step_details.type=="tool_calls"&&c(this,se,"f")&&(this._emit("toolCallDone",c(this,se,"f")),x(this,se,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},Vo=function(e){c(this,Dn,"f").push(e),this._emit("event",e)},Xo=function(e){switch(e.event){case"thread.run.step.created":return c(this,me,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=c(this,me,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let n=ot.accumulateDelta(t,r.delta);c(this,me,"f")[e.data.id]=n}return c(this,me,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":c(this,me,"f")[e.data.id]=e.data;break}if(c(this,me,"f")[e.data.id])return c(this,me,"f")[e.data.id];throw new Error("No snapshot available")},Go=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in t.content){let a=t.content[o.index];t.content[o.index]=c(this,V,"m",Qo).call(this,o,a)}else t.content[o.index]=o,r.push(o);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Qo=function(e,t){return ot.accumulateDelta(t,e)},Yo=function(e){switch(x(this,Hs,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":x(this,it,e.data,"f"),c(this,se,"f")&&(this._emit("toolCallDone",c(this,se,"f")),x(this,se,void 0,"f"));break;case"thread.run.cancelling":break}};var at=class extends u{constructor(){super(...arguments),this.steps=new xr(this._client)}create(e,t,r){let{include:n,...o}=t;return this._client.post(i`/threads/${e}/runs`,{query:{include:n},body:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(i`/threads/${n}/runs/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(i`/threads/${n}/runs/${e}`,{body:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/threads/${e}/runs`,C,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,r){let{thread_id:n}=t;return this._client.post(i`/threads/${n}/runs/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(n.id,{thread_id:e},r)}createAndStream(e,t,r){return we.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let n=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:a}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let f=a.headers.get("openai-poll-after-ms");if(f){let p=parseInt(f);isNaN(p)||(l=p)}}await de(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return we.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:n,...o}=t;return this._client.post(i`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,r){let n=await this.submitToolOutputs(e,t,r);return await this.poll(n.id,t,r)}submitToolOutputsStream(e,t,r){return we.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};at.Steps=xr;var Me=class extends u{constructor(){super(...arguments),this.runs=new at(this._client),this.messages=new Pr(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/threads/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return we.createThreadAssistantStream(e,this._client.beta.threads,t)}};Me.Runs=at;Me.Messages=Pr;var oe=class extends u{constructor(){super(...arguments),this.realtime=new Ne(this._client),this.responses=new Le(this._client),this.chatkit=new Fe(this._client),this.assistants=new _r(this._client),this.threads=new Me(this._client)}};oe.Realtime=Ne;oe.Responses=Le;oe.ChatKit=Fe;oe.Assistants=_r;oe.Threads=Me;var ut=class extends u{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var Sr=class extends u{retrieve(e,t,r){let{container_id:n}=t;return this._client.get(i`/containers/${n}/files/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var ct=class extends u{constructor(){super(...arguments),this.content=new Sr(this._client)}create(e,t,r){return this._client.post(i`/containers/${e}/files`,$e({body:t,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,r){let{container_id:n}=t;return this._client.get(i`/containers/${n}/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/containers/${e}/files`,C,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{container_id:n}=t;return this._client.delete(i`/containers/${n}/files/${e}`,{...r,headers:h([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};ct.Content=Sr;var Ke=class extends u{constructor(){super(...arguments),this.files=new ct(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/containers",C,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/containers/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}};Ke.Files=ct;var Cr=class extends u{create(e,t,r){let{include:n,...o}=t;return this._client.post(i`/conversations/${e}/items`,{query:{include:n},body:o,...r,__security:{bearerAuth:!0}})}retrieve(e,t,r){let{conversation_id:n,...o}=t;return this._client.get(i`/conversations/${n}/items/${e}`,{query:o,...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/conversations/${e}/items`,O,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{conversation_id:n}=t;return this._client.delete(i`/conversations/${n}/items/${e}`,{...r,__security:{bearerAuth:!0}})}};var Be=class extends u{constructor(){super(...arguments),this.items=new Cr(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/conversations/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};Be.Items=Cr;var lt=class extends u{create(e,t){let r=!!e.encoding_format,n=r?e.encoding_format:"base64";r&&K(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t,__security:{bearerAuth:!0}});return r?o:(K(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(a=>(a&&a.data&&a.data.forEach(l=>{let f=l.embedding;l.embedding=Ho(f)}),a)))}};var kr=class extends u{retrieve(e,t,r){let{eval_id:n,run_id:o}=t;return this._client.get(i`/evals/${n}/runs/${o}/output_items/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t,r){let{eval_id:n,...o}=t;return this._client.getAPIList(i`/evals/${n}/runs/${e}/output_items`,C,{query:o,...r,__security:{bearerAuth:!0}})}};var pt=class extends u{constructor(){super(...arguments),this.outputItems=new kr(this._client)}create(e,t,r){return this._client.post(i`/evals/${e}/runs`,{body:t,...r,__security:{bearerAuth:!0}})}retrieve(e,t,r){let{eval_id:n}=t;return this._client.get(i`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/evals/${e}/runs`,C,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{eval_id:n}=t;return this._client.delete(i`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}cancel(e,t,r){let{eval_id:n}=t;return this._client.post(i`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}};pt.OutputItems=kr;var Ue=class extends u{constructor(){super(...arguments),this.runs=new pt(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/evals/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/evals",C,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};Ue.Runs=pt;var dt=class extends u{create(e,t){return this._client.post("/files",Q({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(i`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/files",C,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(i`/files/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=1800*1e3}={}){let n=new Set(["processed","error","deleted"]),o=Date.now(),a=await this.retrieve(e);for(;!a.status||!n.has(a.status);)if(await de(t),a=await this.retrieve(e),Date.now()-o>r)throw new Ce({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return a}};var $r=class extends u{};var Er=class extends u{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}})}};var ft=class extends u{constructor(){super(...arguments),this.graders=new Er(this._client)}};ft.Graders=Er;var Or=class extends u{create(e,t,r){return this._client.getAPIList(i`/fine_tuning/checkpoints/${e}/permissions`,G,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},r){return this._client.get(i`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/fine_tuning/checkpoints/${e}/permissions`,O,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{fine_tuned_model_checkpoint:n}=t;return this._client.delete(i`/fine_tuning/checkpoints/${n}/permissions/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var ht=class extends u{constructor(){super(...arguments),this.permissions=new Or(this._client)}};ht.Permissions=Or;var vr=class extends u{list(e,t={},r){return this._client.getAPIList(i`/fine_tuning/jobs/${e}/checkpoints`,C,{query:t,...r,__security:{bearerAuth:!0}})}};var mt=class extends u{constructor(){super(...arguments),this.checkpoints=new vr(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(i`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",C,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},r){return this._client.getAPIList(i`/fine_tuning/jobs/${e}/events`,C,{query:t,...r,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(i`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(i`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}};mt.Checkpoints=vr;var le=class extends u{constructor(){super(...arguments),this.methods=new $r(this._client),this.jobs=new mt(this._client),this.checkpoints=new ht(this._client),this.alpha=new ft(this._client)}};le.Methods=$r;le.Jobs=mt;le.Checkpoints=ht;le.Alpha=ft;var Tr=class extends u{};var De=class extends u{constructor(){super(...arguments),this.graderModels=new Tr(this._client)}};De.GraderModels=Tr;var _t=class extends u{createVariation(e,t){return this._client.post("/images/variations",Q({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post("/images/edits",Q({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}})}};var yt=class extends u{retrieve(e,t){return this._client.get(i`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",G,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/models/${e}`,{...t,__security:{bearerAuth:!0}})}};var gt=class extends u{create(e,t){return this._client.post("/moderations",{body:e,...t,__security:{bearerAuth:!0}})}};var jr=class extends u{accept(e,t,r){return this._client.post(i`/realtime/calls/${e}/accept`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(i`/realtime/calls/${e}/hangup`,{...t,headers:h([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,r){return this._client.post(i`/realtime/calls/${e}/refer`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},r){return this._client.post(i`/realtime/calls/${e}/reject`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};var Nr=class extends u{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t,__security:{bearerAuth:!0}})}};var Pe=class extends u{constructor(){super(...arguments),this.clientSecrets=new Nr(this._client),this.calls=new jr(this._client)}};Pe.ClientSecrets=Nr;Pe.Calls=jr;function Zo(s,e){if(!e||!mu(e)){let t={...s,output_parsed:null,output:s.output.map(r=>r.type==="function_call"?{...r,parsed_arguments:null}:r.type==="message"?{...r,content:r.content.map(n=>({...n,parsed:null}))}:r)};return ti(s,t)&&ne(t),t}return zn(s,e)}function zn(s,e){let t=!s.status||s.status==="completed",r=s.output.map(o=>{if(o.type==="function_call")return t?yu(e,o):{...o,parsed_arguments:null};if(o.type==="message"){let a=o.content.map(l=>l.type==="output_text"?{...l,parsed:t?hu(e,l.text):null}:l);return{...o,content:a}}return o}),n=Object.assign({},s,{output:r});return ti(s,n)&&ne(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let o of n.output)if(o.type==="message"){for(let a of o.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function hu(s,e){return s.text?.format?.type!=="json_schema"?null:"$parseRaw"in s.text?.format?(s.text?.format).$parseRaw(e):JSON.parse(e)}function mu(s){return rs(s.text?.format)?!0:Array.isArray(s.tools)&&s.tools.some(e=>ei(e)||e.type==="function"&&e.strict===!0)}function ei(s){return s?.$brand==="auto-parseable-tool"}function _u(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function yu(s,e){let t=_u(s.tools??[],e.name);return{...e,...e,parsed_arguments:ei(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function ti(s,e){return!Object.getOwnPropertyDescriptor(s,"output_text")||e.output_text==null}function ne(s){let e=[];for(let t of s.output)if(t.type==="message")for(let r of t.content)r.type==="output_text"&&e.push(r.text);s.output_text=e.join("")}function si(s,e){if(!e){if(s.type!=="response.created")throw new g(`When snapshot hasn't been set yet, expected 'response.created' event, got ${s.type}`);return ri(s.response)}switch(s.type){case"response.output_item.added":{e.output.push(structuredClone(s.item)),s.item.type==="message"&&ne(e);break}case"response.output_item.done":{E(e,s.output_index),e.output[s.output_index]=structuredClone(s.item),s.item.type==="message"&&ne(e);break}case"response.content_part.added":{let t=E(e,s.output_index),r=t.type,n=s.part;r==="message"&&n.type!=="reasoning_text"?(t.content.push(structuredClone(n)),n.type==="output_text"&&ne(e)):r==="reasoning"&&n.type==="reasoning_text"&&(t.content||(t.content=[]),t.content.push(structuredClone(n)));break}case"response.content_part.done":{let t=E(e,s.output_index),r=s.part;if(t.type==="message"&&r.type!=="reasoning_text")ie(t.content,s.content_index),t.content[s.content_index]=structuredClone(r),r.type==="output_text"&&ne(e);else if(t.type==="reasoning"&&r.type==="reasoning_text"){let n=t.content;if(!n)throw new g(`missing content at index ${s.content_index}`);ie(n,s.content_index),n[s.content_index]=structuredClone(r)}break}case"response.output_text.delta":{let t=E(e,s.output_index);if(t.type==="message"){let r=ie(t.content,s.content_index);if(r.type!=="output_text")throw new g(`expected content to be 'output_text', got ${r.type}`);r.text+=s.delta,e.output_text+=s.delta}break}case"response.output_text.done":{let t=E(e,s.output_index);if(t.type==="message"){let r=ie(t.content,s.content_index);if(r.type!=="output_text")throw new g(`expected content to be 'output_text', got ${r.type}`);r.text=s.text,ne(e)}break}case"response.output_text.annotation.added":{let t=E(e,s.output_index);if(t.type==="message"){let r=ie(t.content,s.content_index);if(r.type!=="output_text")throw new g(`expected content to be 'output_text', got ${r.type}`);r.annotations[s.annotation_index]=structuredClone(s.annotation)}break}case"response.refusal.delta":{let t=E(e,s.output_index);if(t.type==="message"){let r=ie(t.content,s.content_index);if(r.type!=="refusal")throw new g(`expected content to be 'refusal', got ${r.type}`);r.refusal+=s.delta}break}case"response.refusal.done":{let t=E(e,s.output_index);if(t.type==="message"){let r=ie(t.content,s.content_index);if(r.type!=="refusal")throw new g(`expected content to be 'refusal', got ${r.type}`);r.refusal=s.refusal}break}case"response.function_call_arguments.delta":{let t=E(e,s.output_index);t.type==="function_call"&&(t.arguments+=s.delta);break}case"response.function_call_arguments.done":{let t=E(e,s.output_index);t.type==="function_call"&&(t.arguments=s.arguments);break}case"response.reasoning_text.delta":{let t=E(e,s.output_index);if(t.type==="reasoning"){if(!t.content)throw new g(`missing content at index ${s.content_index}`);let r=ie(t.content,s.content_index);if(r.type!=="reasoning_text")throw new g(`expected content to be 'reasoning_text', got ${r.type}`);r.text+=s.delta}break}case"response.reasoning_text.done":{let t=E(e,s.output_index);if(t.type==="reasoning"){if(!t.content)throw new g(`missing content at index ${s.content_index}`);let r=ie(t.content,s.content_index);if(r.type!=="reasoning_text")throw new g(`expected content to be 'reasoning_text', got ${r.type}`);r.text=s.text}break}case"response.reasoning_summary_part.added":{let t=E(e,s.output_index);t.type==="reasoning"&&t.summary.push(structuredClone(s.part));break}case"response.reasoning_summary_part.done":{let t=E(e,s.output_index);t.type==="reasoning"&&(ie(t.summary,s.summary_index),t.summary[s.summary_index]=structuredClone(s.part));break}case"response.reasoning_summary_text.delta":{let t=E(e,s.output_index);if(t.type==="reasoning"){let r=ie(t.summary,s.summary_index);r.text+=s.delta}break}case"response.reasoning_summary_text.done":{let t=E(e,s.output_index);if(t.type==="reasoning"){let r=ie(t.summary,s.summary_index);r.text=s.text}break}case"response.custom_tool_call_input.delta":{let t=E(e,s.output_index);t.type==="custom_tool_call"&&(t.input+=s.delta);break}case"response.custom_tool_call_input.done":{let t=E(e,s.output_index);t.type==="custom_tool_call"&&(t.input=s.input);break}case"response.mcp_call_arguments.delta":{let t=E(e,s.output_index);t.type==="mcp_call"&&(t.arguments+=s.delta);break}case"response.mcp_call_arguments.done":{let t=E(e,s.output_index);t.type==="mcp_call"&&(t.arguments=s.arguments);break}case"response.code_interpreter_call_code.delta":{let t=E(e,s.output_index);t.type==="code_interpreter_call"&&(t.code=(t.code??"")+s.delta);break}case"response.code_interpreter_call_code.done":{let t=E(e,s.output_index);t.type==="code_interpreter_call"&&(t.code=s.code);break}case"response.code_interpreter_call.in_progress":{let t=E(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="in_progress");break}case"response.code_interpreter_call.interpreting":{let t=E(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="interpreting");break}case"response.code_interpreter_call.completed":{let t=E(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="completed");break}case"response.file_search_call.in_progress":{let t=E(e,s.output_index);t.type==="file_search_call"&&(t.status="in_progress");break}case"response.file_search_call.searching":{let t=E(e,s.output_index);t.type==="file_search_call"&&(t.status="searching");break}case"response.file_search_call.completed":{let t=E(e,s.output_index);t.type==="file_search_call"&&(t.status="completed");break}case"response.web_search_call.in_progress":{let t=E(e,s.output_index);t.type==="web_search_call"&&(t.status="in_progress");break}case"response.web_search_call.searching":{let t=E(e,s.output_index);t.type==="web_search_call"&&(t.status="searching");break}case"response.web_search_call.completed":{let t=E(e,s.output_index);t.type==="web_search_call"&&(t.status="completed");break}case"response.image_generation_call.in_progress":{let t=E(e,s.output_index);t.type==="image_generation_call"&&(t.status="in_progress");break}case"response.image_generation_call.generating":{let t=E(e,s.output_index);t.type==="image_generation_call"&&(t.status="generating");break}case"response.image_generation_call.completed":{let t=E(e,s.output_index);t.type==="image_generation_call"&&(t.status="completed");break}case"response.mcp_call.in_progress":{let t=E(e,s.output_index);t.type==="mcp_call"&&(t.status="in_progress");break}case"response.mcp_call.completed":{let t=E(e,s.output_index);t.type==="mcp_call"&&(t.status="completed");break}case"response.mcp_call.failed":{let t=E(e,s.output_index);t.type==="mcp_call"&&(t.status="failed");break}case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":{e=ri(s.response);break}case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.image_generation_call.partial_image":case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":case"keepalive":case"error":break;default:gu(s)}return e}function ri(s){let e=structuredClone(s);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&ne(e),e}function E(s,e){let t=s.output[e];if(!t)throw new g(`missing output at index ${e}`);return t}function ie(s,e){let t=s[e];if(!t)throw new g(`missing content at index ${e}`);return t}function gu(s){throw new g(`Unhandled response stream event: ${JSON.stringify(s)}`)}var ze,Js,At,Vs,qn,Hn,Wn,Xs=class s extends Ee{constructor(e){super(),ze.add(this),Js.set(this,void 0),At.set(this,void 0),Vs.set(this,void 0),x(this,Js,e,"f")}static createResponse(e,t,r){let n=new s(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}async _createOrRetrieveResponse(e,t,r){this._listenForAbort(r?.signal),c(this,ze,"m",qn).call(this);let n,o=null;"response_id"in t?(n=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=t.starting_after??null):n=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let a of n)c(this,ze,"m",Hn).call(this,a,o);if(n.controller.signal?.aborted)throw new M;return c(this,ze,"m",Wn).call(this)}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),c(this,ze,"m",qn).call(this),this._connected();let r=Z.fromReadableStream(e,this.controller);for await(let n of r)c(this,ze,"m",Hn).call(this,n,null);if(r.controller.signal?.aborted)throw new M;return c(this,ze,"m",Wn).call(this)}[(Js=new WeakMap,At=new WeakMap,Vs=new WeakMap,ze=new WeakSet,qn=function(){this.ended||x(this,At,void 0,"f")},Hn=function(t,r){if(this.ended)return;let n=(a,l)=>{(r==null||l.sequence_number>r)&&this._emit(a,l)},o=si(t,c(this,At,"f"));switch(x(this,At,o,"f"),n("event",t),t.type){case"response.output_text.delta":{let a=o.output[t.output_index];if(!a)throw new g(`missing output at index ${t.output_index}`);if(a.type==="message"){let l=a.content[t.content_index];if(!l)throw new g(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new g(`expected content to be 'output_text', got ${l.type}`);n("response.output_text.delta",{...t,snapshot:l.text})}break}case"response.function_call_arguments.delta":{let a=o.output[t.output_index];if(!a)throw new g(`missing output at index ${t.output_index}`);a.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:a.arguments});break}default:n(t.type,t);break}},Wn=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");let t=c(this,At,"f");if(!t)throw new g("request ended without sending any events");x(this,At,void 0,"f");let r=Au(t,c(this,Js,"f"));return x(this,Vs,r,"f"),r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=c(this,Vs,"f");if(!e)throw new g("stream ended without producing a ChatCompletion");return e}};function Au(s,e){return Zo(s,e)}var Fr=class extends u{list(e,t={},r){return this._client.getAPIList(i`/responses/${e}/input_items`,C,{query:t,...r,__security:{bearerAuth:!0}})}};var Lr=class extends u{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t,__security:{bearerAuth:!0}})}};var _e=class extends u{constructor(){super(...arguments),this.inputItems=new Fr(this._client),this.inputTokens=new Lr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(r=>("object"in r&&r.object==="response"&&ne(r),r))}retrieve(e,t={},r){return this._client.get(i`/responses/${e}`,{query:t,...r,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&ne(n),n))}delete(e,t){return this._client.delete(i`/responses/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>zn(r,e))}stream(e,t){return Xs.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(i`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post("/responses/compact",{body:e,...t,__security:{bearerAuth:!0}})}};_e.InputItems=Fr;_e.InputTokens=Lr;var Mr=class extends u{retrieve(e,t){return this._client.get(i`/skills/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Kr=class extends u{retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(i`/skills/${n}/versions/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var bt=class extends u{constructor(){super(...arguments),this.content=new Kr(this._client)}create(e,t={},r){return this._client.post(i`/skills/${e}/versions`,$e({body:t,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(i`/skills/${n}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/skills/${e}/versions`,C,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{skill_id:n}=t;return this._client.delete(i`/skills/${n}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}};bt.Content=Kr;var xe=class extends u{constructor(){super(...arguments),this.content=new Mr(this._client),this.versions=new bt(this._client)}create(e={},t){return this._client.post("/skills",$e({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(i`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/skills/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/skills",C,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};xe.Content=Mr;xe.Versions=bt;var Br=class extends u{create(e,t,r){return this._client.post(i`/uploads/${e}/parts`,Q({body:t,...r,__security:{bearerAuth:!0}},this._client))}};var qe=class extends u{constructor(){super(...arguments),this.parts=new Br(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,r){return this._client.post(i`/uploads/${e}/complete`,{body:t,...r,__security:{bearerAuth:!0}})}};qe.Parts=Br;var ni=async s=>{let e=await Promise.allSettled(s),t=e.filter(n=>n.status==="rejected");if(t.length){for(let n of t)console.error(n.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let r=[];for(let n of e)n.status==="fulfilled"&&r.push(n.value);return r};var Ur=class extends u{create(e,t,r){return this._client.post(i`/vector_stores/${e}/file_batches`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(i`/vector_stores/${n}/file_batches/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,r){let{vector_store_id:n}=t;return this._client.post(i`/vector_stores/${n}/file_batches/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){let n=await this.create(e,t);return await this.poll(e,n.id,r)}listFiles(e,t,r){let{vector_store_id:n,...o}=t;return this._client.getAPIList(i`/vector_stores/${n}/file_batches/${e}/files`,C,{query:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,r){let n=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:a}=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse();switch(o.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let f=a.headers.get("openai-poll-after-ms");if(f){let p=parseInt(f);isNaN(p)||(l=p)}}await de(l);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},n){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=n?.maxConcurrency??5,a=Math.min(o,t.length),l=this._client,f=t.values(),p=[...r];async function _(d){for(let b of d){let w=await l.files.create({file:b,purpose:"assistants"},n);p.push(w.id)}}let m=Array(a).fill(f).map(_);return await ni(m),await this.createAndPoll(e,{file_ids:p})}};var Dr=class extends u{create(e,t,r){return this._client.post(i`/vector_stores/${e}/files`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(i`/vector_stores/${n}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{vector_store_id:n,...o}=t;return this._client.post(i`/vector_stores/${n}/files/${e}`,{body:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/vector_stores/${e}/files`,C,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){let{vector_store_id:n}=t;return this._client.delete(i`/vector_stores/${n}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){let n=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse(),a=o.data;switch(a.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let f=o.response.headers.get("openai-poll-after-ms");if(f){let p=parseInt(f);isNaN(p)||(l=p)}}await de(l);break;case"failed":case"completed":return a}}}async upload(e,t,r){let n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){let n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}content(e,t,r){let{vector_store_id:n}=t;return this._client.getAPIList(i`/vector_stores/${n}/files/${e}/content`,G,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Re=class extends u{constructor(){super(...arguments),this.files=new Dr(this._client),this.fileBatches=new Ur(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/vector_stores/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vector_stores",C,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,r){return this._client.getAPIList(i`/vector_stores/${e}/search`,G,{body:t,method:"post",...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};Re.Files=Dr;Re.FileBatches=Ur;var It=class extends u{create(e,t){return this._client.post("/videos",Q({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(i`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/videos",O,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post("/videos/characters",Q({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},r){return this._client.get(i`/videos/${e}/content`,{query:t,...r,headers:h([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post("/videos/edits",Q({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post("/videos/extensions",Q({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(i`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,r){return this._client.post(i`/videos/${e}/remix`,$e({body:t,...r,__security:{bearerAuth:!0}},this._client))}};var zr,oi,Gs,wt=class extends u{constructor(){super(...arguments),zr.add(this)}async unwrap(e,t,r=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,r,n),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,n=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");c(this,zr,"m",oi).call(this,r);let o=h([t]).values,a=c(this,zr,"m",Gs).call(this,o,"webhook-signature"),l=c(this,zr,"m",Gs).call(this,o,"webhook-timestamp"),f=c(this,zr,"m",Gs).call(this,o,"webhook-id"),p=parseInt(l,10);if(isNaN(p))throw new pe("Invalid webhook timestamp format");let _=Math.floor(Date.now()/1e3);if(_-p>n)throw new pe("Webhook timestamp is too old");if(p>_+n)throw new pe("Webhook timestamp is too new");let m=a.split(" ").map(A=>A.startsWith("v1,")?A.substring(3):A),d=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),b=f?`${f}.${l}.${e}`:`${l}.${e}`,w=await crypto.subtle.importKey("raw",d,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let A of m)try{let I=Buffer.from(A,"base64");if(await crypto.subtle.verify("HMAC",w,I,new TextEncoder().encode(b)))return}catch{continue}throw new pe("The given webhook signature does not match the expected signature")}};zr=new WeakSet,oi=function(e){if(typeof e!="string"||e.length===0)throw new 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")},Gs=function(e,t){if(!e)throw new Error("Headers are required");let r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var ai=Symbol.for("openai.node.providerDefinitions.v1"),ui=globalThis,ci=ui[ai],li=ci??new WeakMap;ci||Object.defineProperty(ui,ai,{value:li});function pi(s){let e=li.get(s);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var Jn,Vn,_s,di,ku="workload-identity-auth",S=class{constructor(e={}){Jn.add(this),_s.set(this,void 0),this.completions=new ut(this),this.chat=new ve(this),this.embeddings=new lt(this),this.files=new dt(this),this.images=new _t(this),this.audio=new he(this),this.moderations=new gt(this),this.models=new yt(this),this.fineTuning=new le(this),this.graders=new De(this),this.vectorStores=new Re(this),this.webhooks=new wt(this),this.beta=new oe(this),this.batches=new st(this),this.uploads=new qe(this),this.admin=new je(this),this.responses=new _e(this),this.realtime=new Pe(this),this.conversations=new Be(this),this.evals=new Ue(this),this.containers=new Ke(this),this.skills=new xe(this),this.videos=new It(this);let t=e.provider;if(t){let A=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(I=>e[I]!=null);if(A.length)throw new g(`The \`provider\` option cannot be used with ${A.map(I=>`\`${I}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:r=t?null:ue("OPENAI_BASE_URL"),apiKey:n=t?null:ue("OPENAI_API_KEY")??null,adminAPIKey:o=t?null:ue("OPENAI_ADMIN_KEY")??null,organization:a=t?null:ue("OPENAI_ORG_ID")??null,project:l=t?null:ue("OPENAI_PROJECT_ID")??null,webhookSecret:f=ue("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:p,..._}=e,m=t?pi(t):void 0,d={apiKey:n,adminAPIKey:o,organization:a,project:l,webhookSecret:f,workloadIdentity:p,provider:t,..._,baseURL:m?.baseURL??(r||"https://api.openai.com/v1")};if(n&&p)throw new g("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!m&&!n&&!o&&!p)throw new g("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!d.dangerouslyAllowBrowser&&ao())throw new g(`It looks like you're running in a browser-like environment.
25
25
 
26
26
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
27
27
  If you understand the risks and have appropriate mitigations in place,
@@ -30,5 +30,5 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
30
30
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
31
31
 
32
32
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
33
- `);this.baseURL=d.baseURL,this.timeout=d.timeout??Wn.DEFAULT_TIMEOUT,this.logger=d.logger??console;let b="warn";this.logLevel=b,this.logLevel=mn(d.logLevel,"ClientOptions.logLevel",this)??mn(ue("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??b,this.fetchOptions=d.fetchOptions,this.maxRetries=d.maxRetries??2,this.fetch=d.fetch??bs(),x(this,hs,co,"f");let I=t?void 0:ue("OPENAI_CUSTOM_HEADERS");if(I){let A={};for(let w of I.split(`
34
- `)){let k=w.indexOf(":");k>=0&&(A[w.substring(0,k).trim()]=w.substring(k+1).trim())}d.defaultHeaders=h([A,d.defaultHeaders])}this._options=d,this._provider=f,p&&(this._workloadIdentityAuth=new Cs(p,this.fetch)),this.apiKey=typeof n=="string"?n:null,this.adminAPIKey=o,this.organization=a,this.project=l,this.webhookSecret=m}withOptions(e){let t=this._options.provider,r=e.provider??t,n={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return r&&(delete n.apiKey,delete n.adminAPIKey,delete n.workloadIdentity,delete n.baseURL,r!==t&&(delete n.organization,delete n.project,delete n.defaultHeaders)),new this.constructor({...n,...e,provider:r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},r={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(t.has("authorization")||t.has("api-key"))&&!(this._workloadIdentityAuth&&r.bearerAuth))throw new 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 h([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return h([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return h([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return h([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Ao(e)}getUserAgent(){return`${this.constructor.name}/JS ${ke}`}defaultIdempotencyKey(){return`stainless-node-retry-${He()}`}makeStatusError(e,t,r,n){return F.generate(e,t,r,n)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(r){throw r instanceof g?r:new g(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!="string"||!t)throw new g(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let n=!c(this,Hn,"m",pi).call(this)&&r||this.baseURL,o=Zn(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),l=Object.fromEntries(o.searchParams);return(!rn(a)||!rn(l))&&(t={...l,...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){if(this._provider)return;(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}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,r){return this.request(Promise.resolve(r).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new Ve(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let n=await e,o=n.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(n);let{req:a,url:l,timeout:m}=await this.buildRequest(n,{retryCount:o-t}),p=n.__metadata?.hasStreamingBody===!0;await this.prepareRequest(a,{url:l,options:n}),await this._provider?.prepareRequest?.(a,{url:l,options:n});let _="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),f=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(K(this).debug(`[${_}] sending request`,ye({retryOfRequestLogID:r,method:n.method,url:l,options:n,headers:a.headers})),n.signal?.aborted)throw new M;let b=n.__security??{bearerAuth:!0},I=new AbortController,A=await this.fetchWithAuth(l,a,m,I,b).catch(qr),w=Date.now();if(A instanceof globalThis.Error){let P=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new M;let R=zr(A)||/timed? ?out/i.test(String(A)+("cause"in A?String(A.cause):""));if(t&&!p)return K(this).info(`[${_}] connection ${R?"timed out":"failed"} - ${P}`),K(this).debug(`[${_}] connection ${R?"timed out":"failed"} (${P})`,ye({retryOfRequestLogID:r,url:l,durationMs:w-d,message:A.message})),this.retryRequest(n,t,r??_);let v=p?"error; streaming body cannot be retried":"error; no more retries left";throw K(this).info(`[${_}] connection ${R?"timed out":"failed"} - ${v}`),K(this).debug(`[${_}] connection ${R?"timed out":"failed"} (${v})`,ye({retryOfRequestLogID:r,url:l,durationMs:w-d,message:A.message})),A instanceof We||A instanceof Hr?A:R?new Ce:new Se({message:ku(A),cause:A})}let k=[...A.headers.entries()].filter(([P])=>P==="x-request-id").map(([P,R])=>", "+P+": "+JSON.stringify(R)).join(""),y=`[${_}${f}${k}] ${a.method} ${l} ${A.ok?"succeeded":"failed"} with status ${A.status} in ${w-d}ms`;if(!A.ok){if(A.status===401&&this._workloadIdentityAuth&&b.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await nn(A.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},t,r??_);let P=await this.shouldRetry(A);if(t&&P&&!p){let N=`retrying, ${t} attempts remaining`;return await nn(A.body),K(this).info(`${y} - ${N}`),K(this).debug(`[${_}] response error (${N})`,ye({retryOfRequestLogID:r,url:A.url,status:A.status,headers:A.headers,durationMs:w-d})),this.retryRequest(n,t,r??_,A.headers)}let R=P?p?"error; streaming body cannot be retried":"error; no more retries left":"error; not retryable";K(this).info(`${y} - ${R}`);let v=await A.text().catch(N=>qr(N).message),$=ro(v),L=$?void 0:v;throw K(this).debug(`[${_}] response error (${R})`,ye({retryOfRequestLogID:r,url:A.url,status:A.status,headers:A.headers,message:L,durationMs:Date.now()-d})),this.makeStatusError(A.status,$,L,A.headers)}return K(this).info(y),K(this).debug(`[${_}] response start`,ye({retryOfRequestLogID:r,url:A.url,status:A.status,headers:A.headers,durationMs:w-d})),{response:A,options:n,controller:I,requestLogID:_,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new Qr(this,r,e)}async fetchWithAuth(e,t,r,n,o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&o.bearerAuth){let l=t.headers,m=l.get("Authorization");if(!m||m===`Bearer ${Cu}`){let p=await this._workloadIdentityAuth.getToken();l.set("Authorization",`Bearer ${p}`)}}return await this.fetchWithTimeout(e,t,r,n)}async fetchWithTimeout(e,t,r,n){let{signal:o,method:a,...l}=t||{},m=this._makeAbort(n);o&&o.addEventListener("abort",m,{once:!0});let p=setTimeout(m,r),_=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,f={signal:n.signal,..._?{duplex:"half"}:{},method:"GET",...l};a&&(f.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,f)}finally{clearTimeout(p)}}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,r,n){let o,a=n?.get("retry-after-ms");if(a){let m=parseFloat(a);Number.isNaN(m)||(o=m)}let l=n?.get("retry-after");if(l&&!o){let m=parseFloat(l);Number.isNaN(m)?o=Date.parse(l)-Date.now():o=m*1e3}if(o===void 0){let m=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,m)}return await de(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,a=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return a*l*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:n,path:o,query:a,defaultBaseURL:l}=r,m=this.buildURL(o,a,l);"timeout"in r&&to("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:p,body:_,isStreamingBody:f}=this.buildBody({options:r});f&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let d=await this.buildHeaders({options:e,method:n,bodyHeaders:p,retryCount:t});return{req:{method:n,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:"half"},..._&&{body:_},...this.fetchOptions??{},...r.fetchOptions??{}},url:m,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let a=h([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ao(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,r,e.headers]);return this._provider||this.validateHeaders(a,e.__security??{bearerAuth:!0}),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:r}=e;if(!t)return t===void 0&&"body"in e?{...c(this,hs,"f").call(this,{body:t,headers:h([r])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=h([r]),o=typeof globalThis.ReadableStream<"u"&&t instanceof globalThis.ReadableStream,a=!o&&(typeof t=="string"||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof globalThis.Blob<"u"&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||o?{bodyHeaders:void 0,body:t,isStreamingBody:!a}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:Jr(t),isStreamingBody:!0}:typeof t=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(t),isStreamingBody:!1}:{...c(this,hs,"f").call(this,{body:t,headers:n}),isStreamingBody:!1}}};Wn=S,hs=new WeakMap,Hn=new WeakSet,pi=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};S.OpenAI=Wn;S.DEFAULT_TIMEOUT=6e5;S.OpenAIError=g;S.APIError=F;S.APIConnectionError=Se;S.APIConnectionTimeoutError=Ce;S.APIUserAbortError=M;S.NotFoundError=St;S.ConflictError=Ct;S.RateLimitError=$t;S.BadRequestError=Pt;S.AuthenticationError=xt;S.InternalServerError=Et;S.PermissionDeniedError=Rt;S.UnprocessableEntityError=kt;S.InvalidWebhookSignatureError=pe;S.toFile=Os;S.toStreamingFile=$s;S.Completions=at;S.Chat=ve;S.Embeddings=ct;S.Files=pt;S.Images=ft;S.Audio=he;S.Moderations=yt;S.Models=_t;S.FineTuning=le;S.Graders=De;S.VectorStores=Re;S.Webhooks=wt;S.Beta=oe;S.Batches=rt;S.Uploads=qe;S.Admin=je;S.Responses=_e;S.Realtime=Pe;S.Conversations=Ue;S.Evals=Be;S.Containers=Ke;S.Skills=xe;S.Videos=bt;function ku(s){if($u(s))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 $u(s){let e=s;for(let t=0;t<8&&e&&typeof e=="object";t++){let r=e;if(r.code==="UND_ERR_INVALID_ARG"&&typeof r.message=="string"&&r.message.includes("invalid onRequestStart method"))return!0;e=r.cause}return!1}var Vs=Jn({module:"llm"});var di=class{client;model;systemPrompt;maxOutputTokens;constructor(e,t){let r=en(e);if(!r)throw new gs("OpenAI API key not found, set OPENAI_API_KEY in .swifty/config.y(a)ml, or via OPENAI_API_KEY env variable.");this.client=new S({apiKey:r,baseURL:e.base_url}),this.model=e.model,this.systemPrompt=t,this.maxOutputTokens=Zs(e)}async*stream(e,t,r){let n=Eu(Gs(e.getMessages())),o=[];o.push({role:"system",content:this.systemPrompt});for(let d of n)o.push(d);let a=t.map(d=>{let b=d.input_schema;return{type:"function",name:d.name,description:d.description,parameters:b,strict:!1}}),l={model:this.model,input:o,stream:!0,max_output_tokens:this.maxOutputTokens,...a.length>0?{tools:a}:{}},m=0,p=0,_=0,f=0;try{let d=await this.client.responses.create(l,{...r?{signal:r}:{}}),b="",I="",A="",w="",k="";for await(let y of d)if(y.type==="response.output_text.delta")yield{type:"text_delta",text:y.delta};else if(y.type==="response.reasoning_summary_text.delta")k+=y.delta,yield{type:"thinking_delta",text:y.delta};else if(y.type==="response.reasoning_summary_text.done")yield{type:"thinking_complete",thinking:k,signature:w};else if(y.type==="response.function_call_arguments.delta")A+=y.delta,yield{type:"tool_call_delta",text:y.delta};else if(y.type==="response.output_item.added")y.item.type==="function_call"?(b=y.item.name,I=y.item.call_id,A="",yield{type:"tool_call_start",toolName:b,toolId:I}):y.item.type==="reasoning"&&(w=y.item.id??"",k="");else if(y.type==="response.output_item.done"){if(y.item.type==="function_call"&&b){let P={};if(A)try{let R=JSON.parse(A);P=Qs(R)?ys(R):{[Dr]:A}}catch(R){Vs.error({err:R},"llm operation failed"),P={[Dr]:A}}yield{type:"tool_call_complete",toolId:I,toolName:b,arguments:P},b="",I="",A=""}}else if(y.type==="response.completed"){let P=y.response.usage;P&&(p=P.output_tokens,_=P.input_tokens_details.cached_tokens,m=Math.max(0,P.input_tokens-_));let R="end_turn",v=y.response;v.status==="incomplete"&&v.incomplete_details?.reason==="max_output_tokens"&&(R="max_tokens"),yield{type:"stream_end",stopReason:R,usage:{inputTokens:m,outputTokens:p,cacheReadInputTokens:_,cacheCreationInputTokens:f}}}}catch(d){throw Vs.error({err:d},"llm operation failed"),hi(d)}}setSystemPrompt(e){this.systemPrompt=e}setMaxOutputTokens(e){this.maxOutputTokens=e}};function Xs(s){return`data:${s.mediaType};base64,${s.data}`}function Eu(s){let e=[];for(let t of s){if(t.thinkingBlocks)for(let r of t.thinkingBlocks)e.push({type:"reasoning",id:r.signature,summary:[{type:"summary_text",text:r.thinking}]});if(t.toolUses&&t.toolUses.length>0){t.content&&e.push({role:"assistant",content:t.content});for(let r of t.toolUses)e.push({type:"function_call",name:r.toolName,call_id:r.toolUseId,arguments:JSON.stringify(r.arguments)})}else if(t.toolResults&&t.toolResults.length>0){let r=[];for(let n of t.toolResults)if(e.push({type:"function_call_output",call_id:n.toolUseId,output:n.content}),n.images?.length){r.push({type:"input_text",text:`[Image(s) returned by tool call ${n.toolUseId}]`});for(let o of n.images)r.push({type:"input_image",image_url:Xs(o),detail:"auto"})}r.length>0&&e.push({role:"user",content:r})}else t.role==="user"&&t.images?.length?e.push({role:"user",content:[{type:"input_text",text:t.content},...t.images.map(r=>({type:"input_image",image_url:Xs(r),detail:"auto"}))]}):e.push({role:t.role,content:t.content})}return e}function Ou(s){return/context_length_exceeded/i.test(s)||/maximum\scontext\slength/i.test(s)||/prompts?\s+too\s+long/i.test(s)}function TA(s){let e=[];for(let t of s)if(t.toolUses&&t.toolUses.length>0)e.push({role:"assistant",content:t.content||null,tool_calls:t.toolUses.map(r=>({id:r.toolUseId,type:"function",function:{name:r.toolName,arguments:JSON.stringify(r.arguments)}}))});else if(t.toolResults&&t.toolResults.length>0)for(let r of t.toolResults)e.push({role:"tool",tool_call_id:r.toolUseId,content:r.content});else t.role==="assistant"?e.push({role:"assistant",content:t.content}):e.push({role:t.role==="system"?"system":"user",content:t.content});return e}var mi=class{client;model;systemPrompt;maxOutputTokens;constructor(e,t){let r=en(e);if(!r)throw new gs("OpenAI API key not found. Set OPENAI_API_KEY in .swifty/config.y(a)ml, or via OPENAI_API_KEY env variable.");this.client=new S({apiKey:r,baseURL:e.base_url}),this.model=e.model,this.systemPrompt=t,this.maxOutputTokens=Zs(e)}setSystemPrompt(e){this.systemPrompt=e}setMaxOutputTokens(e){this.maxOutputTokens=e}async*stream(e,t,r){let n=[{role:"system",content:this.systemPrompt},...vu(Gs(e.getMessages()))],o=t.map(f=>({type:"function",function:{name:f.name,description:f.description,arguments:f.input_schema}})),a={model:this.model,messages:n,stream:!0,stream_options:{include_usage:!0},max_tokens:this.maxOutputTokens,...o.length>0?{tools:o}:{}},l=0,m=0,p=0,_=0;try{let f=await this.client.chat.completions.create(a,{...r?{signal:r}:{}}),d=new Map,b=null,I="";for await(let w of f){if(w.usage&&(m=w.usage.completion_tokens??0,p=w.usage.prompt_tokens_details?.cached_tokens??0,l=Math.max(0,(w.usage.prompt_tokens??0)-p)),w.choices.length===0)continue;let k=w.choices[0].delta;k.content&&(yield{type:"text_delta",text:k.content});let y=Vn(ys(k),"reasoning_content");if(y&&(I+=y,yield{type:"thinking_delta",text:y}),k.tool_calls)for(let P of k.tool_calls){d.has(P.index)||(d.set(P.index,{id:P.id??"",name:P.function?.name??"",args:""}),P.id&&(yield{type:"tool_call_start",toolName:P.function?.name??"",toolId:P.id??""}));let R=d.get(P.index);R&&(P.id&&(R.id=P.id),P.function?.name&&(R.name=P.function.name),P.function?.arguments&&(R.args+=P.function.arguments,yield{type:"tool_call_delta",text:P.function.arguments}))}if(w.choices[0].finish_reason){b=w.choices[0].finish_reason,I&&(yield{type:"thinking_complete",thinking:I,signature:""},I="");for(let P of d.values()){let R={},v=P.args;if(v){try{let $=JSON.parse(v);R=Qs($)?ys($):{[Dr]:v}}catch($){Vs.error({err:$},"llm operation failed"),R={[Dr]:v}}yield{type:"tool_call_complete",toolName:P.name,toolId:P.id,arguments:R}}}}}let A;b==="length"?A="max_tokens":b==="tool_calls"||d.size>0?A="tool_use":A="end_turn",yield{type:"stream_end",stopReason:A,usage:{inputTokens:l,outputTokens:m,cacheReadInputTokens:p,cacheCreationInputTokens:_}}}catch(f){throw Vs.error({err:f},"llm operation failed"),hi(f)}}};function hi(s){return s instanceof S.APIError?s.status===413||s.status===400&&Ou(s.message)?new Yn(`Context Too Long: ${s.message}`):s.status===401?new gs(`Invalid API key: ${s.message}`):s.status===429?new Gn("Rate limit error, please wait."):new Xn(`OpenAI API error (${Ys(s.status)}): ${s.message}`):new Qn(`Network error: ${s instanceof Error?s.message:Ys(s)}`)}function vu(s){let e=[];for(let t of s){let r=t.thinkingBlocks?.map(n=>n.thinking).join("")??"";if(t.toolUses&&t.toolUses.length>0)e.push({role:"assistant",content:t.content||null,tool_calls:t.toolUses.map(n=>({id:n.toolUseId,type:"function",function:{name:n.toolName,arguments:JSON.stringify(n.arguments)},...r?{reasoning_content:r}:{}}))});else if(t.toolResults&&t.toolResults.length>0){let n=[];for(let o of t.toolResults)if(e.push({role:"tool",tool_call_id:o.toolUseId,content:o.content}),o.images?.length){n.push({type:"text",text:`[Image(s) returned by tool call ${o.toolUseId}]`});for(let a of o.images)n.push({type:"image_url",image_url:{url:Xs(a)}})}n.length>0&&e.push({role:"user",content:n})}else t.role==="assistant"?e.push({role:"assistant",content:t.content,...r?{reasoning_content:r}:{}}):t.role==="user"&&t.images?.length?e.push({role:"user",content:[{type:"text",text:t.content},...t.images.map(n=>({type:"image_url",image_url:{url:Xs(n)}}))]}):e.push({role:t.role==="system"?"system":"user",content:t.content})}return e}export{di as OpenAIClient,mi as OpenAICompatClient,TA as buildChatCompletionMessage,vu as buildChatCompletionMessages,Eu as buildOpenAIInput};
33
+ `);this.baseURL=d.baseURL,this.timeout=d.timeout??Vn.DEFAULT_TIMEOUT,this.logger=d.logger??console;let b="warn";this.logLevel=b,this.logLevel=mn(d.logLevel,"ClientOptions.logLevel",this)??mn(ue("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??b,this.fetchOptions=d.fetchOptions,this.maxRetries=d.maxRetries??2,this.fetch=d.fetch??Ps(),x(this,_s,lo,"f");let w=t?void 0:ue("OPENAI_CUSTOM_HEADERS");if(w){let A={};for(let I of w.split(`
34
+ `)){let k=I.indexOf(":");k>=0&&(A[I.substring(0,k).trim()]=I.substring(k+1).trim())}d.defaultHeaders=h([A,d.defaultHeaders])}this._options=d,this._provider=m,p&&(this._workloadIdentityAuth=new Es(p,this.fetch)),this.apiKey=typeof n=="string"?n:null,this.adminAPIKey=o,this.organization=a,this.project=l,this.webhookSecret=f}withOptions(e){let t=this._options.provider,r=e.provider??t,n={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return r&&(delete n.apiKey,delete n.adminAPIKey,delete n.workloadIdentity,delete n.baseURL,r!==t&&(delete n.organization,delete n.project,delete n.defaultHeaders)),new this.constructor({...n,...e,provider:r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},r={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(t.has("authorization")||t.has("api-key"))&&!(this._workloadIdentityAuth&&r.bearerAuth))throw new 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 h([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return h([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return h([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return h([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return bo(e)}getUserAgent(){return`${this.constructor.name}/JS ${ke}`}defaultIdempotencyKey(){return`stainless-node-retry-${We()}`}makeStatusError(e,t,r,n){return F.generate(e,t,r,n)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(r){throw r instanceof g?r:new g(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!="string"||!t)throw new g(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let n=!c(this,Jn,"m",di).call(this)&&r||this.baseURL,o=eo(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),l=Object.fromEntries(o.searchParams);return(!nn(a)||!nn(l))&&(t={...l,...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){if(this._provider)return;(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}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,r){return this.request(Promise.resolve(r).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new Xe(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let n=await e,o=n.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(n);let{req:a,url:l,timeout:f}=await this.buildRequest(n,{retryCount:o-t}),p=n.__metadata?.hasStreamingBody===!0;await this.prepareRequest(a,{url:l,options:n}),await this._provider?.prepareRequest?.(a,{url:l,options:n});let _="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(K(this).debug(`[${_}] sending request`,ye({retryOfRequestLogID:r,method:n.method,url:l,options:n,headers:a.headers})),n.signal?.aborted)throw new M;let b=n.__security??{bearerAuth:!0},w=new AbortController,A=await this.fetchWithAuth(l,a,f,w,b).catch(Wr),I=Date.now();if(A instanceof globalThis.Error){let P=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new M;let R=Hr(A)||/timed? ?out/i.test(String(A)+("cause"in A?String(A.cause):""));if(t&&!p)return K(this).info(`[${_}] connection ${R?"timed out":"failed"} - ${P}`),K(this).debug(`[${_}] connection ${R?"timed out":"failed"} (${P})`,ye({retryOfRequestLogID:r,url:l,durationMs:I-d,message:A.message})),this.retryRequest(n,t,r??_);let v=p?"error; streaming body cannot be retried":"error; no more retries left";throw K(this).info(`[${_}] connection ${R?"timed out":"failed"} - ${v}`),K(this).debug(`[${_}] connection ${R?"timed out":"failed"} (${v})`,ye({retryOfRequestLogID:r,url:l,durationMs:I-d,message:A.message})),A instanceof Je||A instanceof Jr?A:R?new Ce:new Se({message:$u(A),cause:A})}let k=[...A.headers.entries()].filter(([P])=>P==="x-request-id").map(([P,R])=>", "+P+": "+JSON.stringify(R)).join(""),y=`[${_}${m}${k}] ${a.method} ${l} ${A.ok?"succeeded":"failed"} with status ${A.status} in ${I-d}ms`;if(!A.ok){if(A.status===401&&this._workloadIdentityAuth&&b.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await an(A.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},t,r??_);let P=await this.shouldRetry(A);if(t&&P&&!p){let N=`retrying, ${t} attempts remaining`;return await an(A.body),K(this).info(`${y} - ${N}`),K(this).debug(`[${_}] response error (${N})`,ye({retryOfRequestLogID:r,url:A.url,status:A.status,headers:A.headers,durationMs:I-d})),this.retryRequest(n,t,r??_,A.headers)}let R=P?p?"error; streaming body cannot be retried":"error; no more retries left":"error; not retryable";K(this).info(`${y} - ${R}`);let v=await A.text().catch(N=>Wr(N).message),$=so(v),L=$?void 0:v;throw K(this).debug(`[${_}] response error (${R})`,ye({retryOfRequestLogID:r,url:A.url,status:A.status,headers:A.headers,message:L,durationMs:Date.now()-d})),this.makeStatusError(A.status,$,L,A.headers)}return K(this).info(y),K(this).debug(`[${_}] response start`,ye({retryOfRequestLogID:r,url:A.url,status:A.status,headers:A.headers,durationMs:I-d})),{response:A,options:n,controller:w,requestLogID:_,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new Zr(this,r,e)}async fetchWithAuth(e,t,r,n,o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&o.bearerAuth){let l=t.headers,f=l.get("Authorization");if(!f||f===`Bearer ${ku}`){let p=await this._workloadIdentityAuth.getToken();l.set("Authorization",`Bearer ${p}`)}}return await this.fetchWithTimeout(e,t,r,n)}async fetchWithTimeout(e,t,r,n){let{signal:o,method:a,...l}=t||{},f=this._makeAbort(n);o&&o.addEventListener("abort",f,{once:!0});let p=setTimeout(f,r),_=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,m={signal:n.signal,..._?{duplex:"half"}:{},method:"GET",...l};a&&(m.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(p)}}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,r,n){let o,a=n?.get("retry-after-ms");if(a){let f=parseFloat(a);Number.isNaN(f)||(o=f)}let l=n?.get("retry-after");if(l&&!o){let f=parseFloat(l);Number.isNaN(f)?o=Date.parse(l)-Date.now():o=f*1e3}if(o===void 0){let f=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,f)}return await de(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,a=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return a*l*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:n,path:o,query:a,defaultBaseURL:l}=r,f=this.buildURL(o,a,l);"timeout"in r&&ro("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:p,body:_,isStreamingBody:m}=this.buildBody({options:r});m&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let d=await this.buildHeaders({options:e,method:n,bodyHeaders:p,retryCount:t});return{req:{method:n,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:"half"},..._&&{body:_},...this.fetchOptions??{},...r.fetchOptions??{}},url:f,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let a=h([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...uo(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,r,e.headers]);return this._provider||this.validateHeaders(a,e.__security??{bearerAuth:!0}),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:r}=e;if(!t)return t===void 0&&"body"in e?{...c(this,_s,"f").call(this,{body:t,headers:h([r])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=h([r]),o=typeof globalThis.ReadableStream<"u"&&t instanceof globalThis.ReadableStream,a=!o&&(typeof t=="string"||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof globalThis.Blob<"u"&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||o?{bodyHeaders:void 0,body:t,isStreamingBody:!a}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:Xr(t),isStreamingBody:!0}:typeof t=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(t),isStreamingBody:!1}:{...c(this,_s,"f").call(this,{body:t,headers:n}),isStreamingBody:!1}}};Vn=S,_s=new WeakMap,Jn=new WeakSet,di=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};S.OpenAI=Vn;S.DEFAULT_TIMEOUT=6e5;S.OpenAIError=g;S.APIError=F;S.APIConnectionError=Se;S.APIConnectionTimeoutError=Ce;S.APIUserAbortError=M;S.NotFoundError=kt;S.ConflictError=$t;S.RateLimitError=Ot;S.BadRequestError=Rt;S.AuthenticationError=St;S.InternalServerError=vt;S.PermissionDeniedError=Ct;S.UnprocessableEntityError=Et;S.InvalidWebhookSignatureError=pe;S.toFile=js;S.toStreamingFile=vs;S.Completions=ut;S.Chat=ve;S.Embeddings=lt;S.Files=dt;S.Images=_t;S.Audio=he;S.Moderations=gt;S.Models=yt;S.FineTuning=le;S.Graders=De;S.VectorStores=Re;S.Webhooks=wt;S.Beta=oe;S.Batches=st;S.Uploads=qe;S.Admin=je;S.Responses=_e;S.Realtime=Pe;S.Conversations=Be;S.Evals=Ue;S.Containers=Ke;S.Skills=xe;S.Videos=It;function $u(s){if(Eu(s))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 Eu(s){let e=s;for(let t=0;t<8&&e&&typeof e=="object";t++){let r=e;if(r.code==="UND_ERR_INVALID_ARG"&&typeof r.message=="string"&&r.message.includes("invalid onRequestStart method"))return!0;e=r.cause}return!1}var Qs=Xn({module:"llm"});var fi=class{client;model;systemPrompt;maxOutputTokens;constructor(e,t){let r=rn(e);if(!r)throw new Is("OpenAI API key not found, set OPENAI_API_KEY in .swifty/config.y(a)ml, or via OPENAI_API_KEY env variable.");this.client=new S({apiKey:r,baseURL:e.base_url}),this.model=e.model,this.systemPrompt=t,this.maxOutputTokens=tn(e)}async*stream(e,t,r){let n=Nu(Zs(e.getMessages())),o=[];o.push({role:"system",content:this.systemPrompt});for(let d of n)o.push(d);let a=t.map(d=>{let b=d.input_schema;return{type:"function",name:d.name,description:d.description,parameters:b,strict:!1}}),l={model:this.model,input:o,stream:!0,max_output_tokens:this.maxOutputTokens,...a.length>0?{tools:a}:{}},f=0,p=0,_=0,m=0;try{let d=await this.client.responses.create(l,{...r?{signal:r}:{}}),b="",w="",A="",I="",k="";for await(let y of d)if(y.type==="response.output_text.delta")yield{type:"text_delta",text:y.delta};else if(y.type==="response.reasoning_summary_text.delta")k+=y.delta,yield{type:"thinking_delta",text:y.delta};else if(y.type==="response.reasoning_summary_text.done")yield{type:"thinking_complete",thinking:k,signature:I};else if(y.type==="response.function_call_arguments.delta")A+=y.delta,yield{type:"tool_call_delta",text:y.delta};else if(y.type==="response.output_item.added")y.item.type==="function_call"?(b=y.item.name,w=y.item.call_id,A="",yield{type:"tool_call_start",toolName:b,toolId:w}):y.item.type==="reasoning"&&(I=y.item.id??"",k="");else if(y.type==="response.output_item.done"){if(y.item.type==="function_call"&&b){let P={};if(A)try{let R=JSON.parse(A);P=As(R)?bs(R):{[qr]:A}}catch(R){Qs.error({err:R},"llm operation failed"),P={[qr]:A}}yield{type:"tool_call_complete",toolId:w,toolName:b,arguments:P},b="",w="",A=""}}else if(y.type==="response.completed"){let P=y.response.usage;P&&(p=P.output_tokens,_=P.input_tokens_details.cached_tokens,f=Math.max(0,P.input_tokens-_));let R="end_turn",v=y.response;v.status==="incomplete"&&v.incomplete_details?.reason==="max_output_tokens"&&(R="max_tokens"),yield{type:"stream_end",stopReason:R,usage:{inputTokens:f,outputTokens:p,cacheReadInputTokens:_,cacheCreationInputTokens:m}}}}catch(d){throw Qs.error({err:d},"llm operation failed"),mi(d)}}setSystemPrompt(e){this.systemPrompt=e}setMaxOutputTokens(e){this.maxOutputTokens=e}};function Ys(s){if(s.type!=="image")return null;let e=s.source;if(!As(e)||e.type!=="base64")return null;let t=xt(e,"media_type"),r=xt(e,"data");return!t||!r?null:`data:${t};base64,${r}`}function Ou(s){let{toolUseId:e,content:t}=s;if(typeof t=="string")return[];let r=[];for(let n of t){let o=Ys(n);o&&r.push({type:"input_image",image_url:o,detail:"auto"})}return r.length===0?[]:[{type:"input_text",text:`[Image(s) returned by tool call ${e}]`},...r]}function vu(s){let{toolUseId:e,content:t}=s;if(typeof t=="string")return[];let r=[];for(let n of t){let o=Ys(n);o&&r.push({type:"image_url",image_url:{url:o}})}return r.length===0?[]:[{type:"text",text:`[Image(s) returned by tool call ${e}]`},...r]}function Tu(s){if(typeof s=="string")return s;let e=[];for(let t of s)if(t.type==="text")e.push({type:"input_text",text:xt(t,"text")});else{let r=Ys(t);r&&e.push({type:"input_image",image_url:r,detail:"auto"})}return e}function ju(s){if(typeof s=="string")return s;let e=[];for(let t of s)if(t.type==="text")e.push({type:"text",text:xt(t,"text")});else{let r=Ys(t);r&&e.push({type:"image_url",image_url:{url:r}})}return e}function Nu(s){let e=[];for(let t of s){if(t.thinkingBlocks)for(let r of t.thinkingBlocks)e.push({type:"reasoning",id:r.signature,summary:[{type:"summary_text",text:r.thinking}]});if(t.toolUses&&t.toolUses.length>0){let r=typeof t.content=="string"?t.content:He(t.content);r&&e.push({role:"assistant",content:r});for(let n of t.toolUses)e.push({type:"function_call",name:n.toolName,call_id:n.toolUseId,arguments:JSON.stringify(n.arguments)})}else if(t.toolResults&&t.toolResults.length>0){let r=[];for(let n of t.toolResults)e.push({type:"function_call_output",call_id:n.toolUseId,output:He(n.content)}),r.push(...Ou(n));r.length>0&&e.push({role:"user",content:r})}else t.role==="assistant"?e.push({role:"assistant",content:typeof t.content=="string"?t.content:He(t.content)}):e.push({role:t.role,content:Tu(t.content)})}return e}function Fu(s){return/context_length_exceeded/i.test(s)||/maximum\scontext\slength/i.test(s)||/prompts?\s+too\s+long/i.test(s)}var hi=class{client;model;systemPrompt;maxOutputTokens;constructor(e,t){let r=rn(e);if(!r)throw new Is("OpenAI API key not found. Set OPENAI_API_KEY in .swifty/config.y(a)ml, or via OPENAI_API_KEY env variable.");this.client=new S({apiKey:r,baseURL:e.base_url}),this.model=e.model,this.systemPrompt=t,this.maxOutputTokens=tn(e)}setSystemPrompt(e){this.systemPrompt=e}setMaxOutputTokens(e){this.maxOutputTokens=e}async*stream(e,t,r){let n=[{role:"system",content:this.systemPrompt},...Lu(Zs(e.getMessages()))],o=t.map(m=>({type:"function",function:{name:m.name,description:m.description,arguments:m.input_schema}})),a={model:this.model,messages:n,stream:!0,stream_options:{include_usage:!0},max_tokens:this.maxOutputTokens,...o.length>0?{tools:o}:{}},l=0,f=0,p=0,_=0;try{let m=await this.client.chat.completions.create(a,{...r?{signal:r}:{}}),d=new Map,b=null,w="";for await(let I of m){if(I.usage&&(f=I.usage.completion_tokens??0,p=I.usage.prompt_tokens_details?.cached_tokens??0,l=Math.max(0,(I.usage.prompt_tokens??0)-p)),I.choices.length===0)continue;let k=I.choices[0].delta;k.content&&(yield{type:"text_delta",text:k.content});let y=xt(bs(k),"reasoning_content");if(y&&(w+=y,yield{type:"thinking_delta",text:y}),k.tool_calls)for(let P of k.tool_calls){d.has(P.index)||(d.set(P.index,{id:P.id??"",name:P.function?.name??"",args:""}),P.id&&(yield{type:"tool_call_start",toolName:P.function?.name??"",toolId:P.id??""}));let R=d.get(P.index);R&&(P.id&&(R.id=P.id),P.function?.name&&(R.name=P.function.name),P.function?.arguments&&(R.args+=P.function.arguments,yield{type:"tool_call_delta",text:P.function.arguments}))}if(I.choices[0].finish_reason){b=I.choices[0].finish_reason,w&&(yield{type:"thinking_complete",thinking:w,signature:""},w="");for(let P of d.values()){let R={},v=P.args;if(v){try{let $=JSON.parse(v);R=As($)?bs($):{[qr]:v}}catch($){Qs.error({err:$},"llm operation failed"),R={[qr]:v}}yield{type:"tool_call_complete",toolName:P.name,toolId:P.id,arguments:R}}}}}let A;b==="length"?A="max_tokens":b==="tool_calls"||d.size>0?A="tool_use":A="end_turn",yield{type:"stream_end",stopReason:A,usage:{inputTokens:l,outputTokens:f,cacheReadInputTokens:p,cacheCreationInputTokens:_}}}catch(m){throw Qs.error({err:m},"llm operation failed"),mi(m)}}};function mi(s){return s instanceof S.APIError?s.status===413||s.status===400&&Fu(s.message)?new Zn(`Context Too Long: ${s.message}`):s.status===401?new Is(`Invalid API key: ${s.message}`):s.status===429?new Qn("Rate limit error, please wait."):new Gn(`OpenAI API error (${en(s.status)}): ${s.message}`):new Yn(`Network error: ${s instanceof Error?s.message:en(s)}`)}function Lu(s){let e=[];for(let t of s){let r=t.thinkingBlocks?.map(o=>o.thinking).join("")??"",n=typeof t.content=="string"?t.content:He(t.content);if(t.toolUses&&t.toolUses.length>0)e.push({role:"assistant",content:n||null,tool_calls:t.toolUses.map(o=>({id:o.toolUseId,type:"function",function:{name:o.toolName,arguments:JSON.stringify(o.arguments)},...r?{reasoning_content:r}:{}}))});else if(t.toolResults&&t.toolResults.length>0){let o=[];for(let a of t.toolResults)e.push({role:"tool",tool_call_id:a.toolUseId,content:He(a.content)}),o.push(...vu(a));o.length>0&&e.push({role:"user",content:o})}else t.role==="assistant"?e.push({role:"assistant",content:n,...r?{reasoning_content:r}:{}}):t.role==="system"?e.push({role:"system",content:typeof t.content=="string"?t.content:He(t.content)}):e.push({role:"user",content:ju(t.content)})}return e}export{fi as OpenAIClient,hi as OpenAICompatClient,Lu as buildChatCompletionMessages,Nu as buildOpenAIInput};