@swifty.js/swifty 0.0.1 → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +183 -0
- package/dist/agent-MICFDGUF.js +4 -0
- package/dist/anthropic-JDAGNAPR.js +4 -0
- package/dist/checker-PF3FEOF2.js +4 -0
- package/dist/chunk-4KVSJNS6.js +90 -0
- package/dist/chunk-6ARDOHBL.js +4 -0
- package/dist/chunk-7MHXMDYC.js +35 -0
- package/dist/chunk-F6HLYUZ4.js +355 -0
- package/dist/chunk-FZPTNGTU.js +4 -0
- package/dist/chunk-LPLPMGWW.js +336 -0
- package/dist/chunk-MQ5XOYLD.js +4 -0
- package/dist/chunk-RD3MICOU.js +4 -0
- package/dist/{cleanup-4R3534Z3.js → cleanup-BQJDUOKA.js} +1 -1
- package/dist/glob_addon.node +0 -0
- package/dist/main.js +240 -240
- package/dist/openai-I4WTRNNT.js +26 -0
- package/dist/{server-XPKSROM2.js → server-OGPKL2U2.js} +22 -21
- package/package.json +17 -24
- package/dist/anthropic-737END4X.js +0 -4
- package/dist/chunk-NCPOPA4A.js +0 -4
- package/dist/chunk-SC34YHMX.js +0 -521
- package/dist/chunk-Z3E5YV3P.js +0 -121
- package/dist/openai-4KX74QBZ.js +0 -27
- package/docs/ch1.md +0 -25
- package/docs/ch10.md +0 -122
- package/docs/ch11.md +0 -163
- package/docs/ch12.md +0 -289
- package/docs/ch13.md +0 -320
- package/docs/ch14.md +0 -152
- package/docs/ch15.md +0 -547
- package/docs/ch2.md +0 -273
- package/docs/ch3.md +0 -206
- package/docs/ch4.md +0 -125
- package/docs/ch5.md +0 -165
- package/docs/ch6.md +0 -201
- package/docs/ch7.md +0 -448
- package/docs/ch8.md +0 -217
- package/docs/ch9.md +0 -351
- package/docs/index.css +0 -23
- package/docs/index.md +0 -21
- package/docs/swifty.mdx +0 -7
package/dist/openai-4KX74QBZ.js
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
|
-
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
-
import{N as kr,O as Os,P as Qr,Q as Ts,U as Pn,W as Rn,X as Zr,Y as Cn,Z as Sn,_ as kn,ba as Ns,ca as js,e as xn}from"./chunk-Z3E5YV3P.js";import"./chunk-NCPOPA4A.js";import"./chunk-X3UA5OZL.js";function P(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 u(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 Ls=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return Ls=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 $r(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}var Er=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{},N=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 Ie({message:r,cause:Er(t)});let o=t?.error;return e===400?new mt(e,o,r,n):e===401?new ft(e,o,r,n):e===403?new _t(e,o,r,n):e===404?new gt(e,o,r,n):e===409?new yt(e,o,r,n):e===422?new At(e,o,r,n):e===429?new bt(e,o,r,n):e>=500?new wt(e,o,r,n):new s(e,o,r,n)}},K=class extends N{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Ie=class extends N{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},xe=class extends Ie{constructor({message:e}={}){super({message:e??"Request timed out."})}},mt=class extends N{},ft=class extends N{},_t=class extends N{},gt=class extends N{},yt=class extends N{},At=class extends N{},bt=class extends N{},wt=class extends N{},It=class extends g{constructor(){super("Could not parse response content as the length limit was reached")}},xt=class extends g{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},ae=class extends Error{constructor(e){super(e)}},Fe=class extends N{constructor(e,t,r){let n="OAuth2 authentication error",o;if(t&&typeof t=="object"){let c=t;o=c.error;let l=c.error_description;l&&typeof l=="string"?n=l:o&&(n=o)}super(e,t,n,r),this.error_code=o}},vr=class extends g{constructor(e,t,r){super(e),this.provider=t,this.cause=r}};var Xo=/^[a-z][a-z0-9+.-]*:/i,$n=s=>Xo.test(s),X=s=>(X=Array.isArray,X(s)),Ms=X;function es(s){return typeof s!="object"?{}:s??{}}function Ks(s){if(!s)return!0;for(let e in s)return!1;return!0}function En(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function Or(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var vn=(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 On=s=>{try{return JSON.parse(s)}catch{return}};var ce=s=>new Promise(e=>setTimeout(e,s));var Pe="6.45.0";var Ln=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Go(){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 Vo=()=>{let s=Go();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Pe,"X-Stainless-OS":Nn(Deno.build.os),"X-Stainless-Arch":Tn(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":Pe,"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":Pe,"X-Stainless-OS":Nn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Tn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Yo();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Pe,"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":Pe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Yo(){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,c=r[3]||0;return{browser:e,version:`${n}.${o}.${c}`}}}return null}var Tn=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",Nn=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"),jn,Mn=()=>jn??(jn=Vo());function ts(){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 Fs(...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 rs(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return Fs({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function Us(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 Bs(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 Fn=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Ds="RFC3986",zs=s=>String(s),qs={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:zs},Un="RFC1738";var ss=(s,e)=>(ss=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),ss(s,e)),ue=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var Ws=1024,Bn=(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 c="";for(let l=0;l<o.length;l+=Ws){let m=o.length>=Ws?o.slice(l,l+Ws):o,p=[];for(let w=0;w<m.length;++w){let h=m.charCodeAt(w);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||n===Un&&(h===40||h===41)){p[p.length]=m.charAt(w);continue}if(h<128){p[p.length]=ue[h];continue}if(h<2048){p[p.length]=ue[192|h>>6]+ue[128|h&63];continue}if(h<55296||h>=57344){p[p.length]=ue[224|h>>12]+ue[128|h>>6&63]+ue[128|h&63];continue}w+=1,h=65536+((h&1023)<<10|m.charCodeAt(w)&1023),p[p.length]=ue[240|h>>18]+ue[128|h>>12&63]+ue[128|h>>6&63]+ue[128|h&63]}c+=p.join("")}return c};function Dn(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function Hs(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 qn={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},Wn=function(s,e){Array.prototype.push.apply(s,X(e)?e:[e])},zn,B={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Bn,encodeValuesOnly:!1,format:Ds,formatter:zs,indices:!1,serializeDate(s){return(zn??(zn=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function Zo(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var Js={};function Hn(s,e,t,r,n,o,c,l,m,p,w,h,f,b,y,A,I,k){let _=s,x=k,R=0,O=!1;for(;(x=x.get(Js))!==void 0&&!O;){let M=x.get(s);if(R+=1,typeof M<"u"){if(M===R)throw new RangeError("Cyclic object value");O=!0}typeof x.get(Js)>"u"&&(R=0)}if(typeof p=="function"?_=p(e,_):_ instanceof Date?_=f?.(_):t==="comma"&&X(_)&&(_=Hs(_,function(M){return M instanceof Date?f?.(M):M})),_===null){if(o)return m&&!A?m(e,B.encoder,I,"key",b):e;_=""}if(Zo(_)||Dn(_)){if(m){let M=A?e:m(e,B.encoder,I,"key",b);return[y?.(M)+"="+y?.(m(_,B.encoder,I,"value",b))]}return[y?.(e)+"="+y?.(String(_))]}let v=[];if(typeof _>"u")return v;let T;if(t==="comma"&&X(_))A&&m&&(_=Hs(_,m)),T=[{value:_.length>0?_.join(",")||null:void 0}];else if(X(p))T=p;else{let M=Object.keys(_);T=w?M.sort(w):M}let j=l?String(e).replace(/\./g,"%2E"):String(e),J=r&&X(_)&&_.length===1?j+"[]":j;if(n&&X(_)&&_.length===0)return J+"[]";for(let M=0;M<T.length;++M){let U=T[M],wn=typeof U=="object"&&typeof U.value<"u"?U.value:_[U];if(c&&wn===null)continue;let vs=h&&l?U.replace(/\./g,"%2E"):U,Ho=X(_)?typeof t=="function"?t(J,vs):J:J+(h?"."+vs:"["+vs+"]");k.set(s,R);let In=new WeakMap;In.set(Js,k),Wn(v,Hn(wn,Ho,t,r,n,o,c,l,t==="comma"&&A&&X(_)?null:m,p,w,h,f,b,y,A,I,In))}return v}function ei(s=B){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||B.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=Ds;if(typeof s.format<"u"){if(!ss(qs,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=qs[t],n=B.filter;(typeof s.filter=="function"||X(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in qn?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=B.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let c=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:B.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:B.addQueryPrefix,allowDots:c,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:B.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:B.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?B.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:B.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:B.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:B.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:B.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:B.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:B.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:B.strictNullHandling}}function Jn(s,e={}){let t=s,r=ei(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):X(r.filter)&&(o=r.filter,n=o);let c=[];if(typeof t!="object"||t===null)return"";let l=qn[r.arrayFormat],m=l==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let p=new WeakMap;for(let f=0;f<n.length;++f){let b=n[f];r.skipNulls&&t[b]===null||Wn(c,Hn(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 w=c.join(r.delimiter),h=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),w.length>0?h+w:""}function Xn(s){return Jn(s,{arrayFormat:"brackets"})}function Yn(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 Gn;function Pt(s){let e;return(Gn??(e=new globalThis.TextEncoder,Gn=e.encode.bind(e)))(s)}var Vn;function Xs(s){let e;return(Vn??(e=new globalThis.TextDecoder,Vn=e.decode.bind(e)))(s)}var Q,Z,Ue=class{constructor(){Q.set(this,void 0),Z.set(this,void 0),P(this,Q,new Uint8Array,"f"),P(this,Z,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Pt(e):e;P(this,Q,Yn([u(this,Q,"f"),t]),"f");let r=[],n;for(;(n=ri(u(this,Q,"f"),u(this,Z,"f")))!=null;){if(n.carriage&&u(this,Z,"f")==null){P(this,Z,n.index,"f");continue}if(u(this,Z,"f")!=null&&(n.index!==u(this,Z,"f")+1||n.carriage)){r.push(Xs(u(this,Q,"f").subarray(0,u(this,Z,"f")-1))),P(this,Q,u(this,Q,"f").subarray(u(this,Z,"f")),"f"),P(this,Z,null,"f");continue}let o=u(this,Z,"f")!==null?n.preceding-1:n.preceding,c=Xs(u(this,Q,"f").subarray(0,o));r.push(c),P(this,Q,u(this,Q,"f").subarray(n.index),"f"),P(this,Z,null,"f")}return r}flush(){return u(this,Q,"f").length?this.decode(`
|
|
5
|
-
`):[]}};Q=new WeakMap,Z=new WeakMap;Ue.NEWLINE_CHARS=new Set([`
|
|
6
|
-
`,"\r"]);Ue.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 Qn(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 os={off:0,error:200,warn:300,info:400,debug:500},Gs=(s,e,t)=>{if(s){if(En(os,s))return s;L(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(os))}`)}};function Tr(){}function ns(s,e,t){return!e||os[s]>os[t]?Tr:e[s].bind(e)}var si={error:Tr,warn:Tr,info:Tr,debug:Tr},Zn=new WeakMap;function L(s){let e=s.logger,t=s.logLevel??"off";if(!e)return si;let r=Zn.get(e);if(r&&r[0]===t)return r[1];let n={error:ns("error",e,t),warn:ns("warn",e,t),info:ns("info",e,t),debug:ns("debug",e,t)};return Zn.set(e,[t,n]),n}var me=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 Nr,le=class s{constructor(e,t,r){this.iterator=e,Nr.set(this,void 0),this.controller=t,P(this,Nr,r,"f")}static fromSSEResponse(e,t,r,n){let o=!1,c=r?L(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 ni(e,t))if(!m){if(p.data.startsWith("[DONE]")){m=!0;continue}if(p.event===null||!p.event.startsWith("thread.")){let w;try{w=JSON.parse(p.data)}catch(h){throw c.error("Could not parse message into JSON:",p.data),c.error("From chunk:",p.raw),h}if(w&&w.error)throw new N(void 0,w.error,void 0,e.headers);yield n?{event:p.event,data:w}:w}else{let w;try{w=JSON.parse(p.data)}catch(h){throw console.error("Could not parse message into JSON:",p.data),console.error("From chunk:",p.raw),h}if(p.event=="error")throw new N(void 0,w.error,w.message,void 0);yield{event:p.event,data:w}}}m=!0}catch(p){if($r(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 Ue,m=Us(e);for await(let p of m)for(let w of l.decode(p))yield w;for(let p of l.flush())yield p}async function*c(){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($r(m))return;throw m}finally{l||t.abort()}}return new s(c,t,r)}[(Nr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=o=>({next:()=>{if(o.length===0){let c=r.next();e.push(c),t.push(c)}return o.shift()}});return[new s(()=>n(e),this.controller,u(this,Nr,"f")),new s(()=>n(t),this.controller,u(this,Nr,"f"))]}toReadableStream(){let e=this,t;return Fs({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:n,done:o}=await t.next();if(o)return r.close();let c=Pt(JSON.stringify(n)+`
|
|
7
|
-
`);r.enqueue(c)}catch(n){r.error(n)}},async cancel(){await t.return?.()}})}};async function*ni(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 Vs,r=new Ue,n=Us(s.body);for await(let o of oi(n))for(let c of r.decode(o)){let l=t.decode(c);l&&(yield l)}for(let o of r.flush()){let c=t.decode(o);c&&(yield c)}}async function*oi(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"?Pt(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let o;for(;(o=Qn(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var Vs=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]=ii(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function ii(s,e){let t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}async function is(s,e){let{response:t,requestLogID:r,retryOfRequestLogID:n,startTime:o}=e,c=await(async()=>{if(e.options.stream)return L(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):le.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 f=await t.json();return Ys(f,t)}return await t.text()})();return L(s).debug(`[${r}] response parsed`,me({retryOfRequestLogID:n,url:t.url,status:t.status,body:c,durationMs:Date.now()-o})),c}function Ys(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 jr,Be=class s extends Promise{constructor(e,t,r=is){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=r,jr.set(this,void 0),P(this,jr,e,"f")}_thenUnwrap(e){return new s(u(this,jr,"f"),this.responsePromise,async(t,r)=>Ys(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(u(this,jr,"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)}};jr=new WeakMap;var as,Rt=class{constructor(e,t,r,n){as.set(this,void 0),P(this,as,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 u(this,as,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(as=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Lr=class extends Be{constructor(e,t,r){super(e,t,async(n,o)=>new r(n,o.response,await is(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},G=class extends Rt{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}},S=class extends Rt{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:{...es(this.options.query),after:t}}:null}},E=class extends Rt{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:{...es(this.options.query),after:e}}:null}},F=class extends Rt{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:{...es(this.options.query),after:e}}:null}};var ci={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},ui="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??ts()}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:ui,subject_token:e,subject_token_type:ci[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 Fe(r.status,p,r.headers):N.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,c=n.expires_in??3600,l=Date.now()+c*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 en=()=>{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 Ct(s,e,t){return en(),new File(s,e??"unknown_file",t)}function Mr(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 us=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",Re=async(s,e)=>Qs(s.body)?{...s,body:await to(s.body,e)}:s,V=async(s,e)=>({...s,body:await to(s.body,e)}),eo=new WeakMap;function li(s){let e=typeof s=="function"?s:s.fetch,t=eo.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 eo.set(e,r),r}var to=async(s,e)=>{if(!await li(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])=>Zs(t,r,n))),t},ro=s=>s instanceof Blob&&"name"in s,pi=s=>typeof s=="object"&&s!==null&&(s instanceof Response||us(s)||ro(s)),Qs=s=>{if(pi(s))return!0;if(Array.isArray(s))return s.some(Qs);if(s&&typeof s=="object"){for(let e in s)if(Qs(s[e]))return!0}return!1},Zs=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,Ct([await t.blob()],Mr(t)));else if(us(t))s.append(e,Ct([await new Response(rs(t)).blob()],Mr(t)));else if(ro(t))s.append(e,t,Mr(t));else if(Array.isArray(t))await Promise.all(t.map(r=>Zs(s,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,n])=>Zs(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 so=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",hi=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&so(s),di=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function ls(s,e,t){if(en(),s=await s,hi(s))return s instanceof File?s:Ct([await s.arrayBuffer()],s.name);if(di(s)){let n=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),Ct(await tn(n),e,t)}let r=await tn(s);if(e||(e=Mr(s)),!t?.type){let n=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(t={...t,type:n})}return Ct(r,e,t)}async function tn(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(so(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(us(s))for await(let t of s)e.push(...await tn(t));else{let t=s?.constructor?.name;throw new Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${mi(s)}`)}return e}function mi(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}var a=class{constructor(e){this._client=e}};function oo(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var no=Object.freeze(Object.create(null)),_i=(s=oo)=>function(t,...r){if(t.length===1)return t[0];let n=!1,o=[],c=t.reduce((w,h,f)=>{/[?#]/.test(h)&&(n=!0);let b=r[f],y=(n?encodeURIComponent:s)(""+b);return f!==r.length&&(b==null||typeof b=="object"&&b.toString===Object.getPrototypeOf(Object.getPrototypeOf(b.hasOwnProperty??no)??no)?.toString)&&(y=b+"",o.push({start:w.length+h.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(b).slice(8,-1)} is not a valid path parameter`})),w+h+(f===r.length?"":y)},""),l=c.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((w,h)=>w.start-h.start),o.length>0){let w=0,h=o.reduce((f,b)=>{let y=" ".repeat(b.start-w),A="^".repeat(b.length);return w=b.start+b.length,f+y+A},"");throw new g(`Path parameters result in path with invalid segments:
|
|
9
|
-
${o.map(f=>f.error).join(`
|
|
10
|
-
`)}
|
|
11
|
-
${c}
|
|
12
|
-
${h}`)}return c},i=_i(oo);var De=class extends a{list(e,t={},r){return this._client.getAPIList(i`/chat/completions/${e}/messages`,S,{query:t,...r,__security:{bearerAuth:!0}})}};function Kr(s){return s!==void 0&&"function"in s&&s.function!==void 0}function Fr(s){return s?.$brand==="auto-parseable-response-format"}function ze(s){return s?.$brand==="auto-parseable-tool"}function ao(s,e){return!e||!rn(e)?{...s,choices:s.choices.map(t=>(uo(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Ur(s,e)}function Ur(s,e){let t=s.choices.map(r=>{if(r.finish_reason==="length")throw new It;if(r.finish_reason==="content_filter")throw new xt;return uo(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(n=>Ai(e,n))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?yi(e,r.message.content):null}}});return{...s,choices:t}}function yi(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 Ai(s,e){let t=s.tools?.find(r=>Kr(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:ze(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function co(s,e){if(!s||!("tools"in s)||!s.tools)return!1;let t=s.tools?.find(r=>Kr(r)&&r.function?.name===e.function.name);return Kr(t)&&(ze(t)||t?.function.strict||!1)}function rn(s){return Fr(s.response_format)?!0:s.tools?.some(e=>ze(e)||e.type==="function"&&e.function.strict===!0)??!1}function uo(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 St=s=>s?.role==="assistant",sn=s=>s?.role==="tool";var ps,hs,ds,Br,Dr,ms,zr,fe,fs,qr,_s,gs,kt,po,ho,Ce=class{constructor(){ps.add(this),this.controller=new AbortController,hs.set(this,void 0),ds.set(this,()=>{}),Br.set(this,()=>{}),Dr.set(this,void 0),ms.set(this,()=>{}),zr.set(this,()=>{}),fe.set(this,{}),fs.set(this,[]),qr.set(this,!1),_s.set(this,!1),gs.set(this,!1),kt.set(this,!1),P(this,hs,new Promise((e,t)=>{P(this,ds,e,"f"),P(this,Br,t,"f")}),"f"),P(this,Dr,new Promise((e,t)=>{P(this,ms,e,"f"),P(this,zr,t,"f")}),"f"),u(this,hs,"f").catch(()=>{}),u(this,Dr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},u(this,ps,"m",ho).bind(this))},0)}_connected(){this.ended||(u(this,ds,"f").call(this),this._emit("connect"))}get ended(){return u(this,qr,"f")}get errored(){return u(this,_s,"f")}get aborted(){return u(this,gs,"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}),u(this,fs,"f").push({signal:e,listener:t})}on(e,t){return(u(this,fe,"f")[e]||(u(this,fe,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=u(this,fe,"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(u(this,fe,"f")[e]||(u(this,fe,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{P(this,kt,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){P(this,kt,!0,"f"),await u(this,Dr,"f")}_emit(e,...t){if(u(this,qr,"f"))return;e==="end"&&(u(this,ps,"m",po).call(this),P(this,qr,!0,"f"),u(this,ms,"f").call(this));let r=u(this,fe,"f")[e];if(r&&(u(this,fe,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!u(this,kt,"f")&&!r?.length&&Promise.reject(n),u(this,Br,"f").call(this,n),u(this,zr,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!u(this,kt,"f")&&!r?.length&&Promise.reject(n),u(this,Br,"f").call(this,n),u(this,zr,"f").call(this,n),this._emit("end")}}_emitFinal(){}};hs=new WeakMap,ds=new WeakMap,Br=new WeakMap,Dr=new WeakMap,ms=new WeakMap,zr=new WeakMap,fe=new WeakMap,fs=new WeakMap,qr=new WeakMap,_s=new WeakMap,gs=new WeakMap,kt=new WeakMap,ps=new WeakSet,po=function(){for(let{signal:e,listener:t}of u(this,fs,"f").splice(0))e.removeEventListener("abort",t)},ho=function(e){if(P(this,_s,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new K),e instanceof K)return P(this,gs,!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 mo(s){return typeof s.parse=="function"}var Y,nn,ys,on,an,cn,fo,_o,bi=10,$t=class extends Ce{constructor(){super(...arguments),Y.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),sn(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(St(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(),u(this,Y,"m",nn).call(this)}async finalMessage(){return await this.done(),u(this,Y,"m",ys).call(this)}async finalFunctionToolCall(){return await this.done(),u(this,Y,"m",on).call(this)}async finalFunctionToolCallResult(){return await this.done(),u(this,Y,"m",an).call(this)}async totalUsage(){return await this.done(),u(this,Y,"m",cn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=u(this,Y,"m",ys).call(this);t&&this._emit("finalMessage",t);let r=u(this,Y,"m",nn).call(this);r&&this._emit("finalContent",r);let n=u(this,Y,"m",on).call(this);n&&this._emit("finalFunctionToolCall",n);let o=u(this,Y,"m",an).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(c=>c.usage)&&this._emit("totalUsage",u(this,Y,"m",cn).call(this))}async _createChatCompletion(e,t,r){this._listenForAbort(r?.signal),u(this,Y,"m",fo).call(this,t);let n=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Ur(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:c="auto",stream:l,...m}=t,p=typeof c!="string"&&c.type==="function"&&c?.function?.name,{maxChatCompletions:w=bi,afterCompletion:h}=n||{},f=t.tools.map(I=>{if(ze(I)){if(!I.$callback)throw new g("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:I.$callback,name:I.function.name,description:I.function.description||"",parameters:I.function.parameters,parse:I.$parseRaw,strict:!0}}}return I}),b={};for(let I of f)I.type==="function"&&(b[I.function.name||I.function.function.name]=I.function);let y="tools"in t?f.map(I=>I.type==="function"?{type:"function",function:{name:I.function.name||I.function.function.name,parameters:I.function.parameters,description:I.function.description,strict:I.function.strict}}:I):void 0;for(let I of t.messages)this._addMessage(I,!1);let A=async I=>{if(I.type!=="function")return{message:void 0,functionCalled:!1};let k=I.id,{name:_,arguments:x}=I.function,R=b[_];if(!R){let T=`Invalid tool_call: ${JSON.stringify(_)}. Available options are: ${Object.keys(b).map(j=>JSON.stringify(j)).join(", ")}. Please try again`;return{message:{role:o,tool_call_id:k,content:T},functionCalled:!1}}if(p&&p!==_){let T=`Invalid tool_call: ${JSON.stringify(_)}. ${JSON.stringify(p)} requested. Please try again`;return{message:{role:o,tool_call_id:k,content:T},functionCalled:!1}}let O;if(mo(R)){let T;try{T=await R.parse(x)}catch(j){let J=j instanceof Error?j.message:String(j);return{message:{role:o,tool_call_id:k,content:J},functionCalled:!1}}O=await R.function(T,r)}else O=await R.function(x,r);let v=u(this,Y,"m",_o).call(this,O);return{message:{role:o,tool_call_id:k,content:v},functionCalled:!0}};for(let I=0;I<w;++I){let k=await this._createChatCompletion(e,{...m,tool_choice:c,tools:y,messages:[...this.messages]},n),_=k.choices[0]?.message;if(!_)throw new g("missing message in ChatCompletion response");if(!_.tool_calls?.length){await h?.(k,r);return}if(p||t.parallel_tool_calls===!1)for(let x of _.tool_calls){let R=await A(x);if(R.message&&this._addMessage(R.message),p&&R.functionCalled){await h?.(k,r);return}}else{let x=await Promise.allSettled(_.tool_calls.map(A));for(let R of x)if(R.status==="rejected")throw R.reason;for(let R of x)R.status==="fulfilled"&&R.value.message&&this._addMessage(R.value.message)}await h?.(k,r)}}};Y=new WeakSet,nn=function(){return u(this,Y,"m",ys).call(this).content??null},ys=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(St(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new g("stream ended without producing a ChatCompletionMessage with role=assistant")},on=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(St(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}}},an=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(sn(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}},cn=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},fo=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.")},_o=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Wr=class s extends $t{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),St(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},un=class extends Error{},ln=class extends Error{};function wi(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 Ii(s.trim(),e)}var Ii=(s,e)=>{let t=s.length,r=0,n=f=>{throw new un(`${f} at position ${r}`)},o=f=>{throw new ln(`${f} at position ${r}`)},c=()=>(h(),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):w()),l=()=>{let f=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(f,++r-Number(b)))}catch(y){o(String(y))}else if(z.STR&e)try{return JSON.parse(s.substring(f,r-Number(b))+'"')}catch{return JSON.parse(s.substring(f,s.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},m=()=>{r++,h();let f={};try{for(;s[r]!=="}";){if(h(),r>=t&&z.OBJ&e)return f;let b=l();h(),r++;try{let y=c();Object.defineProperty(f,b,{value:y,writable:!0,enumerable:!0,configurable:!0})}catch(y){if(z.OBJ&e)return f;throw y}h(),s[r]===","&&r++}}catch{if(z.OBJ&e)return f;n("Expected '}' at end of object")}return r++,f},p=()=>{r++;let f=[];try{for(;s[r]!=="]";)f.push(c()),h(),s[r]===","&&r++}catch{if(z.ARR&e)return f;n("Expected ']' at end of array")}return r++,f},w=()=>{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 f=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(f,r))}catch{s.substring(f,r)==="-"&&z.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s.substring(f,s.lastIndexOf("e")))}catch(y){o(String(y))}}},h=()=>{for(;r<t&&`
|
|
13
|
-
\r `.includes(s[r]);)r++};return c()},pn=s=>wi(s,z.ALL^z.NUM);var D,_e,Et,Se,hn,As,dn,mn,fn,bs,_n,go,qe=class s extends $t{constructor(e){super(),D.add(this),_e.set(this,void 0),Et.set(this,void 0),Se.set(this,void 0),P(this,_e,e,"f"),P(this,Et,[],"f")}get currentChatCompletionSnapshot(){return u(this,Se,"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),u(this,D,"m",hn).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)u(this,D,"m",dn).call(this,o);if(n.controller.signal?.aborted)throw new K;return this._addChatCompletion(u(this,D,"m",bs).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),u(this,D,"m",hn).call(this),this._connected();let r=le.fromReadableStream(e,this.controller),n;for await(let o of r)n&&n!==o.id&&this._addChatCompletion(u(this,D,"m",bs).call(this)),u(this,D,"m",dn).call(this,o),n=o.id;if(r.controller.signal?.aborted)throw new K;return this._addChatCompletion(u(this,D,"m",bs).call(this))}[(_e=new WeakMap,Et=new WeakMap,Se=new WeakMap,D=new WeakSet,hn=function(){this.ended||P(this,Se,void 0,"f")},As=function(t){let r=u(this,Et,"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},u(this,Et,"f")[t.index]=r,r)},dn=function(t){if(this.ended)return;let r=u(this,D,"m",go).call(this,t);this._emit("chunk",t,r);for(let n of t.choices){let o=r.choices[n.index];n.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",n.delta.content,o.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),n.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.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 c=u(this,D,"m",As).call(this,o);o.finish_reason&&(u(this,D,"m",fn).call(this,o),c.current_tool_call_index!=null&&u(this,D,"m",mn).call(this,o,c.current_tool_call_index));for(let l of n.delta.tool_calls??[])c.current_tool_call_index!==l.index&&(u(this,D,"m",fn).call(this,o),c.current_tool_call_index!=null&&u(this,D,"m",mn).call(this,o,c.current_tool_call_index)),c.current_tool_call_index=l.index;for(let l of n.delta.tool_calls??[]){let m=o.message.tool_calls?.[l.index];m?.type&&(m?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:m.function?.name,index:l.index,arguments:m.function.arguments,parsed_arguments:m.function.parsed_arguments,arguments_delta:l.function?.arguments??""}):(m?.type,void 0))}}},mn=function(t,r){if(u(this,D,"m",As).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 c=u(this,_e,"f")?.tools?.find(l=>Kr(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:ze(c)?c.$parseRaw(o.function.arguments):c?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},fn=function(t){let r=u(this,D,"m",As).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let n=u(this,D,"m",_n).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}))},bs=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");let t=u(this,Se,"f");if(!t)throw new g("request ended without sending any chunks");return P(this,Se,void 0,"f"),P(this,Et,[],"f"),xi(t,u(this,_e,"f"))},_n=function(){let t=u(this,_e,"f")?.response_format;return Fr(t)?t:null},go=function(t){var r,n,o,c;let l=u(this,Se,"f"),{choices:m,...p}=t;l?Object.assign(l,p):l=P(this,Se,{...p,choices:[]},"f");for(let{delta:w,finish_reason:h,index:f,logprobs:b=null,...y}of t.choices){let A=l.choices[f];if(A||(A=l.choices[f]={finish_reason:h,index:f,message:{},logprobs:b,...y}),b)if(!A.logprobs)A.logprobs=Object.assign({},b);else{let{content:v,refusal:T,...j}=b;Object.assign(A.logprobs,j),v&&((r=A.logprobs).content??(r.content=[]),A.logprobs.content.push(...v)),T&&((n=A.logprobs).refusal??(n.refusal=[]),A.logprobs.refusal.push(...T))}if(h&&(A.finish_reason=h,u(this,_e,"f")&&rn(u(this,_e,"f")))){if(h==="length")throw new It;if(h==="content_filter")throw new xt}if(Object.assign(A,y),!w)continue;let{content:I,refusal:k,function_call:_,role:x,tool_calls:R,...O}=w;if(Object.assign(A.message,O),k&&(A.message.refusal=(A.message.refusal||"")+k),x&&(A.message.role=x),_&&(A.message.function_call?(_.name&&(A.message.function_call.name=_.name),_.arguments&&((o=A.message.function_call).arguments??(o.arguments=""),A.message.function_call.arguments+=_.arguments)):A.message.function_call=_),I&&(A.message.content=(A.message.content||"")+I,!A.message.refusal&&u(this,D,"m",_n).call(this)&&(A.message.parsed=A.message.content.trim()?pn(A.message.content):null)),R){A.message.tool_calls||(A.message.tool_calls=[]);for(let{index:v,id:T,type:j,function:J,...M}of R){let U=(c=A.message.tool_calls)[v]??(c[v]={});Object.assign(U,M),T&&(U.id=T),j&&(U.type=j),J&&(U.function??(U.function={name:J.name??"",arguments:""})),J?.name&&(U.function.name=J.name),J?.arguments&&(U.function.arguments+=J.arguments,co(u(this,_e,"f"),U)&&(U.function.parsed_arguments=pn(U.function.arguments)))}}}return l},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,c)=>t.push({resolve:o,reject:c})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function xi(s,e){let{id:t,choices:r,created:n,model:o,system_fingerprint:c,...l}=s,m={...l,id:t,choices:r.map(({message:p,finish_reason:w,index:h,logprobs:f,...b})=>{if(!w)throw new g(`missing finish_reason for choice ${h}`);let{content:y=null,function_call:A,tool_calls:I,...k}=p,_=p.role;if(!_)throw new g(`missing role for choice ${h}`);if(A){let{arguments:x,name:R}=A;if(x==null)throw new g(`missing function_call.arguments for choice ${h}`);if(!R)throw new g(`missing function_call.name for choice ${h}`);return{...b,message:{content:y,function_call:{arguments:x,name:R},role:_,refusal:p.refusal??null},finish_reason:w,index:h,logprobs:f}}return I?{...b,index:h,finish_reason:w,logprobs:f,message:{...k,role:_,content:y,refusal:p.refusal??null,tool_calls:I.map((x,R)=>{let{function:O,type:v,id:T,...j}=x,{arguments:J,name:M,...U}=O||{};if(T==null)throw new g(`missing choices[${h}].tool_calls[${R}].id
|
|
14
|
-
${ws(s)}`);if(v==null)throw new g(`missing choices[${h}].tool_calls[${R}].type
|
|
15
|
-
${ws(s)}`);if(M==null)throw new g(`missing choices[${h}].tool_calls[${R}].function.name
|
|
16
|
-
${ws(s)}`);if(J==null)throw new g(`missing choices[${h}].tool_calls[${R}].function.arguments
|
|
17
|
-
${ws(s)}`);return{...j,id:T,type:v,function:{...U,name:M,arguments:J}}})}}:{...b,message:{...k,content:y,role:_,refusal:p.refusal??null},finish_reason:w,index:h,logprobs:f}}),created:n,model:o,object:"chat.completion",...c?{system_fingerprint:c}:{}};return ao(m,e)}function ws(s){return JSON.stringify(s)}var Hr=class s extends qe{static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}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 ge=class extends a{constructor(){super(...arguments),this.messages=new De(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",S,{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=>Ur(r,e))}runTools(e,t){return e.stream?Hr.runTools(this._client,e,t):Wr.runTools(this._client,e,t)}stream(e,t){return qe.createChatCompletion(this._client,e,t)}};ge.Messages=De;var ke=class extends a{constructor(){super(...arguments),this.completions=new ge(this._client)}};ke.Completions=ge;var vt=class extends a{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",S,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Ot=class extends a{list(e={},t){return this._client.getAPIList("/organization/audit_logs",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}};var Tt=class extends a{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",E,{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 Nt=class extends a{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 a{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",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Lt=class extends a{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",F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Mt=class extends a{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",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Kt=class extends a{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 Ft=class extends a{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`,F,{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 Ut=class extends a{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`,F,{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 $e=class extends a{constructor(){super(...arguments),this.users=new Ut(this._client),this.roles=new Ft(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",F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};$e.Users=Ut;$e.Roles=Ft;var Bt=class extends a{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`,E,{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 Dt=class extends a{list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/certificates`,E,{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 zt=class extends a{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 qt=class extends a{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 Wt=class extends a{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 Ht=class extends a{listRateLimits(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/rate_limits`,E,{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 Jt=class extends a{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`,F,{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 Xt=class extends a{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`,E,{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}})}};var Gt=class extends a{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`,E,{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 Vt=class extends a{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`,F,{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 We=class extends a{constructor(){super(...arguments),this.roles=new Vt(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`,F,{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}})}};We.Roles=Vt;var Yt=class extends a{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`,F,{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 He=class extends a{constructor(){super(...arguments),this.roles=new Yt(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`,E,{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}})}};He.Roles=Yt;var q=class extends a{constructor(){super(...arguments),this.users=new He(this._client),this.serviceAccounts=new Xt(this._client),this.apiKeys=new Bt(this._client),this.rateLimits=new Ht(this._client),this.modelPermissions=new Wt(this._client),this.hostedToolPermissions=new qt(this._client),this.groups=new We(this._client),this.roles=new Jt(this._client),this.dataRetention=new zt(this._client),this.spendAlerts=new Gt(this._client),this.certificates=new Dt(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",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(i`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};q.Users=He;q.ServiceAccounts=Xt;q.APIKeys=Bt;q.RateLimits=Ht;q.ModelPermissions=Wt;q.HostedToolPermissions=qt;q.Groups=We;q.Roles=Jt;q.DataRetention=zt;q.SpendAlerts=Gt;q.Certificates=Dt;var Qt=class extends a{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`,F,{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 Je=class extends a{constructor(){super(...arguments),this.roles=new Qt(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",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};Je.Roles=Qt;var W=class extends a{constructor(){super(...arguments),this.auditLogs=new Ot(this._client),this.adminAPIKeys=new vt(this._client),this.usage=new Kt(this._client),this.invites=new jt(this._client),this.users=new Je(this._client),this.groups=new $e(this._client),this.roles=new Lt(this._client),this.dataRetention=new Nt(this._client),this.spendAlerts=new Mt(this._client),this.certificates=new Tt(this._client),this.projects=new q(this._client)}};W.AuditLogs=Ot;W.AdminAPIKeys=vt;W.Usage=Kt;W.Invites=jt;W.Users=Je;W.Groups=$e;W.Roles=Lt;W.DataRetention=Nt;W.SpendAlerts=Mt;W.Certificates=Tt;W.Projects=q;var Ee=class extends a{constructor(){super(...arguments),this.organization=new W(this._client)}};Ee.Organization=W;var yo=Symbol("brand.privateNullableHeaders");function*Zi(s){if(!s)return;if(yo 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():Ms(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=Ms(r[1])?r[1]:[r[1]],c=!1;for(let l of o)l!==void 0&&(e&&!c&&(c=!0,yield[n,null]),yield[n,l])}}var d=s=>{let e=new Headers,t=new Set;for(let r of s){let n=new Set;for(let[o,c]of Zi(r)){let l=o.toLowerCase();n.has(l)||(e.delete(o),n.add(l)),c===null?(e.delete(o),t.add(l)):(e.append(o,c),t.delete(l))}}return{[yo]:!0,values:e,nulls:t}};var Zt=class extends a{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:d([{Accept:"application/octet-stream"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var er=class extends a{create(e,t){return this._client.post("/audio/transcriptions",V({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var tr=class extends a{create(e,t){return this._client.post("/audio/translations",V({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var pe=class extends a{constructor(){super(...arguments),this.transcriptions=new er(this._client),this.translations=new tr(this._client),this.speech=new Zt(this._client)}};pe.Transcriptions=er;pe.Translations=tr;pe.Speech=Zt;var Xe=class extends a{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",S,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}};var rr=class extends a{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/assistants/${e}`,{...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/assistants/${e}`,{body:t,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/assistants",S,{query:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/assistants/${e}`,{...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var sr=class extends a{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var nr=class extends a{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var ve=class extends a{constructor(){super(...arguments),this.sessions=new sr(this._client),this.transcriptionSessions=new nr(this._client)}};ve.Sessions=sr;ve.TranscriptionSessions=nr;var or=class extends a{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:d([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/chatkit/sessions/${e}/cancel`,{...t,headers:d([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}};var ir=class extends a{retrieve(e,t){return this._client.get(i`/chatkit/threads/${e}`,{...t,headers:d([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chatkit/threads",E,{query:e,...t,headers:d([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/chatkit/threads/${e}`,{...t,headers:d([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},r){return this._client.getAPIList(i`/chatkit/threads/${e}/items`,E,{query:t,...r,headers:d([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var Oe=class extends a{constructor(){super(...arguments),this.sessions=new or(this._client),this.threads=new ir(this._client)}};Oe.Sessions=or;Oe.Threads=ir;var ar=class extends a{create(e,t,r){return this._client.post(i`/threads/${e}/messages`,{body:t,...r,headers:d([{"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:d([{"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:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/threads/${e}/messages`,S,{query:t,...r,headers:d([{"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:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var cr=class extends a{retrieve(e,t,r){let{thread_id:n,run_id:o,...c}=t;return this._client.get(i`/threads/${n}/runs/${o}/steps/${e}`,{query:c,...r,headers:d([{"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`,S,{query:o,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Ao=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 se=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 H,Ve,gn,he,Is,ne,Ye,ur,Ge,Rs,ee,xs,Ps,Gr,Jr,Xr,bo,wo,Io,xo,Po,Ro,Co,ye=class extends Ce{constructor(){super(...arguments),H.add(this),gn.set(this,[]),he.set(this,{}),Is.set(this,{}),ne.set(this,void 0),Ye.set(this,void 0),ur.set(this,void 0),Ge.set(this,void 0),Rs.set(this,void 0),ee.set(this,void 0),xs.set(this,void 0),Ps.set(this,void 0),Gr.set(this,void 0)}[(gn=new WeakMap,he=new WeakMap,Is=new WeakMap,ne=new WeakMap,Ye=new WeakMap,ur=new WeakMap,Ge=new WeakMap,Rs=new WeakMap,ee=new WeakMap,xs=new WeakMap,Ps=new WeakMap,Gr=new WeakMap,H=new WeakSet,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,c)=>t.push({resolve:o,reject:c})).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 Ve;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let r=le.fromReadableStream(e,this.controller);for await(let n of r)u(this,H,"m",Jr).call(this,n);if(r.controller.signal?.aborted)throw new K;return this._addRun(u(this,H,"m",Xr).call(this))}toReadableStream(){return new le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n){let o=new Ve;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},c=await e.submitToolOutputs(t,o,{...n,signal:this.controller.signal});this._connected();for await(let l of c)u(this,H,"m",Jr).call(this,l);if(c.controller.signal?.aborted)throw new K;return this._addRun(u(this,H,"m",Xr).call(this))}static createThreadAssistantStream(e,t,r){let n=new Ve;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 Ve;return o._run(()=>o._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return u(this,xs,"f")}currentRun(){return u(this,Ps,"f")}currentMessageSnapshot(){return u(this,ne,"f")}currentRunStepSnapshot(){return u(this,Gr,"f")}async finalRunSteps(){return await this.done(),Object.values(u(this,he,"f"))}async finalMessages(){return await this.done(),Object.values(u(this,Is,"f"))}async finalRun(){if(await this.done(),!u(this,Ye,"f"))throw Error("Final run was not received.");return u(this,Ye,"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 c of o)u(this,H,"m",Jr).call(this,c);if(o.controller.signal?.aborted)throw new K;return this._addRun(u(this,H,"m",Xr).call(this))}async _createAssistantStream(e,t,r,n){this._listenForAbort(n?.signal);let o={...r,stream:!0},c=await e.create(t,o,{...n,signal:this.controller.signal});this._connected();for await(let l of c)u(this,H,"m",Jr).call(this,l);if(c.controller.signal?.aborted)throw new K;return this._addRun(u(this,H,"m",Xr).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(Or(o)&&Or(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(c=>typeof c=="string"||typeof c=="number")){o.push(...n);continue}for(let c of n){if(!Or(c))throw new Error(`Expected array delta entry to be an object but got: ${c}`);let l=c.index;if(l==null)throw console.error(c),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.push(c):o[l]=this.accumulateDelta(m,c)}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)}};Ve=ye,Jr=function(e){if(!this.ended)switch(P(this,xs,e,"f"),u(this,H,"m",Io).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":u(this,H,"m",Co).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":u(this,H,"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":u(this,H,"m",bo).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},Xr=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");if(!u(this,Ye,"f"))throw Error("Final run has not been received");return u(this,Ye,"f")},bo=function(e){let[t,r]=u(this,H,"m",Po).call(this,e,u(this,ne,"f"));P(this,ne,t,"f"),u(this,Is,"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,c=t.content[n.index];if(c&&c.type=="text")this._emit("textDelta",o,c.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=u(this,ur,"f")){if(u(this,Ge,"f"))switch(u(this,Ge,"f").type){case"text":this._emit("textDone",u(this,Ge,"f").text,u(this,ne,"f"));break;case"image_file":this._emit("imageFileDone",u(this,Ge,"f").image_file,u(this,ne,"f"));break}P(this,ur,n.index,"f")}P(this,Ge,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(u(this,ur,"f")!==void 0){let n=e.data.content[u(this,ur,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,u(this,ne,"f"));break;case"text":this._emit("textDone",n.text,u(this,ne,"f"));break}}u(this,ne,"f")&&this._emit("messageDone",e.data),P(this,ne,void 0,"f")}},wo=function(e){let t=u(this,H,"m",xo).call(this,e);switch(P(this,Gr,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==u(this,Rs,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(u(this,ee,"f")&&this._emit("toolCallDone",u(this,ee,"f")),P(this,Rs,o.index,"f"),P(this,ee,t.step_details.tool_calls[o.index],"f"),u(this,ee,"f")&&this._emit("toolCallCreated",u(this,ee,"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":P(this,Gr,void 0,"f"),e.data.step_details.type=="tool_calls"&&u(this,ee,"f")&&(this._emit("toolCallDone",u(this,ee,"f")),P(this,ee,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},Io=function(e){u(this,gn,"f").push(e),this._emit("event",e)},xo=function(e){switch(e.event){case"thread.run.step.created":return u(this,he,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=u(this,he,"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=Ve.accumulateDelta(t,r.delta);u(this,he,"f")[e.data.id]=n}return u(this,he,"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":u(this,he,"f")[e.data.id]=e.data;break}if(u(this,he,"f")[e.data.id])return u(this,he,"f")[e.data.id];throw new Error("No snapshot available")},Po=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 c=t.content[o.index];t.content[o.index]=u(this,H,"m",Ro).call(this,o,c)}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")},Ro=function(e,t){return Ve.accumulateDelta(t,e)},Co=function(e){switch(P(this,Ps,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":P(this,Ye,e.data,"f"),u(this,ee,"f")&&(this._emit("toolCallDone",u(this,ee,"f")),P(this,ee,void 0,"f"));break;case"thread.run.cancelling":break}};var Qe=class extends a{constructor(){super(...arguments),this.steps=new cr(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:d([{"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:d([{"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:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/threads/${e}/runs`,S,{query:t,...r,headers:d([{"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:d([{"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 ye.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let n=d([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:c}=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=c.headers.get("openai-poll-after-ms");if(m){let p=parseInt(m);isNaN(p)||(l=p)}}await ce(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return ye.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:d([{"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 ye.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};Qe.Steps=cr;var Te=class extends a{constructor(){super(...arguments),this.runs=new Qe(this._client),this.messages=new ar(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/threads/${e}`,{...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/threads/${e}`,{body:t,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/threads/${e}`,{...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:d([{"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 ye.createThreadAssistantStream(e,this._client.beta.threads,t)}};Te.Runs=Qe;Te.Messages=ar;var oe=class extends a{constructor(){super(...arguments),this.realtime=new ve(this._client),this.chatkit=new Oe(this._client),this.assistants=new rr(this._client),this.threads=new Te(this._client)}};oe.Realtime=ve;oe.ChatKit=Oe;oe.Assistants=rr;oe.Threads=Te;var Ze=class extends a{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var lr=class extends a{retrieve(e,t,r){let{container_id:n}=t;return this._client.get(i`/containers/${n}/files/${e}/content`,{...r,headers:d([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var et=class extends a{constructor(){super(...arguments),this.content=new lr(this._client)}create(e,t,r){return this._client.post(i`/containers/${e}/files`,Re({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`,S,{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:d([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};et.Content=lr;var Ne=class extends a{constructor(){super(...arguments),this.files=new et(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",S,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/containers/${e}`,{...t,headers:d([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}};Ne.Files=et;var pr=class extends a{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`,E,{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 je=class extends a{constructor(){super(...arguments),this.items=new pr(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}})}};je.Items=pr;var tt=class extends a{create(e,t){let r=!!e.encoding_format,n=r?e.encoding_format:"base64";r&&L(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:(L(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(c=>(c&&c.data&&c.data.forEach(l=>{let m=l.embedding;l.embedding=Ao(m)}),c)))}};var hr=class extends a{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`,S,{query:o,...r,__security:{bearerAuth:!0}})}};var rt=class extends a{constructor(){super(...arguments),this.outputItems=new hr(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`,S,{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}})}};rt.OutputItems=hr;var Le=class extends a{constructor(){super(...arguments),this.runs=new rt(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",S,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};Le.Runs=rt;var st=class extends a{create(e,t){return this._client.post("/files",V({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",S,{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:d([{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(),c=await this.retrieve(e);for(;!c.status||!n.has(c.status);)if(await ce(t),c=await this.retrieve(e),Date.now()-o>r)throw new xe({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return c}};var dr=class extends a{};var mr=class extends a{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 nt=class extends a{constructor(){super(...arguments),this.graders=new mr(this._client)}};nt.Graders=mr;var fr=class extends a{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`,E,{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 ot=class extends a{constructor(){super(...arguments),this.permissions=new fr(this._client)}};ot.Permissions=fr;var _r=class extends a{list(e,t={},r){return this._client.getAPIList(i`/fine_tuning/jobs/${e}/checkpoints`,S,{query:t,...r,__security:{bearerAuth:!0}})}};var it=class extends a{constructor(){super(...arguments),this.checkpoints=new _r(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",S,{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`,S,{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}})}};it.Checkpoints=_r;var ie=class extends a{constructor(){super(...arguments),this.methods=new dr(this._client),this.jobs=new it(this._client),this.checkpoints=new ot(this._client),this.alpha=new nt(this._client)}};ie.Methods=dr;ie.Jobs=it;ie.Checkpoints=ot;ie.Alpha=nt;var gr=class extends a{};var Me=class extends a{constructor(){super(...arguments),this.graderModels=new gr(this._client)}};Me.GraderModels=gr;var at=class extends a{createVariation(e,t){return this._client.post("/images/variations",V({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post("/images/edits",V({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 ct=class extends a{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 ut=class extends a{create(e,t){return this._client.post("/moderations",{body:e,...t,__security:{bearerAuth:!0}})}};var yr=class extends a{accept(e,t,r){return this._client.post(i`/realtime/calls/${e}/accept`,{body:t,...r,headers:d([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(i`/realtime/calls/${e}/hangup`,{...t,headers:d([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,r){return this._client.post(i`/realtime/calls/${e}/refer`,{body:t,...r,headers:d([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},r){return this._client.post(i`/realtime/calls/${e}/reject`,{body:t,...r,headers:d([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};var Ar=class extends a{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t,__security:{bearerAuth:!0}})}};var Ae=class extends a{constructor(){super(...arguments),this.clientSecrets=new Ar(this._client),this.calls=new yr(this._client)}};Ae.ClientSecrets=Ar;Ae.Calls=yr;function So(s,e){if(!e||!Ea(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 ko(s,t)&&te(t),t}return yn(s,e)}function yn(s,e){let t=!s.status||s.status==="completed",r=s.output.map(o=>{if(o.type==="function_call")return{...o,parsed_arguments:t?Ta(e,o):null};if(o.type==="message"){let c=o.content.map(l=>l.type==="output_text"?{...l,parsed:t?$a(e,l.text):null}:l);return{...o,content:c}}return o}),n=Object.assign({},s,{output:r});return ko(s,n)&&te(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let o of n.output)if(o.type==="message"){for(let c of o.content)if(c.type==="output_text"&&c.parsed!==null)return c.parsed}return null}}),n}function $a(s,e){return s.text?.format?.type!=="json_schema"?null:"$parseRaw"in s.text?.format?(s.text?.format).$parseRaw(e):JSON.parse(e)}function Ea(s){return!!Fr(s.text?.format)}function va(s){return s?.$brand==="auto-parseable-tool"}function Oa(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function Ta(s,e){let t=Oa(s.tools??[],e.name);return{...e,...e,parsed_arguments:va(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function ko(s,e){return!Object.getOwnPropertyDescriptor(s,"output_text")||e.output_text==null}function te(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 Eo(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 $o(s.response)}switch(s.type){case"response.output_item.added":{e.output.push(structuredClone(s.item)),s.item.type==="message"&&te(e);break}case"response.output_item.done":{$(e,s.output_index),e.output[s.output_index]=structuredClone(s.item),s.item.type==="message"&&te(e);break}case"response.content_part.added":{let t=$(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"&&te(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,s.output_index),r=s.part;if(t.type==="message"&&r.type!=="reasoning_text")re(t.content,s.content_index),t.content[s.content_index]=structuredClone(r),r.type==="output_text"&&te(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}`);re(n,s.content_index),n[s.content_index]=structuredClone(r)}break}case"response.output_text.delta":{let t=$(e,s.output_index);if(t.type==="message"){let r=re(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,s.output_index);if(t.type==="message"){let r=re(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,te(e)}break}case"response.output_text.annotation.added":{let t=$(e,s.output_index);if(t.type==="message"){let r=re(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,s.output_index);if(t.type==="message"){let r=re(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,s.output_index);if(t.type==="message"){let r=re(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,s.output_index);t.type==="function_call"&&(t.arguments+=s.delta);break}case"response.function_call_arguments.done":{let t=$(e,s.output_index);t.type==="function_call"&&(t.arguments=s.arguments);break}case"response.reasoning_text.delta":{let t=$(e,s.output_index);if(t.type==="reasoning"){if(!t.content)throw new g(`missing content at index ${s.content_index}`);let r=re(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,s.output_index);if(t.type==="reasoning"){if(!t.content)throw new g(`missing content at index ${s.content_index}`);let r=re(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,s.output_index);t.type==="reasoning"&&t.summary.push(structuredClone(s.part));break}case"response.reasoning_summary_part.done":{let t=$(e,s.output_index);t.type==="reasoning"&&(re(t.summary,s.summary_index),t.summary[s.summary_index]=structuredClone(s.part));break}case"response.reasoning_summary_text.delta":{let t=$(e,s.output_index);if(t.type==="reasoning"){let r=re(t.summary,s.summary_index);r.text+=s.delta}break}case"response.reasoning_summary_text.done":{let t=$(e,s.output_index);if(t.type==="reasoning"){let r=re(t.summary,s.summary_index);r.text=s.text}break}case"response.custom_tool_call_input.delta":{let t=$(e,s.output_index);t.type==="custom_tool_call"&&(t.input+=s.delta);break}case"response.custom_tool_call_input.done":{let t=$(e,s.output_index);t.type==="custom_tool_call"&&(t.input=s.input);break}case"response.mcp_call_arguments.delta":{let t=$(e,s.output_index);t.type==="mcp_call"&&(t.arguments+=s.delta);break}case"response.mcp_call_arguments.done":{let t=$(e,s.output_index);t.type==="mcp_call"&&(t.arguments=s.arguments);break}case"response.code_interpreter_call_code.delta":{let t=$(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,s.output_index);t.type==="code_interpreter_call"&&(t.code=s.code);break}case"response.code_interpreter_call.in_progress":{let t=$(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="in_progress");break}case"response.code_interpreter_call.interpreting":{let t=$(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="interpreting");break}case"response.code_interpreter_call.completed":{let t=$(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="completed");break}case"response.file_search_call.in_progress":{let t=$(e,s.output_index);t.type==="file_search_call"&&(t.status="in_progress");break}case"response.file_search_call.searching":{let t=$(e,s.output_index);t.type==="file_search_call"&&(t.status="searching");break}case"response.file_search_call.completed":{let t=$(e,s.output_index);t.type==="file_search_call"&&(t.status="completed");break}case"response.web_search_call.in_progress":{let t=$(e,s.output_index);t.type==="web_search_call"&&(t.status="in_progress");break}case"response.web_search_call.searching":{let t=$(e,s.output_index);t.type==="web_search_call"&&(t.status="searching");break}case"response.web_search_call.completed":{let t=$(e,s.output_index);t.type==="web_search_call"&&(t.status="completed");break}case"response.image_generation_call.in_progress":{let t=$(e,s.output_index);t.type==="image_generation_call"&&(t.status="in_progress");break}case"response.image_generation_call.generating":{let t=$(e,s.output_index);t.type==="image_generation_call"&&(t.status="generating");break}case"response.image_generation_call.completed":{let t=$(e,s.output_index);t.type==="image_generation_call"&&(t.status="completed");break}case"response.mcp_call.in_progress":{let t=$(e,s.output_index);t.type==="mcp_call"&&(t.status="in_progress");break}case"response.mcp_call.completed":{let t=$(e,s.output_index);t.type==="mcp_call"&&(t.status="completed");break}case"response.mcp_call.failed":{let t=$(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=$o(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"error":break;default:Na(s)}return e}function $o(s){let e=structuredClone(s);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&te(e),e}function $(s,e){let t=s.output[e];if(!t)throw new g(`missing output at index ${e}`);return t}function re(s,e){let t=s[e];if(!t)throw new g(`missing content at index ${e}`);return t}function Na(s){throw new g(`Unhandled response stream event: ${JSON.stringify(s)}`)}var Vr,Cs,lt,Ss,vo,Oo,To,ks=class s extends Ce{constructor(e){super(),Vr.add(this),Cs.set(this,void 0),lt.set(this,void 0),Ss.set(this,void 0),P(this,Cs,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}async _createOrRetrieveResponse(e,t,r){this._listenForAbort(r?.signal),u(this,Vr,"m",vo).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 c of n)u(this,Vr,"m",Oo).call(this,c,o);if(n.controller.signal?.aborted)throw new K;return u(this,Vr,"m",To).call(this)}[(Cs=new WeakMap,lt=new WeakMap,Ss=new WeakMap,Vr=new WeakSet,vo=function(){this.ended||P(this,lt,void 0,"f")},Oo=function(t,r){if(this.ended)return;let n=(c,l)=>{(r==null||l.sequence_number>r)&&this._emit(c,l)},o=Eo(t,u(this,lt,"f"));switch(P(this,lt,o,"f"),n("event",t),t.type){case"response.output_text.delta":{let c=o.output[t.output_index];if(!c)throw new g(`missing output at index ${t.output_index}`);if(c.type==="message"){let l=c.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 c=o.output[t.output_index];if(!c)throw new g(`missing output at index ${t.output_index}`);c.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:c.arguments});break}default:n(t.type,t);break}},To=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");let t=u(this,lt,"f");if(!t)throw new g("request ended without sending any events");P(this,lt,void 0,"f");let r=ja(t,u(this,Cs,"f"));return P(this,Ss,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,c)=>t.push({resolve:o,reject:c})).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=u(this,Ss,"f");if(!e)throw new g("stream ended without producing a ChatCompletion");return e}};function ja(s,e){return So(s,e)}var br=class extends a{list(e,t={},r){return this._client.getAPIList(i`/responses/${e}/input_items`,S,{query:t,...r,__security:{bearerAuth:!0}})}};var wr=class extends a{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t,__security:{bearerAuth:!0}})}};var de=class extends a{constructor(){super(...arguments),this.inputItems=new br(this._client),this.inputTokens=new wr(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"&&te(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"&&te(n),n))}delete(e,t){return this._client.delete(i`/responses/${e}`,{...t,headers:d([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>yn(r,e))}stream(e,t){return ks.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}})}};de.InputItems=br;de.InputTokens=wr;var Ir=class extends a{retrieve(e,t){return this._client.get(i`/skills/${e}/content`,{...t,headers:d([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var xr=class extends a{retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(i`/skills/${n}/versions/${e}/content`,{...r,headers:d([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var pt=class extends a{constructor(){super(...arguments),this.content=new xr(this._client)}create(e,t={},r){return this._client.post(i`/skills/${e}/versions`,Re({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`,S,{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}})}};pt.Content=xr;var be=class extends a{constructor(){super(...arguments),this.content=new Ir(this._client),this.versions=new pt(this._client)}create(e={},t){return this._client.post("/skills",Re({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",S,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};be.Content=Ir;be.Versions=pt;var Pr=class extends a{create(e,t,r){return this._client.post(i`/uploads/${e}/parts`,V({body:t,...r,__security:{bearerAuth:!0}},this._client))}};var Ke=class extends a{constructor(){super(...arguments),this.parts=new Pr(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}})}};Ke.Parts=Pr;var No=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 Rr=class extends a{create(e,t,r){return this._client.post(i`/vector_stores/${e}/file_batches`,{body:t,...r,headers:d([{"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:d([{"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:d([{"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`,S,{query:o,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,r){let n=d([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:c}=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=c.headers.get("openai-poll-after-ms");if(m){let p=parseInt(m);isNaN(p)||(l=p)}}await ce(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,c=Math.min(o,t.length),l=this._client,m=t.values(),p=[...r];async function w(f){for(let b of f){let y=await l.files.create({file:b,purpose:"assistants"},n);p.push(y.id)}}let h=Array(c).fill(m).map(w);return await No(h),await this.createAndPoll(e,{file_ids:p})}};var Cr=class extends a{create(e,t,r){return this._client.post(i`/vector_stores/${e}/files`,{body:t,...r,headers:d([{"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:d([{"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:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/vector_stores/${e}/files`,S,{query:t,...r,headers:d([{"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:d([{"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=d([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(),c=o.data;switch(c.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 ce(l);break;case"failed":case"completed":return c}}}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:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var we=class extends a{constructor(){super(...arguments),this.files=new Cr(this._client),this.fileBatches=new Rr(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/vector_stores/${e}`,{...t,headers:d([{"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:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vector_stores",S,{query:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/vector_stores/${e}`,{...t,headers:d([{"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:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};we.Files=Cr;we.FileBatches=Rr;var ht=class extends a{create(e,t){return this._client.post("/videos",V({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",E,{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",V({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},r){return this._client.get(i`/videos/${e}/content`,{query:t,...r,headers:d([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post("/videos/edits",V({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post("/videos/extensions",V({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`,Re({body:t,...r,__security:{bearerAuth:!0}},this._client))}};var Sr,jo,$s,dt=class extends a{constructor(){super(...arguments),Sr.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");u(this,Sr,"m",jo).call(this,r);let o=d([t]).values,c=u(this,Sr,"m",$s).call(this,o,"webhook-signature"),l=u(this,Sr,"m",$s).call(this,o,"webhook-timestamp"),m=u(this,Sr,"m",$s).call(this,o,"webhook-id"),p=parseInt(l,10);if(isNaN(p))throw new ae("Invalid webhook timestamp format");let w=Math.floor(Date.now()/1e3);if(w-p>n)throw new ae("Webhook timestamp is too old");if(p>w+n)throw new ae("Webhook timestamp is too new");let h=c.split(" ").map(A=>A.startsWith("v1,")?A.substring(3):A),f=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),b=m?`${m}.${l}.${e}`:`${l}.${e}`,y=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let A of h)try{let I=Buffer.from(A,"base64");if(await crypto.subtle.verify("HMAC",y,I,new TextEncoder().encode(b)))return}catch{continue}throw new ae("The given webhook signature does not match the expected signature")}};Sr=new WeakSet,jo=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")},$s=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 Mo=Symbol.for("openai.node.providerDefinitions.v1"),Ko=globalThis,Fo=Ko[Mo],Uo=Fo??new WeakMap;Fo||Object.defineProperty(Ko,Mo,{value:Uo});function Bo(s){let e=Uo.get(s);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var An,bn,Yr,Do,qa="workload-identity-auth",C=class{constructor(e={}){An.add(this),Yr.set(this,void 0),this.completions=new Ze(this),this.chat=new ke(this),this.embeddings=new tt(this),this.files=new st(this),this.images=new at(this),this.audio=new pe(this),this.moderations=new ut(this),this.models=new ct(this),this.fineTuning=new ie(this),this.graders=new Me(this),this.vectorStores=new we(this),this.webhooks=new dt(this),this.beta=new oe(this),this.batches=new Xe(this),this.uploads=new Ke(this),this.admin=new Ee(this),this.responses=new de(this),this.realtime=new Ae(this),this.conversations=new je(this),this.evals=new Le(this),this.containers=new Ne(this),this.skills=new be(this),this.videos=new ht(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:se("OPENAI_BASE_URL"),apiKey:n=t?null:se("OPENAI_API_KEY")??null,adminAPIKey:o=t?null:se("OPENAI_ADMIN_KEY")??null,organization:c=t?null:se("OPENAI_ORG_ID")??null,project:l=t?null:se("OPENAI_PROJECT_ID")??null,webhookSecret:m=se("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:p,...w}=e,h=t?Bo(t):void 0,f={apiKey:n,adminAPIKey:o,organization:c,project:l,webhookSecret:m,workloadIdentity:p,provider:t,...w,baseURL:h?.baseURL??(r||"https://api.openai.com/v1")};if(n&&p)throw new g("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!h&&!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(!f.dangerouslyAllowBrowser&&Ln())throw new g(`It looks like you're running in a browser-like environment.
|
|
18
|
-
|
|
19
|
-
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
20
|
-
If you understand the risks and have appropriate mitigations in place,
|
|
21
|
-
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
22
|
-
|
|
23
|
-
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
24
|
-
|
|
25
|
-
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
26
|
-
`);this.baseURL=f.baseURL,this.timeout=f.timeout??bn.DEFAULT_TIMEOUT,this.logger=f.logger??console;let b="warn";this.logLevel=b,this.logLevel=Gs(f.logLevel,"ClientOptions.logLevel",this)??Gs(se("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??b,this.fetchOptions=f.fetchOptions,this.maxRetries=f.maxRetries??2,this.fetch=f.fetch??ts(),P(this,Yr,Fn,"f");let y=t?void 0:se("OPENAI_CUSTOM_HEADERS");if(y){let A={};for(let I of y.split(`
|
|
27
|
-
`)){let k=I.indexOf(":");k>=0&&(A[I.substring(0,k).trim()]=I.substring(k+1).trim())}f.defaultHeaders=d([A,f.defaultHeaders])}this._options=f,this._provider=h,p&&(this._workloadIdentityAuth=new cs(p,this.fetch)),this.apiKey=typeof n=="string"?n:null,this.adminAPIKey=o,this.organization=c,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 d([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return d([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return d([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return d([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Xn(e)}getUserAgent(){return`${this.constructor.name}/JS ${Pe}`}defaultIdempotencyKey(){return`stainless-node-retry-${Ls()}`}makeStatusError(e,t,r,n){return N.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=!u(this,An,"m",Do).call(this)&&r||this.baseURL,o=$n(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),c=this.defaultQuery(),l=Object.fromEntries(o.searchParams);return(!Ks(c)||!Ks(l))&&(t={...l,...c,...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 Be(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:c,url:l,timeout:m}=await this.buildRequest(n,{retryCount:o-t});await this.prepareRequest(c,{url:l,options:n}),await this._provider?.prepareRequest?.(c,{url:l,options:n});let p="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),w=r===void 0?"":`, retryOf: ${r}`,h=Date.now();if(L(this).debug(`[${p}] sending request`,me({retryOfRequestLogID:r,method:n.method,url:l,options:n,headers:c.headers})),n.signal?.aborted)throw new K;let f=n.__security??{bearerAuth:!0},b=new AbortController,y=await this.fetchWithAuth(l,c,m,b,f).catch(Er),A=Date.now();if(y instanceof globalThis.Error){let _=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new K;let x=$r(y)||/timed? ?out/i.test(String(y)+("cause"in y?String(y.cause):""));if(t)return L(this).info(`[${p}] connection ${x?"timed out":"failed"} - ${_}`),L(this).debug(`[${p}] connection ${x?"timed out":"failed"} (${_})`,me({retryOfRequestLogID:r,url:l,durationMs:A-h,message:y.message})),this.retryRequest(n,t,r??p);throw L(this).info(`[${p}] connection ${x?"timed out":"failed"} - error; no more retries left`),L(this).debug(`[${p}] connection ${x?"timed out":"failed"} (error; no more retries left)`,me({retryOfRequestLogID:r,url:l,durationMs:A-h,message:y.message})),y instanceof Fe||y instanceof vr?y:x?new xe:new Ie({message:Wa(y),cause:y})}let I=[...y.headers.entries()].filter(([_])=>_==="x-request-id").map(([_,x])=>", "+_+": "+JSON.stringify(x)).join(""),k=`[${p}${w}${I}] ${c.method} ${l} ${y.ok?"succeeded":"failed"} with status ${y.status} in ${A-h}ms`;if(!y.ok){if(y.status===401&&this._workloadIdentityAuth&&f.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await Bs(y.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},t,r??p);let _=await this.shouldRetry(y);if(t&&_){let j=`retrying, ${t} attempts remaining`;return await Bs(y.body),L(this).info(`${k} - ${j}`),L(this).debug(`[${p}] response error (${j})`,me({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,durationMs:A-h})),this.retryRequest(n,t,r??p,y.headers)}let x=_?"error; no more retries left":"error; not retryable";L(this).info(`${k} - ${x}`);let R=await y.text().catch(j=>Er(j).message),O=On(R),v=O?void 0:R;throw L(this).debug(`[${p}] response error (${x})`,me({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,message:v,durationMs:Date.now()-h})),this.makeStatusError(y.status,O,v,y.headers)}return L(this).info(k),L(this).debug(`[${p}] response start`,me({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,durationMs:A-h})),{response:y,options:n,controller:b,requestLogID:p,retryOfRequestLogID:r,startTime:h}}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 Lr(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 ${qa}`){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:c,...l}=t||{},m=this._makeAbort(n);o&&o.addEventListener("abort",m,{once:!0});let p=setTimeout(m,r),w=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,h={signal:n.signal,...w?{duplex:"half"}:{},method:"GET",...l};c&&(h.method=c.toUpperCase());try{return await this.fetch.call(void 0,e,h)}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,c=n?.get("retry-after-ms");if(c){let m=parseFloat(c);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 ce(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,c=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return c*l*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:n,path:o,query:c,defaultBaseURL:l}=r,m=this.buildURL(o,c,l);"timeout"in r&&vn("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:p,body:w,isStreamingBody:h}=this.buildBody({options:r});h&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let f=await this.buildHeaders({options:e,method:n,bodyHeaders:p,retryCount:t});return{req:{method:n,headers:f,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&w instanceof globalThis.ReadableStream&&{duplex:"half"},...w&&{body:w},...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 c=d([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))}:{},...Mn(),"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(c,e.__security??{bearerAuth:!0}),c.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:r}=e;if(!t)return t===void 0&&"body"in e?{...u(this,Yr,"f").call(this,{body:t,headers:d([r])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=d([r]),o=typeof globalThis.ReadableStream<"u"&&t instanceof globalThis.ReadableStream,c=!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:!c}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:rs(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}:{...u(this,Yr,"f").call(this,{body:t,headers:n}),isStreamingBody:!1}}};bn=C,Yr=new WeakMap,An=new WeakSet,Do=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};C.OpenAI=bn;C.DEFAULT_TIMEOUT=6e5;C.OpenAIError=g;C.APIError=N;C.APIConnectionError=Ie;C.APIConnectionTimeoutError=xe;C.APIUserAbortError=K;C.NotFoundError=gt;C.ConflictError=yt;C.RateLimitError=bt;C.BadRequestError=mt;C.AuthenticationError=ft;C.InternalServerError=wt;C.PermissionDeniedError=_t;C.UnprocessableEntityError=At;C.InvalidWebhookSignatureError=ae;C.toFile=ls;C.Completions=Ze;C.Chat=ke;C.Embeddings=tt;C.Files=st;C.Images=at;C.Audio=pe;C.Moderations=ut;C.Models=ct;C.FineTuning=ie;C.Graders=Me;C.VectorStores=we;C.Webhooks=dt;C.Beta=oe;C.Batches=Xe;C.Uploads=Ke;C.Admin=Ee;C.Responses=de;C.Realtime=Ae;C.Conversations=je;C.Evals=Le;C.Containers=Ne;C.Skills=be;C.Videos=ht;function Wa(s){if(Ha(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 Ha(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 Es=xn({module:"llm"});var zo=class{client;model;systemPrompt;maxOutputTokens;constructor(e,t){let r=js(e);if(!r)throw new Zr("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 C({apiKey:r,baseURL:e.base_url}),this.model=e.model,this.systemPrompt=t,this.maxOutputTokens=Ns(e)}async*stream(e,t,r){let n=Ja(e.getMessages()),o=[];o.push({role:"system",content:this.systemPrompt});for(let f of n)o.push(f);let c=t.map(f=>{let b=f.input_schema;return{type:"function",name:f.name,description:f.description,parameters:b,strict:!1}}),l={model:this.model,input:o,stream:!0,max_output_tokens:this.maxOutputTokens,...c.length>0?{tools:c}:{}},m=0,p=0,w=0,h=0;try{let f=await this.client.responses.create(l,{...r?{signal:r}:{}}),b="",y="",A="",I="",k="";for await(let _ of f)if(_.type==="response.output_text.delta")yield{type:"text_delta",text:_.delta};else if(_.type==="response.reasoning_summary_text.delta")k+=_.delta,yield{type:"thinking_delta",text:_.delta};else if(_.type==="response.reasoning_summary_text.done")yield{type:"thinking_complete",thinking:k,signature:I};else if(_.type==="response.function_call_arguments.delta")A+=_.delta,yield{type:"tool_call_delta",text:_.delta};else if(_.type==="response.output_item.added")_.item.type==="function_call"?(b=_.item.name,y=_.item.call_id,A="",yield{type:"tool_call_start",toolName:b,toolId:y}):_.item.type==="reasoning"&&(I=_.item.id??"",k="");else if(_.type==="response.output_item.done"){if(_.item.type==="function_call"&&b){let x={};if(A)try{let R=JSON.parse(A);x=Os(R)?Qr(R):{[kr]:A}}catch(R){Es.error({err:R},"llm operation failed"),x={[kr]:A}}yield{type:"tool_call_complete",toolId:y,toolName:b,arguments:x},b="",y="",A=""}}else if(_.type==="response.completed"){let x=_.response.usage;x&&(p=x.output_tokens,w=x.input_tokens_details.cached_tokens,m=Math.max(0,x.input_tokens-w));let R="end_turn",O=_.response;O.status==="incomplete"&&O.incomplete_details?.reason==="max_output_tokens"&&(R="max_tokens"),yield{type:"stream_end",stopReason:R,usage:{inputTokens:m,outputTokens:p,cacheReadInputTokens:w,cacheCreationInputTokens:h}}}}catch(f){throw Es.error({err:f},"llm operation failed"),Wo(f)}}setSystemPrompt(e){this.systemPrompt=e}setMaxOutputTokens(e){this.maxOutputTokens=e}};function Ja(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)for(let r of t.toolResults)e.push({type:"function_call_output",call_id:r.toolUseId,output:r.content});else e.push({role:t.role,content:t.content})}return e}function Xa(s){return/context_length_exceeded/i.test(s)||/maximum\scontext\slength/i.test(s)||/prompts?\s+too\s+long/i.test(s)}function by(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 qo=class{client;model;systemPrompt;maxOutputTokens;constructor(e,t){let r=js(e);if(!r)throw new Zr("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 C({apiKey:r,baseURL:e.base_url}),this.model=e.model,this.systemPrompt=t,this.maxOutputTokens=Ns(e)}setSystemPrompt(e){this.systemPrompt=e}setMaxOutputTokens(e){this.maxOutputTokens=e}async*stream(e,t,r){let n=[{role:"system",content:this.systemPrompt},...Ga(e.getMessages())],o=t.map(h=>({type:"function",function:{name:h.name,description:h.description,arguments:h.input_schema}})),c={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,w=0;try{let h=await this.client.chat.completions.create(c,{...r?{signal:r}:{}}),f=new Map,b=null,y="";for await(let I of h){if(I.usage&&(m=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 _=Pn(Qr(k),"reasoning_content");if(_&&(y+=_,yield{type:"thinking_delta",text:_}),k.tool_calls)for(let x of k.tool_calls){f.has(x.index)||(f.set(x.index,{id:x.id??"",name:x.function?.name??"",args:""}),x.id&&(yield{type:"tool_call_start",toolName:x.function?.name??"",toolId:x.id??""}));let R=f.get(x.index);R&&(x.id&&(R.id=x.id),x.function?.name&&(R.name=x.function.name),x.function?.arguments&&(R.args+=x.function.arguments,yield{type:"tool_call_delta",text:x.function.arguments}))}if(I.choices[0].finish_reason){b=I.choices[0].finish_reason,y&&(yield{type:"thinking_complete",thinking:y,signature:""},y="");for(let x of f.values()){let R={},O=x.args;if(O){try{let v=JSON.parse(O);R=Os(v)?Qr(v):{[kr]:O}}catch(v){Es.error({err:v},"llm operation failed"),R={[kr]:O}}yield{type:"tool_call_complete",toolName:x.name,toolId:x.id,arguments:R}}}}}let A;b==="length"?A="max_tokens":b==="tool_calls"||f.size>0?A="tool_use":A="end_turn",yield{type:"stream_end",stopReason:A,usage:{inputTokens:l,outputTokens:m,cacheReadInputTokens:p,cacheCreationInputTokens:w}}}catch(h){throw Es.error({err:h},"llm operation failed"),Wo(h)}}};function Wo(s){return s instanceof C.APIError?s.status===413||s.status===400&&Xa(s.message)?new kn(`Context Too Long: ${s.message}`):s.status===401?new Zr(`Invalid API key: ${s.message}`):s.status===429?new Cn("Rate limit error, please wait."):new Rn(`OpenAI API error (${Ts(s.status)}): ${s.message}`):new Sn(`Network error: ${s instanceof Error?s.message:Ts(s)}`)}function Ga(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)for(let n of t.toolResults)e.push({role:"tool",tool_call_id:n.toolUseId,content:n.content});else t.role==="assistant"?e.push({role:"assistant",content:t.content,...r?{reasoning_content:r}:{}}):e.push({role:t.role==="system"?"system":"user",content:t.content})}return e}export{zo as OpenAIClient,qo as OpenAICompatClient,by as buildChatCompletionMessage,Ga as buildChatCompletionMessages,Ja as buildOpenAIInput};
|
package/docs/ch1.md
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
# 什么是 Agent
|
|
2
|
-
|
|
3
|
-
agent 是 LLM 在循环中根据环境反馈自主使用工具的系统
|
|
4
|
-
|
|
5
|
-
- LLM 是大脑,负责理解和思考
|
|
6
|
-
- 循环: 意味着不是一次性问答就结束, 做一步操作, 拿到结果,再决定下一步
|
|
7
|
-
- 反馈: agent 每做一步操作, 都能拿到到结果, 这些反馈驱动下一步决策
|
|
8
|
-
- 执行一条命令, 拿到输出
|
|
9
|
-
- 读一个文件, 拿到内容
|
|
10
|
-
- 跑一个测试, 拿到错误信息
|
|
11
|
-
- 自主使用工具: agent 自主判断使用什么工具, 是读文件还是写文件, 是 grep 搜索代码还是执行 shell 命令
|
|
12
|
-
|
|
13
|
-
## Swifty 的 5 层架构
|
|
14
|
-
|
|
15
|
-
1. 交互层: cli、command、skill
|
|
16
|
-
2. 引擎层: 对话、循环、提示词
|
|
17
|
-
3. 工具层: 工具、mcp、hook
|
|
18
|
-
4. 记忆层: 上下文、会话、自动记忆
|
|
19
|
-
5. 安全层: 沙箱、权限、HITL (Human-in-the-Loop)
|
|
20
|
-
|
|
21
|
-
## AI Coding
|
|
22
|
-
|
|
23
|
-
- spec.md 需求文档
|
|
24
|
-
- plan.md 技术方案
|
|
25
|
-
- task.md、checklist.md 任务清单
|
package/docs/ch10.md
DELETED
|
@@ -1,122 +0,0 @@
|
|
|
1
|
-
# Slash Command
|
|
2
|
-
|
|
3
|
-
Slash Command: 以 / 开头的输入会被命令解析器拦截
|
|
4
|
-
|
|
5
|
-
## 命令的分类
|
|
6
|
-
|
|
7
|
-
<!-- 源码: src/commands/commands.ts -->
|
|
8
|
-
|
|
9
|
-
- local: 不参与 agent loop
|
|
10
|
-
- local_ui: 不参与 agent loop, 需要重新渲染 UI
|
|
11
|
-
- prompt: 参与 agent loop, CLI 负责构造 prompt
|
|
12
|
-
- skill_fork: skill 加载后自动注册为 Slash Command (prompt 命令)
|
|
13
|
-
|
|
14
|
-
> 不参与 agent loop != 不调用 LLM API
|
|
15
|
-
>
|
|
16
|
-
> 例如 /compact 命令调用 LLM API 生成摘要, 但是不参与 agent loop
|
|
17
|
-
|
|
18
|
-
命令拦截时机: 消息发送给 LLM API 前, 用户按下回车, 先判断输入是不是命令, 如果是命令则走命令处理逻辑, 不是命令才发送给 LLM API
|
|
19
|
-
|
|
20
|
-
## local 命令
|
|
21
|
-
|
|
22
|
-
`/help` 打印帮助信息
|
|
23
|
-
|
|
24
|
-
<!-- 源码: src/commands/commands.ts -->
|
|
25
|
-
|
|
26
|
-
```txt
|
|
27
|
-
- /help, /h, /? 打印帮助信息
|
|
28
|
-
- /compact, /c 压缩上下文
|
|
29
|
-
- /clear 清除对话历史
|
|
30
|
-
- /plan, /p 切换到 plan 模式
|
|
31
|
-
- /session 会话管理
|
|
32
|
-
- /memory 记忆管理
|
|
33
|
-
- /permission 权限管理
|
|
34
|
-
- /status, /s 打印状态信息
|
|
35
|
-
- /review 代码审查
|
|
36
|
-
|
|
37
|
-
输入 /help <命令名> 查看详细用法
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
`/compact` 手动触发上下文压缩, `/compact [description]` 指定上下文保留重点; 如果当前上下文窗口 <= 5k token, 直接提示无需压缩
|
|
41
|
-
|
|
42
|
-
<!-- 源码: src/commands/commands.ts, 部分子命令未实现, TODO -->
|
|
43
|
-
|
|
44
|
-
`/session` 会话信息
|
|
45
|
-
|
|
46
|
-
- `/session` 打印当前会话信息
|
|
47
|
-
- `/session list` 打印历史会话列表
|
|
48
|
-
- `/session resume <id>` 切换到指定 ID 的会话
|
|
49
|
-
- `/session new` 开启新会话
|
|
50
|
-
- `/session delete <id>` 删除指定 ID 的会话
|
|
51
|
-
|
|
52
|
-
`/memory` 记忆管理
|
|
53
|
-
|
|
54
|
-
- `/memory list` 打印记忆列表
|
|
55
|
-
- `/memory add <content>` 添加一条记忆
|
|
56
|
-
- `/memory clear` 清空记忆, 需要用户确认
|
|
57
|
-
|
|
58
|
-
`/permission` 权限管理
|
|
59
|
-
|
|
60
|
-
- `/permission` 打印权限模式和生效的权限规则数量
|
|
61
|
-
- `/permission mode <plan | default | acceptEdits | bypassPermissions>` 切换权限模式
|
|
62
|
-
- `/permission rules` 打印生效的权限规则列表
|
|
63
|
-
- `/permission add <rule> <effect>` 添加一条本地权限规则
|
|
64
|
-
- `/permission reset` 重置本地权限规则
|
|
65
|
-
|
|
66
|
-
`/status` 打印当前状态
|
|
67
|
-
|
|
68
|
-
<!-- 源码: src/commands/commands.ts -->
|
|
69
|
-
|
|
70
|
-
```txt
|
|
71
|
-
Swifty Status
|
|
72
|
-
──────────────
|
|
73
|
-
Mode: default
|
|
74
|
-
Tokens: 45230 in / 1200 out
|
|
75
|
-
Tools: 6 enabled
|
|
76
|
-
Memories: 8 entries
|
|
77
|
-
Model: claude-sonnet-4-20250514
|
|
78
|
-
Directory: /path/to/project
|
|
79
|
-
```
|
|
80
|
-
|
|
81
|
-
`/skills` skill 管理
|
|
82
|
-
|
|
83
|
-
<!-- 源码: src/commands/commands.ts -->
|
|
84
|
-
|
|
85
|
-
- `/skills list` 打印 skill 列表
|
|
86
|
-
- `/skills info <name>` 打印指定 skill 的 frontmatter 和路径
|
|
87
|
-
- `/skills reload` 重新扫描并加载所有 skill
|
|
88
|
-
|
|
89
|
-
`/mcp` MCP 服务器连接状态
|
|
90
|
-
|
|
91
|
-
<!-- 源码: src/commands/commands.ts -->
|
|
92
|
-
|
|
93
|
-
- `/mcp` 打印 MCP 服务器连接状态
|
|
94
|
-
|
|
95
|
-
`/code-review` 代码审查 agent team 管理
|
|
96
|
-
|
|
97
|
-
<!-- 源码: src/commands/commands.ts -->
|
|
98
|
-
|
|
99
|
-
- `/code-review`, `/cr` 管理代码审查 agent team
|
|
100
|
-
- `/cr create` TODO
|
|
101
|
-
- `/cr add <name>` TODO
|
|
102
|
-
- `/cr remove <name>` TODO
|
|
103
|
-
- `/cr list` TODO
|
|
104
|
-
- `/cr status` TODO
|
|
105
|
-
|
|
106
|
-
## local_ui 命令
|
|
107
|
-
|
|
108
|
-
<!-- 源码: src/commands/commands.ts -->
|
|
109
|
-
|
|
110
|
-
- `/clear` 开启新对话, 关闭当前会话, 持久化到磁盘的 jsonl 会话日志
|
|
111
|
-
- `/compact, /c` 强制上下文压缩
|
|
112
|
-
- `/plan, /p` 切换 plan 模式 (toggle), `/plan [description]` 指定任务描述
|
|
113
|
-
- `/quit, /exit, /q` 退出 Swifty
|
|
114
|
-
- `/resume, /r` 恢复以前的会话
|
|
115
|
-
- `/rewind` 回退对话到以前的检查点
|
|
116
|
-
- `/worktree, /wt` 管理 git worktree
|
|
117
|
-
|
|
118
|
-
## prompt 命令
|
|
119
|
-
|
|
120
|
-
<!-- 源码: src/commands/commands.ts -->
|
|
121
|
-
|
|
122
|
-
`/review` CLI 将预设的代码审查 prompt 发送给 LLM API, 分析未提交的代码变更, `/review [description]` 指定代码审查重点; prompt 命令消耗 token
|