@musistudio/claude-code-router 3.0.0 → 3.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.
@@ -1,18 +1,18 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Li=Object.create;var ao=Object.defineProperty;var Fi=Object.getOwnPropertyDescriptor;var Ki=Object.getOwnPropertyNames;var Bi=Object.getPrototypeOf,zi=Object.prototype.hasOwnProperty;var Ui=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ki(e))!zi.call(s,n)&&n!==t&&ao(s,n,{get:()=>e[n],enumerable:!(r=Fi(e,n))||r.enumerable});return s};var co=(s,e,t)=>(t=s!=null?Li(Bi(s)):{},Ui(e||!s||!s.__esModule?ao(t,"default",{value:s,enumerable:!0}):t,s));var Ti=require("node:child_process"),Xs=require("node:crypto"),_e=require("node:fs"),Ei=co(require("node:os")),Yn=co(require("node:path"));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 Zs=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return Zs=s.randomUUID.bind(s),s.randomUUID();let e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function zr(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}var Ur=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 A=class extends Error{},N=class s extends A{constructor(e,t,r,n){super(`${s.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,r){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new Se({message:r,cause:Ur(t)});let o=t?.error;return e===400?new wt(e,o,r,n):e===401?new Pt(e,o,r,n):e===403?new It(e,o,r,n):e===404?new xt(e,o,r,n):e===409?new vt(e,o,r,n):e===422?new St(e,o,r,n):e===429?new Rt(e,o,r,n):e>=500?new kt(e,o,r,n):new s(e,o,r,n)}},F=class extends N{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Se=class extends N{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Re=class extends Se{constructor({message:e}={}){super({message:e??"Request timed out."})}},wt=class extends N{},Pt=class extends N{},It=class extends N{},xt=class extends N{},vt=class extends N{},St=class extends N{},Rt=class extends N{},kt=class extends N{},Ct=class extends A{constructor(){super("Could not parse response content as the length limit was reached")}},Tt=class extends A{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},le=class extends Error{constructor(e){super(e)}},We=class extends N{constructor(e,t,r){let n="OAuth2 authentication error",o;if(t&&typeof t=="object"){let i=t;o=i.error;let c=i.error_description;c&&typeof c=="string"?n=c:o&&(n=o)}super(e,t,n,r),this.error_code=o}},qr=class extends A{constructor(e,t,r){super(e),this.provider=t,this.cause=r}};var Di=/^[a-z][a-z0-9+.-]*:/i,lo=s=>Di.test(s),V=s=>(V=Array.isArray,V(s)),en=V;function ps(s){return typeof s!="object"?{}:s??{}}function tn(s){if(!s)return!0;for(let e in s)return!1;return!0}function uo(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function Dr(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var ho=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new A(`${s} must be an integer`);if(e<0)throw new A(`${s} must be a positive integer`);return e};var mo=s=>{try{return JSON.parse(s)}catch{return}};var ue=s=>new Promise(e=>setTimeout(e,s));var ke="6.44.0";var _o=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Hi(){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 Wi=()=>{let s=Hi();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":po(Deno.build.os),"X-Stainless-Arch":fo(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":po(globalThis.process.platform??"unknown"),"X-Stainless-Arch":fo(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Ji();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Ji(){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,i=r[3]||0;return{browser:e,version:`${n}.${o}.${i}`}}}return null}var fo=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",po=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"),go,yo=()=>go??(go=Wi());function gs(){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 rn(...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 _s(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return rn({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function sn(s){if(s[Symbol.asyncIterator])return s;let e=s.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function nn(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}let e=s.getReader(),t=e.cancel();e.releaseLock(),await t}var bo=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var on="RFC3986",an=s=>String(s),cn={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:an},wo="RFC1738";var ys=(s,e)=>(ys=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),ys(s,e)),de=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var ln=1024,Po=(s,e,t,r,n)=>{if(s.length===0)return s;let o=s;if(typeof s=="symbol"?o=Symbol.prototype.toString.call(s):typeof s!="string"&&(o=String(s)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let i="";for(let c=0;c<o.length;c+=ln){let d=o.length>=ln?o.slice(c,c+ln):o,h=[];for(let g=0;g<d.length;++g){let m=d.charCodeAt(g);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||n===wo&&(m===40||m===41)){h[h.length]=d.charAt(g);continue}if(m<128){h[h.length]=de[m];continue}if(m<2048){h[h.length]=de[192|m>>6]+de[128|m&63];continue}if(m<55296||m>=57344){h[h.length]=de[224|m>>12]+de[128|m>>6&63]+de[128|m&63];continue}g+=1,m=65536+((m&1023)<<10|d.charCodeAt(g)&1023),h[h.length]=de[240|m>>18]+de[128|m>>12&63]+de[128|m>>6&63]+de[128|m&63]}i+=h.join("")}return i};function Io(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function un(s,e){if(V(s)){let t=[];for(let r=0;r<s.length;r+=1)t.push(e(s[r]));return t}return e(s)}var vo={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},So=function(s,e){Array.prototype.push.apply(s,V(e)?e:[e])},xo,z={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Po,encodeValuesOnly:!1,format:on,formatter:an,indices:!1,serializeDate(s){return(xo??(xo=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function Vi(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var dn={};function Ro(s,e,t,r,n,o,i,c,d,h,g,m,_,f,y,w,O,E){let b=s,S=E,k=0,H=!1;for(;(S=S.get(dn))!==void 0&&!H;){let $=S.get(s);if(k+=1,typeof $<"u"){if($===k)throw new RangeError("Cyclic object value");H=!0}typeof S.get(dn)>"u"&&(k=0)}if(typeof h=="function"?b=h(e,b):b instanceof Date?b=_?.(b):t==="comma"&&V(b)&&(b=un(b,function($){return $ instanceof Date?_?.($):$})),b===null){if(o)return d&&!w?d(e,z.encoder,O,"key",f):e;b=""}if(Vi(b)||Io(b)){if(d){let $=w?e:d(e,z.encoder,O,"key",f);return[y?.($)+"="+y?.(d(b,z.encoder,O,"value",f))]}return[y?.(e)+"="+y?.(String(b))]}let L=[];if(typeof b>"u")return L;let q;if(t==="comma"&&V(b))w&&d&&(b=un(b,d)),q=[{value:b.length>0?b.join(",")||null:void 0}];else if(V(h))q=h;else{let $=Object.keys(b);q=g?$.sort(g):$}let C=c?String(e).replace(/\./g,"%2E"):String(e),T=r&&V(b)&&b.length===1?C+"[]":C;if(n&&V(b)&&b.length===0)return T+"[]";for(let $=0;$<q.length;++$){let M=q[$],ce=typeof M=="object"&&typeof M.value<"u"?M.value:b[M];if(i&&ce===null)continue;let Fr=m&&c?M.replace(/\./g,"%2E"):M,ms=V(b)?typeof t=="function"?t(T,Fr):T:T+(m?"."+Fr:"["+Fr+"]");E.set(s,k);let fs=new WeakMap;fs.set(dn,E),So(L,Ro(ce,ms,t,r,n,o,i,c,t==="comma"&&w&&V(b)?null:d,h,g,m,_,f,y,w,O,fs))}return L}function Xi(s=z){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||z.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=on;if(typeof s.format<"u"){if(!ys(cn,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=cn[t],n=z.filter;(typeof s.filter=="function"||V(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in vo?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=z.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:z.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:z.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:z.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:z.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?z.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:z.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:z.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:z.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:z.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:z.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:z.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:z.strictNullHandling}}function ko(s,e={}){let t=s,r=Xi(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):V(r.filter)&&(o=r.filter,n=o);let i=[];if(typeof t!="object"||t===null)return"";let c=vo[r.arrayFormat],d=c==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let h=new WeakMap;for(let _=0;_<n.length;++_){let f=n[_];r.skipNulls&&t[f]===null||So(i,Ro(t[f],f,c,d,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,h))}let g=i.join(r.delimiter),m=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?m+="utf8=%26%2310003%3B&":m+="utf8=%E2%9C%93&"),g.length>0?m+g:""}function Co(s){return ko(s,{arrayFormat:"brackets"})}function $o(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 To;function Et(s){let e;return(To??(e=new globalThis.TextEncoder,To=e.encode.bind(e)))(s)}var Eo;function hn(s){let e;return(Eo??(e=new globalThis.TextDecoder,Eo=e.decode.bind(e)))(s)}var ee,te,Je=class{constructor(){ee.set(this,void 0),te.set(this,void 0),P(this,ee,new Uint8Array,"f"),P(this,te,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Et(e):e;P(this,ee,$o([u(this,ee,"f"),t]),"f");let r=[],n;for(;(n=Qi(u(this,ee,"f"),u(this,te,"f")))!=null;){if(n.carriage&&u(this,te,"f")==null){P(this,te,n.index,"f");continue}if(u(this,te,"f")!=null&&(n.index!==u(this,te,"f")+1||n.carriage)){r.push(hn(u(this,ee,"f").subarray(0,u(this,te,"f")-1))),P(this,ee,u(this,ee,"f").subarray(u(this,te,"f")),"f"),P(this,te,null,"f");continue}let o=u(this,te,"f")!==null?n.preceding-1:n.preceding,i=hn(u(this,ee,"f").subarray(0,o));r.push(i),P(this,ee,u(this,ee,"f").subarray(n.index),"f"),P(this,te,null,"f")}return r}flush(){return u(this,ee,"f").length?this.decode(`
3
- `):[]}};ee=new WeakMap,te=new WeakMap;Je.NEWLINE_CHARS=new Set([`
4
- `,"\r"]);Je.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Qi(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 Oo(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 bs={off:0,error:200,warn:300,info:400,debug:500},mn=(s,e,t)=>{if(s){if(uo(bs,s))return s;j(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(bs))}`)}};function Hr(){}function As(s,e,t){return!e||bs[s]>bs[t]?Hr:e[s].bind(e)}var Zi={error:Hr,warn:Hr,info:Hr,debug:Hr},No=new WeakMap;function j(s){let e=s.logger,t=s.logLevel??"off";if(!e)return Zi;let r=No.get(e);if(r&&r[0]===t)return r[1];let n={error:As("error",e,t),warn:As("warn",e,t),info:As("info",e,t),debug:As("debug",e,t)};return No.set(e,[t,n]),n}var ye=s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s);var Wr,he=class s{constructor(e,t,r){this.iterator=e,Wr.set(this,void 0),this.controller=t,P(this,Wr,r,"f")}static fromSSEResponse(e,t,r,n){let o=!1,i=r?j(r):console;async function*c(){if(o)throw new A("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let d=!1;try{for await(let h of ea(e,t))if(!d){if(h.data.startsWith("[DONE]")){d=!0;continue}if(h.event===null||!h.event.startsWith("thread.")){let g;try{g=JSON.parse(h.data)}catch(m){throw i.error("Could not parse message into JSON:",h.data),i.error("From chunk:",h.raw),m}if(g&&g.error)throw new N(void 0,g.error,void 0,e.headers);yield n?{event:h.event,data:g}:g}else{let g;try{g=JSON.parse(h.data)}catch(m){throw console.error("Could not parse message into JSON:",h.data),console.error("From chunk:",h.raw),m}if(h.event=="error")throw new N(void 0,g.error,g.message,void 0);yield{event:h.event,data:g}}}d=!0}catch(h){if(zr(h))return;throw h}finally{d||t.abort()}}return new s(c,t,r)}static fromReadableStream(e,t,r){let n=!1;async function*o(){let c=new Je,d=sn(e);for await(let h of d)for(let g of c.decode(h))yield g;for(let h of c.flush())yield h}async function*i(){if(n)throw new A("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let c=!1;try{for await(let d of o())c||d&&(yield JSON.parse(d));c=!0}catch(d){if(zr(d))return;throw d}finally{c||t.abort()}}return new s(i,t,r)}[(Wr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=o=>({next:()=>{if(o.length===0){let i=r.next();e.push(i),t.push(i)}return o.shift()}});return[new s(()=>n(e),this.controller,u(this,Wr,"f")),new s(()=>n(t),this.controller,u(this,Wr,"f"))]}toReadableStream(){let e=this,t;return rn({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:n,done:o}=await t.next();if(o)return r.close();let i=Et(JSON.stringify(n)+`
5
- `);r.enqueue(i)}catch(n){r.error(n)}},async cancel(){await t.return?.()}})}};async function*ea(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new A("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new A("Attempted to iterate over a response with no body");let t=new fn,r=new Je,n=sn(s.body);for await(let o of ta(n))for(let i of r.decode(o)){let c=t.decode(i);c&&(yield c)}for(let o of r.flush()){let i=t.decode(o);i&&(yield i)}}async function*ta(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"?Et(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let o;for(;(o=Oo(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var fn=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(`
6
- `),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]=ra(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function ra(s,e){let t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}async function ws(s,e){let{response:t,requestLogID:r,retryOfRequestLogID:n,startTime:o}=e,i=await(async()=>{if(e.options.stream)return j(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):he.fromSSEResponse(t,e.controller,s,e.options.__synthesizeEventData);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let d=t.headers.get("content-type")?.split(";")[0]?.trim();if(d?.includes("application/json")||d?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;let _=await t.json();return pn(_,t)}return await t.text()})();return j(s).debug(`[${r}] response parsed`,ye({retryOfRequestLogID:n,url:t.url,status:t.status,body:i,durationMs:Date.now()-o})),i}function pn(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,Ge=class s extends Promise{constructor(e,t,r=ws){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)=>pn(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 Ps,$t=class{constructor(e,t,r,n){Ps.set(this,void 0),P(this,Ps,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 A("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await u(this,Ps,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ps=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Gr=class extends Ge{constructor(e,t,r){super(e,t,async(n,o)=>new r(n,o.response,await ws(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},X=class extends $t{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}},x=class extends $t{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:{...ps(this.options.query),after:t}}:null}},v=class extends $t{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:{...ps(this.options.query),after:e}}:null}},K=class extends $t{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:{...ps(this.options.query),after:e}}:null}};var na={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},oa="urn:ietf:params:oauth:grant-type:token-exchange",Is=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=t??gs()}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:oa,subject_token:e,subject_token_type:na[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 c=await r.text(),d;try{d=JSON.parse(c)}catch{}throw r.status===400||r.status===401||r.status===403?new We(r.status,d,r.headers):N.generate(r.status,d,`Token exchange failed with status ${r.status}`,r.headers)}let n=await r.json(),o=n.expires_in||3600,i=Date.now()+o*1e3;return this.cachedToken={token:n.access_token,expiresAt:i},n.access_token}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 yn=()=>{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 Ot(s,e,t){return yn(),new File(s,e??"unknown_file",t)}function Vr(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 xs=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",Ce=async(s,e)=>gn(s.body)?{...s,body:await jo(s.body,e)}:s,Y=async(s,e)=>({...s,body:await jo(s.body,e)}),Mo=new WeakMap;function ia(s){let e=typeof s=="function"?s:s.fetch,t=Mo.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 Mo.set(e,r),r}var jo=async(s,e)=>{if(!await ia(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])=>_n(t,r,n))),t},Lo=s=>s instanceof Blob&&"name"in s,aa=s=>typeof s=="object"&&s!==null&&(s instanceof Response||xs(s)||Lo(s)),gn=s=>{if(aa(s))return!0;if(Array.isArray(s))return s.some(gn);if(s&&typeof s=="object"){for(let e in s)if(gn(s[e]))return!0}return!1},_n=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,Ot([await t.blob()],Vr(t)));else if(xs(t))s.append(e,Ot([await new Response(_s(t)).blob()],Vr(t)));else if(Lo(t))s.append(e,t,Vr(t));else if(Array.isArray(t))await Promise.all(t.map(r=>_n(s,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,n])=>_n(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 Fo=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",ca=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&Fo(s),la=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function vs(s,e,t){if(yn(),s=await s,ca(s))return s instanceof File?s:Ot([await s.arrayBuffer()],s.name);if(la(s)){let n=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),Ot(await An(n),e,t)}let r=await An(s);if(e||(e=Vr(s)),!t?.type){let n=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(t={...t,type:n})}return Ot(r,e,t)}async function An(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(Fo(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(xs(s))for await(let t of s)e.push(...await An(t));else{let t=s?.constructor?.name;throw new Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${ua(s)}`)}return e}function ua(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}var l=class{constructor(e){this._client=e}};function Bo(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Ko=Object.freeze(Object.create(null)),ha=(s=Bo)=>function(t,...r){if(t.length===1)return t[0];let n=!1,o=[],i=t.reduce((g,m,_)=>{/[?#]/.test(m)&&(n=!0);let f=r[_],y=(n?encodeURIComponent:s)(""+f);return _!==r.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??Ko)??Ko)?.toString)&&(y=f+"",o.push({start:g.length+m.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),g+m+(_===r.length?"":y)},""),c=i.split(/[?#]/,1)[0],d=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,h;for(;(h=d.exec(c))!==null;)o.push({start:h.index,length:h[0].length,error:`Value "${h[0]}" can't be safely passed as a path parameter`});if(o.sort((g,m)=>g.start-m.start),o.length>0){let g=0,m=o.reduce((_,f)=>{let y=" ".repeat(f.start-g),w="^".repeat(f.length);return g=f.start+f.length,_+y+w},"");throw new A(`Path parameters result in path with invalid segments:
2
+ "use strict";var Di=Object.create;var mo=Object.defineProperty;var Hi=Object.getOwnPropertyDescriptor;var Wi=Object.getOwnPropertyNames;var Ji=Object.getPrototypeOf,Gi=Object.prototype.hasOwnProperty;var Vi=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Wi(e))!Gi.call(s,n)&&n!==t&&mo(s,n,{get:()=>e[n],enumerable:!(r=Hi(e,n))||r.enumerable});return s};var fo=(s,e,t)=>(t=s!=null?Di(Ji(s)):{},Vi(e||!s||!s.__esModule?mo(t,"default",{value:s,enumerable:!0}):t,s));var ji=require("node:child_process"),Zs=require("node:crypto"),_e=require("node:fs"),Li=fo(require("node:os")),ro=fo(require("node:path"));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 rn=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return rn=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 Dr(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}var Hr=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 A=class extends Error{},N=class s extends A{constructor(e,t,r,n){super(`${s.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,r){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new Se({message:r,cause:Hr(t)});let o=t?.error;return e===400?new It(e,o,r,n):e===401?new vt(e,o,r,n):e===403?new xt(e,o,r,n):e===404?new St(e,o,r,n):e===409?new Rt(e,o,r,n):e===422?new kt(e,o,r,n):e===429?new Ct(e,o,r,n):e>=500?new Tt(e,o,r,n):new s(e,o,r,n)}},F=class extends N{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Se=class extends N{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Re=class extends Se{constructor({message:e}={}){super({message:e??"Request timed out."})}},It=class extends N{},vt=class extends N{},xt=class extends N{},St=class extends N{},Rt=class extends N{},kt=class extends N{},Ct=class extends N{},Tt=class extends N{},Et=class extends A{constructor(){super("Could not parse response content as the length limit was reached")}},$t=class extends A{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},ue=class extends Error{constructor(e){super(e)}},Je=class extends N{constructor(e,t,r){let n="OAuth2 authentication error",o;if(t&&typeof t=="object"){let i=t;o=i.error;let c=i.error_description;c&&typeof c=="string"?n=c:o&&(n=o)}super(e,t,n,r),this.error_code=o}},Wr=class extends A{constructor(e,t,r){super(e),this.provider=t,this.cause=r}};var Yi=/^[a-z][a-z0-9+.-]*:/i,po=s=>Yi.test(s),V=s=>(V=Array.isArray,V(s)),sn=V;function _s(s){return typeof s!="object"?{}:s??{}}function nn(s){if(!s)return!0;for(let e in s)return!1;return!0}function go(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function Jr(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var _o=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new A(`${s} must be an integer`);if(e<0)throw new A(`${s} must be a positive integer`);return e};var yo=s=>{try{return JSON.parse(s)}catch{return}};var de=s=>new Promise(e=>setTimeout(e,s));var ke="6.44.0";var Po=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Qi(){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 Zi=()=>{let s=Qi();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":bo(Deno.build.os),"X-Stainless-Arch":Ao(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":bo(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Ao(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=ea();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ea(){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,i=r[3]||0;return{browser:e,version:`${n}.${o}.${i}`}}}return null}var Ao=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",bo=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"),wo,Io=()=>wo??(wo=Zi());function ys(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function on(...s){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...s)}function As(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return on({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function an(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 cn(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 xo=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var ln="RFC3986",un=s=>String(s),dn={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:un},So="RFC1738";var bs=(s,e)=>(bs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),bs(s,e)),he=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var hn=1024,Ro=(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(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let i="";for(let c=0;c<o.length;c+=hn){let d=o.length>=hn?o.slice(c,c+hn):o,h=[];for(let g=0;g<d.length;++g){let m=d.charCodeAt(g);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||n===So&&(m===40||m===41)){h[h.length]=d.charAt(g);continue}if(m<128){h[h.length]=he[m];continue}if(m<2048){h[h.length]=he[192|m>>6]+he[128|m&63];continue}if(m<55296||m>=57344){h[h.length]=he[224|m>>12]+he[128|m>>6&63]+he[128|m&63];continue}g+=1,m=65536+((m&1023)<<10|d.charCodeAt(g)&1023),h[h.length]=he[240|m>>18]+he[128|m>>12&63]+he[128|m>>6&63]+he[128|m&63]}i+=h.join("")}return i};function ko(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function mn(s,e){if(V(s)){let t=[];for(let r=0;r<s.length;r+=1)t.push(e(s[r]));return t}return e(s)}var To={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},Eo=function(s,e){Array.prototype.push.apply(s,V(e)?e:[e])},Co,z={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Ro,encodeValuesOnly:!1,format:ln,formatter:un,indices:!1,serializeDate(s){return(Co??(Co=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function ra(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var fn={};function $o(s,e,t,r,n,o,i,c,d,h,g,m,_,f,y,w,O,E){let b=s,S=E,k=0,H=!1;for(;(S=S.get(fn))!==void 0&&!H;){let $=S.get(s);if(k+=1,typeof $<"u"){if($===k)throw new RangeError("Cyclic object value");H=!0}typeof S.get(fn)>"u"&&(k=0)}if(typeof h=="function"?b=h(e,b):b instanceof Date?b=_?.(b):t==="comma"&&V(b)&&(b=mn(b,function($){return $ instanceof Date?_?.($):$})),b===null){if(o)return d&&!w?d(e,z.encoder,O,"key",f):e;b=""}if(ra(b)||ko(b)){if(d){let $=w?e:d(e,z.encoder,O,"key",f);return[y?.($)+"="+y?.(d(b,z.encoder,O,"value",f))]}return[y?.(e)+"="+y?.(String(b))]}let L=[];if(typeof b>"u")return L;let q;if(t==="comma"&&V(b))w&&d&&(b=mn(b,d)),q=[{value:b.length>0?b.join(",")||null:void 0}];else if(V(h))q=h;else{let $=Object.keys(b);q=g?$.sort(g):$}let C=c?String(e).replace(/\./g,"%2E"):String(e),T=r&&V(b)&&b.length===1?C+"[]":C;if(n&&V(b)&&b.length===0)return T+"[]";for(let $=0;$<q.length;++$){let M=q[$],le=typeof M=="object"&&typeof M.value<"u"?M.value:b[M];if(i&&le===null)continue;let zr=m&&c?M.replace(/\./g,"%2E"):M,ps=V(b)?typeof t=="function"?t(T,zr):T:T+(m?"."+zr:"["+zr+"]");E.set(s,k);let gs=new WeakMap;gs.set(fn,E),Eo(L,$o(le,ps,t,r,n,o,i,c,t==="comma"&&w&&V(b)?null:d,h,g,m,_,f,y,w,O,gs))}return L}function sa(s=z){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||z.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=ln;if(typeof s.format<"u"){if(!bs(dn,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=dn[t],n=z.filter;(typeof s.filter=="function"||V(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in To?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=z.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:z.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:z.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:z.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:z.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?z.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:z.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:z.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:z.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:z.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:z.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:z.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:z.strictNullHandling}}function Oo(s,e={}){let t=s,r=sa(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):V(r.filter)&&(o=r.filter,n=o);let i=[];if(typeof t!="object"||t===null)return"";let c=To[r.arrayFormat],d=c==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let h=new WeakMap;for(let _=0;_<n.length;++_){let f=n[_];r.skipNulls&&t[f]===null||Eo(i,$o(t[f],f,c,d,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,h))}let g=i.join(r.delimiter),m=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?m+="utf8=%26%2310003%3B&":m+="utf8=%E2%9C%93&"),g.length>0?m+g:""}function No(s){return Oo(s,{arrayFormat:"brackets"})}function Lo(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 Mo;function Ot(s){let e;return(Mo??(e=new globalThis.TextEncoder,Mo=e.encode.bind(e)))(s)}var jo;function pn(s){let e;return(jo??(e=new globalThis.TextDecoder,jo=e.decode.bind(e)))(s)}var ee,te,Ge=class{constructor(){ee.set(this,void 0),te.set(this,void 0),P(this,ee,new Uint8Array,"f"),P(this,te,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Ot(e):e;P(this,ee,Lo([u(this,ee,"f"),t]),"f");let r=[],n;for(;(n=oa(u(this,ee,"f"),u(this,te,"f")))!=null;){if(n.carriage&&u(this,te,"f")==null){P(this,te,n.index,"f");continue}if(u(this,te,"f")!=null&&(n.index!==u(this,te,"f")+1||n.carriage)){r.push(pn(u(this,ee,"f").subarray(0,u(this,te,"f")-1))),P(this,ee,u(this,ee,"f").subarray(u(this,te,"f")),"f"),P(this,te,null,"f");continue}let o=u(this,te,"f")!==null?n.preceding-1:n.preceding,i=pn(u(this,ee,"f").subarray(0,o));r.push(i),P(this,ee,u(this,ee,"f").subarray(n.index),"f"),P(this,te,null,"f")}return r}flush(){return u(this,ee,"f").length?this.decode(`
3
+ `):[]}};ee=new WeakMap,te=new WeakMap;Ge.NEWLINE_CHARS=new Set([`
4
+ `,"\r"]);Ge.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function oa(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 Fo(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 Ps={off:0,error:200,warn:300,info:400,debug:500},gn=(s,e,t)=>{if(s){if(go(Ps,s))return s;j(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(Ps))}`)}};function Gr(){}function ws(s,e,t){return!e||Ps[s]>Ps[t]?Gr:e[s].bind(e)}var ia={error:Gr,warn:Gr,info:Gr,debug:Gr},Bo=new WeakMap;function j(s){let e=s.logger,t=s.logLevel??"off";if(!e)return ia;let r=Bo.get(e);if(r&&r[0]===t)return r[1];let n={error:ws("error",e,t),warn:ws("warn",e,t),info:ws("info",e,t),debug:ws("debug",e,t)};return Bo.set(e,[t,n]),n}var ye=s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s);var Vr,me=class s{constructor(e,t,r){this.iterator=e,Vr.set(this,void 0),this.controller=t,P(this,Vr,r,"f")}static fromSSEResponse(e,t,r,n){let o=!1,i=r?j(r):console;async function*c(){if(o)throw new A("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let d=!1;try{for await(let h of aa(e,t))if(!d){if(h.data.startsWith("[DONE]")){d=!0;continue}if(h.event===null||!h.event.startsWith("thread.")){let g;try{g=JSON.parse(h.data)}catch(m){throw i.error("Could not parse message into JSON:",h.data),i.error("From chunk:",h.raw),m}if(g&&g.error)throw new N(void 0,g.error,void 0,e.headers);yield n?{event:h.event,data:g}:g}else{let g;try{g=JSON.parse(h.data)}catch(m){throw console.error("Could not parse message into JSON:",h.data),console.error("From chunk:",h.raw),m}if(h.event=="error")throw new N(void 0,g.error,g.message,void 0);yield{event:h.event,data:g}}}d=!0}catch(h){if(Dr(h))return;throw h}finally{d||t.abort()}}return new s(c,t,r)}static fromReadableStream(e,t,r){let n=!1;async function*o(){let c=new Ge,d=an(e);for await(let h of d)for(let g of c.decode(h))yield g;for(let h of c.flush())yield h}async function*i(){if(n)throw new A("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let c=!1;try{for await(let d of o())c||d&&(yield JSON.parse(d));c=!0}catch(d){if(Dr(d))return;throw d}finally{c||t.abort()}}return new s(i,t,r)}[(Vr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=o=>({next:()=>{if(o.length===0){let i=r.next();e.push(i),t.push(i)}return o.shift()}});return[new s(()=>n(e),this.controller,u(this,Vr,"f")),new s(()=>n(t),this.controller,u(this,Vr,"f"))]}toReadableStream(){let e=this,t;return on({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:n,done:o}=await t.next();if(o)return r.close();let i=Ot(JSON.stringify(n)+`
5
+ `);r.enqueue(i)}catch(n){r.error(n)}},async cancel(){await t.return?.()}})}};async function*aa(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new A("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new A("Attempted to iterate over a response with no body");let t=new _n,r=new Ge,n=an(s.body);for await(let o of ca(n))for(let i of r.decode(o)){let c=t.decode(i);c&&(yield c)}for(let o of r.flush()){let i=t.decode(o);i&&(yield i)}}async function*ca(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"?Ot(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let o;for(;(o=Fo(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var _n=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
6
+ `),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]=la(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function la(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,i=await(async()=>{if(e.options.stream)return j(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):me.fromSSEResponse(t,e.controller,s,e.options.__synthesizeEventData);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let d=t.headers.get("content-type")?.split(";")[0]?.trim();if(d?.includes("application/json")||d?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;let _=await t.json();return yn(_,t)}return await t.text()})();return j(s).debug(`[${r}] response parsed`,ye({retryOfRequestLogID:n,url:t.url,status:t.status,body:i,durationMs:Date.now()-o})),i}function yn(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Xr,Ve=class s extends Promise{constructor(e,t,r=Is){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=r,Xr.set(this,void 0),P(this,Xr,e,"f")}_thenUnwrap(e){return new s(u(this,Xr,"f"),this.responsePromise,async(t,r)=>yn(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(u(this,Xr,"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)}};Xr=new WeakMap;var vs,Nt=class{constructor(e,t,r,n){vs.set(this,void 0),P(this,vs,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 A("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await u(this,vs,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(vs=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Yr=class extends Ve{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}},X=class extends Nt{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},v=class extends Nt{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{..._s(this.options.query),after:t}}:null}},x=class extends Nt{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{..._s(this.options.query),after:e}}:null}},B=class extends Nt{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.next=r.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{..._s(this.options.query),after:e}}:null}};var da={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},ha="urn:ietf:params:oauth:grant-type:token-exchange",xs=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=t??ys()}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:ha,subject_token:e,subject_token_type:da[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 c=await r.text(),d;try{d=JSON.parse(c)}catch{}throw r.status===400||r.status===401||r.status===403?new Je(r.status,d,r.headers):N.generate(r.status,d,`Token exchange failed with status ${r.status}`,r.headers)}let n=await r.json(),o=n.expires_in||3600,i=Date.now()+o*1e3;return this.cachedToken={token:n.access_token,expiresAt:i},n.access_token}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 wn=()=>{if(typeof File>"u"){let{process:s}=globalThis,e=typeof s?.versions?.node=="string"&&parseInt(s.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Mt(s,e,t){return wn(),new File(s,e??"unknown_file",t)}function Qr(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 Ss=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",Ce=async(s,e)=>An(s.body)?{...s,body:await zo(s.body,e)}:s,Y=async(s,e)=>({...s,body:await zo(s.body,e)}),Ko=new WeakMap;function ma(s){let e=typeof s=="function"?s:s.fetch,t=Ko.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 Ko.set(e,r),r}var zo=async(s,e)=>{if(!await ma(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])=>bn(t,r,n))),t},Uo=s=>s instanceof Blob&&"name"in s,fa=s=>typeof s=="object"&&s!==null&&(s instanceof Response||Ss(s)||Uo(s)),An=s=>{if(fa(s))return!0;if(Array.isArray(s))return s.some(An);if(s&&typeof s=="object"){for(let e in s)if(An(s[e]))return!0}return!1},bn=async(s,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")s.append(e,String(t));else if(t instanceof Response)s.append(e,Mt([await t.blob()],Qr(t)));else if(Ss(t))s.append(e,Mt([await new Response(As(t)).blob()],Qr(t)));else if(Uo(t))s.append(e,t,Qr(t));else if(Array.isArray(t))await Promise.all(t.map(r=>bn(s,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,n])=>bn(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 qo=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",pa=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&qo(s),ga=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function Rs(s,e,t){if(wn(),s=await s,pa(s))return s instanceof File?s:Mt([await s.arrayBuffer()],s.name);if(ga(s)){let n=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),Mt(await Pn(n),e,t)}let r=await Pn(s);if(e||(e=Qr(s)),!t?.type){let n=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(t={...t,type:n})}return Mt(r,e,t)}async function Pn(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(qo(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(Ss(s))for await(let t of s)e.push(...await Pn(t));else{let t=s?.constructor?.name;throw new Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${_a(s)}`)}return e}function _a(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}var l=class{constructor(e){this._client=e}};function Ho(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Do=Object.freeze(Object.create(null)),Aa=(s=Ho)=>function(t,...r){if(t.length===1)return t[0];let n=!1,o=[],i=t.reduce((g,m,_)=>{/[?#]/.test(m)&&(n=!0);let f=r[_],y=(n?encodeURIComponent:s)(""+f);return _!==r.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??Do)??Do)?.toString)&&(y=f+"",o.push({start:g.length+m.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),g+m+(_===r.length?"":y)},""),c=i.split(/[?#]/,1)[0],d=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,h;for(;(h=d.exec(c))!==null;)o.push({start:h.index,length:h[0].length,error:`Value "${h[0]}" can't be safely passed as a path parameter`});if(o.sort((g,m)=>g.start-m.start),o.length>0){let g=0,m=o.reduce((_,f)=>{let y=" ".repeat(f.start-g),w="^".repeat(f.length);return g=f.start+f.length,_+y+w},"");throw new A(`Path parameters result in path with invalid segments:
7
7
  ${o.map(_=>_.error).join(`
8
8
  `)}
9
9
  ${i}
10
- ${m}`)}return i},a=ha(Bo);var Ve=class extends l{list(e,t={},r){return this._client.getAPIList(a`/chat/completions/${e}/messages`,x,{query:t,...r,__security:{bearerAuth:!0}})}};function Xr(s){return s!==void 0&&"function"in s&&s.function!==void 0}function Yr(s){return s?.$brand==="auto-parseable-response-format"}function Xe(s){return s?.$brand==="auto-parseable-tool"}function Uo(s,e){return!e||!bn(e)?{...s,choices:s.choices.map(t=>(Do(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Qr(s,e)}function Qr(s,e){let t=s.choices.map(r=>{if(r.finish_reason==="length")throw new Ct;if(r.finish_reason==="content_filter")throw new Tt;return Do(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(n=>pa(e,n))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?fa(e,r.message.content):null}}});return{...s,choices:t}}function fa(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 pa(s,e){let t=s.tools?.find(r=>Xr(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Xe(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function qo(s,e){if(!s||!("tools"in s)||!s.tools)return!1;let t=s.tools?.find(r=>Xr(r)&&r.function?.name===e.function.name);return Xr(t)&&(Xe(t)||t?.function.strict||!1)}function bn(s){return Yr(s.response_format)?!0:s.tools?.some(e=>Xe(e)||e.type==="function"&&e.function.strict===!0)??!1}function Do(s){for(let e of s||[])if(e.type!=="function")throw new A(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Ho(s){for(let e of s??[]){if(e.type!=="function")throw new A(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new A(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Nt=s=>s?.role==="assistant",wn=s=>s?.role==="tool";var Pn,Ss,Rs,Zr,es,ks,ts,Ae,rs,Cs,Ts,Mt,Wo,Te=class{constructor(){Pn.add(this),this.controller=new AbortController,Ss.set(this,void 0),Rs.set(this,()=>{}),Zr.set(this,()=>{}),es.set(this,void 0),ks.set(this,()=>{}),ts.set(this,()=>{}),Ae.set(this,{}),rs.set(this,!1),Cs.set(this,!1),Ts.set(this,!1),Mt.set(this,!1),P(this,Ss,new Promise((e,t)=>{P(this,Rs,e,"f"),P(this,Zr,t,"f")}),"f"),P(this,es,new Promise((e,t)=>{P(this,ks,e,"f"),P(this,ts,t,"f")}),"f"),u(this,Ss,"f").catch(()=>{}),u(this,es,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},u(this,Pn,"m",Wo).bind(this))},0)}_connected(){this.ended||(u(this,Rs,"f").call(this),this._emit("connect"))}get ended(){return u(this,rs,"f")}get errored(){return u(this,Cs,"f")}get aborted(){return u(this,Ts,"f")}abort(){this.controller.abort()}on(e,t){return(u(this,Ae,"f")[e]||(u(this,Ae,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=u(this,Ae,"f")[e];if(!r)return this;let n=r.findIndex(o=>o.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(u(this,Ae,"f")[e]||(u(this,Ae,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{P(this,Mt,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){P(this,Mt,!0,"f"),await u(this,es,"f")}_emit(e,...t){if(u(this,rs,"f"))return;e==="end"&&(P(this,rs,!0,"f"),u(this,ks,"f").call(this));let r=u(this,Ae,"f")[e];if(r&&(u(this,Ae,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!u(this,Mt,"f")&&!r?.length&&Promise.reject(n),u(this,Zr,"f").call(this,n),u(this,ts,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!u(this,Mt,"f")&&!r?.length&&Promise.reject(n),u(this,Zr,"f").call(this,n),u(this,ts,"f").call(this,n),this._emit("end")}}_emitFinal(){}};Ss=new WeakMap,Rs=new WeakMap,Zr=new WeakMap,es=new WeakMap,ks=new WeakMap,ts=new WeakMap,Ae=new WeakMap,rs=new WeakMap,Cs=new WeakMap,Ts=new WeakMap,Mt=new WeakMap,Pn=new WeakSet,Wo=function(e){if(P(this,Cs,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new F),e instanceof F)return P(this,Ts,!0,"f"),this._emit("abort",e);if(e instanceof A)return this._emit("error",e);if(e instanceof Error){let t=new A(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new A(String(e)))};function Jo(s){return typeof s.parse=="function"}var Z,In,Es,xn,vn,Sn,Go,Vo,ga=10,jt=class extends Te{constructor(){super(...arguments),Z.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),wn(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Nt(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 A("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),u(this,Z,"m",In).call(this)}async finalMessage(){return await this.done(),u(this,Z,"m",Es).call(this)}async finalFunctionToolCall(){return await this.done(),u(this,Z,"m",xn).call(this)}async finalFunctionToolCallResult(){return await this.done(),u(this,Z,"m",vn).call(this)}async totalUsage(){return await this.done(),u(this,Z,"m",Sn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=u(this,Z,"m",Es).call(this);t&&this._emit("finalMessage",t);let r=u(this,Z,"m",In).call(this);r&&this._emit("finalContent",r);let n=u(this,Z,"m",xn).call(this);n&&this._emit("finalFunctionToolCall",n);let o=u(this,Z,"m",vn).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",u(this,Z,"m",Sn).call(this))}async _createChatCompletion(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),u(this,Z,"m",Go).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Qr(o,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){let n="tool",{tool_choice:o="auto",stream:i,...c}=t,d=typeof o!="string"&&o.type==="function"&&o?.function?.name,{maxChatCompletions:h=ga}=r||{},g=t.tools.map(f=>{if(Xe(f)){if(!f.$callback)throw new A("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:f.$callback,name:f.function.name,description:f.function.description||"",parameters:f.function.parameters,parse:f.$parseRaw,strict:!0}}}return f}),m={};for(let f of g)f.type==="function"&&(m[f.function.name||f.function.function.name]=f.function);let _="tools"in t?g.map(f=>f.type==="function"?{type:"function",function:{name:f.function.name||f.function.function.name,parameters:f.function.parameters,description:f.function.description,strict:f.function.strict}}:f):void 0;for(let f of t.messages)this._addMessage(f,!1);for(let f=0;f<h;++f){let w=(await this._createChatCompletion(e,{...c,tool_choice:o,tools:_,messages:[...this.messages]},r)).choices[0]?.message;if(!w)throw new A("missing message in ChatCompletion response");if(!w.tool_calls?.length)return;for(let O of w.tool_calls){if(O.type!=="function")continue;let E=O.id,{name:b,arguments:S}=O.function,k=m[b];if(k){if(d&&d!==b){let C=`Invalid tool_call: ${JSON.stringify(b)}. ${JSON.stringify(d)} requested. Please try again`;this._addMessage({role:n,tool_call_id:E,content:C});continue}}else{let C=`Invalid tool_call: ${JSON.stringify(b)}. Available options are: ${Object.keys(m).map(T=>JSON.stringify(T)).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:E,content:C});continue}let H;try{H=Jo(k)?await k.parse(S):S}catch(C){let T=C instanceof Error?C.message:String(C);this._addMessage({role:n,tool_call_id:E,content:T});continue}let L=await k.function(H,this),q=u(this,Z,"m",Vo).call(this,L);if(this._addMessage({role:n,tool_call_id:E,content:q}),d)return}}}};Z=new WeakSet,In=function(){return u(this,Z,"m",Es).call(this).content??null},Es=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(Nt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new A("stream ended without producing a ChatCompletionMessage with role=assistant")},xn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Nt(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}}},vn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(wn(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}},Sn=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},Go=function(e){if(e.n!=null&&e.n>1)throw new A("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Vo=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var ss=class s extends jt{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,o)),n}_addMessage(e,t=!0){super._addMessage(e,t),Nt(e)&&e.content&&this._emit("content",e.content)}};var D={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},Rn=class extends Error{},kn=class extends Error{};function _a(s,e=D.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return ya(s.trim(),e)}var ya=(s,e)=>{let t=s.length,r=0,n=_=>{throw new Rn(`${_} at position ${r}`)},o=_=>{throw new kn(`${_} at position ${r}`)},i=()=>(m(),r>=t&&n("Unexpected end of input"),s[r]==='"'?c():s[r]==="{"?d():s[r]==="["?h():s.substring(r,r+4)==="null"||D.NULL&e&&t-r<4&&"null".startsWith(s.substring(r))?(r+=4,null):s.substring(r,r+4)==="true"||D.BOOL&e&&t-r<4&&"true".startsWith(s.substring(r))?(r+=4,!0):s.substring(r,r+5)==="false"||D.BOOL&e&&t-r<5&&"false".startsWith(s.substring(r))?(r+=5,!1):s.substring(r,r+8)==="Infinity"||D.INFINITY&e&&t-r<8&&"Infinity".startsWith(s.substring(r))?(r+=8,1/0):s.substring(r,r+9)==="-Infinity"||D.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(s.substring(r))?(r+=9,-1/0):s.substring(r,r+3)==="NaN"||D.NAN&e&&t-r<3&&"NaN".startsWith(s.substring(r))?(r+=3,NaN):g()),c=()=>{let _=r,f=!1;for(r++;r<t&&(s[r]!=='"'||f&&s[r-1]==="\\");)f=s[r]==="\\"?!f:!1,r++;if(s.charAt(r)=='"')try{return JSON.parse(s.substring(_,++r-Number(f)))}catch(y){o(String(y))}else if(D.STR&e)try{return JSON.parse(s.substring(_,r-Number(f))+'"')}catch{return JSON.parse(s.substring(_,s.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},d=()=>{r++,m();let _={};try{for(;s[r]!=="}";){if(m(),r>=t&&D.OBJ&e)return _;let f=c();m(),r++;try{let y=i();Object.defineProperty(_,f,{value:y,writable:!0,enumerable:!0,configurable:!0})}catch(y){if(D.OBJ&e)return _;throw y}m(),s[r]===","&&r++}}catch{if(D.OBJ&e)return _;n("Expected '}' at end of object")}return r++,_},h=()=>{r++;let _=[];try{for(;s[r]!=="]";)_.push(i()),m(),s[r]===","&&r++}catch{if(D.ARR&e)return _;n("Expected ']' at end of array")}return r++,_},g=()=>{if(r===0){s==="-"&&D.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s)}catch(f){if(D.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(f))}}let _=r;for(s[r]==="-"&&r++;s[r]&&!",]}".includes(s[r]);)r++;r==t&&!(D.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(s.substring(_,r))}catch{s.substring(_,r)==="-"&&D.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s.substring(_,s.lastIndexOf("e")))}catch(y){o(String(y))}}},m=()=>{for(;r<t&&`
11
- \r `.includes(s[r]);)r++};return i()},Cn=s=>_a(s,D.ALL^D.NUM);var U,be,Lt,Ee,Tn,$s,En,$n,On,Os,Nn,Xo,Ye=class s extends jt{constructor(e){super(),U.add(this),be.set(this,void 0),Lt.set(this,void 0),Ee.set(this,void 0),P(this,be,e,"f"),P(this,Lt,[],"f")}get currentChatCompletionSnapshot(){return u(this,Ee,"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;let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),u(this,U,"m",Tn).call(this);let o=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let i of o)u(this,U,"m",En).call(this,i);if(o.controller.signal?.aborted)throw new F;return this._addChatCompletion(u(this,U,"m",Os).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),u(this,U,"m",Tn).call(this),this._connected();let n=he.fromReadableStream(e,this.controller),o;for await(let i of n)o&&o!==i.id&&this._addChatCompletion(u(this,U,"m",Os).call(this)),u(this,U,"m",En).call(this,i),o=i.id;if(n.controller.signal?.aborted)throw new F;return this._addChatCompletion(u(this,U,"m",Os).call(this))}[(be=new WeakMap,Lt=new WeakMap,Ee=new WeakMap,U=new WeakSet,Tn=function(){this.ended||P(this,Ee,void 0,"f")},$s=function(t){let r=u(this,Lt,"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,Lt,"f")[t.index]=r,r)},En=function(t){if(this.ended)return;let r=u(this,U,"m",Xo).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 i=u(this,U,"m",$s).call(this,o);o.finish_reason&&(u(this,U,"m",On).call(this,o),i.current_tool_call_index!=null&&u(this,U,"m",$n).call(this,o,i.current_tool_call_index));for(let c of n.delta.tool_calls??[])i.current_tool_call_index!==c.index&&(u(this,U,"m",On).call(this,o),i.current_tool_call_index!=null&&u(this,U,"m",$n).call(this,o,i.current_tool_call_index)),i.current_tool_call_index=c.index;for(let c of n.delta.tool_calls??[]){let d=o.message.tool_calls?.[c.index];d?.type&&(d?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:d.function?.name,index:c.index,arguments:d.function.arguments,parsed_arguments:d.function.parsed_arguments,arguments_delta:c.function?.arguments??""}):(d?.type,void 0))}}},$n=function(t,r){if(u(this,U,"m",$s).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 i=u(this,be,"f")?.tools?.find(c=>Xr(c)&&c.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:r,arguments:o.function.arguments,parsed_arguments:Xe(i)?i.$parseRaw(o.function.arguments):i?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},On=function(t){let r=u(this,U,"m",$s).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let n=u(this,U,"m",Nn).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}))},Os=function(){if(this.ended)throw new A("stream has ended, this shouldn't happen");let t=u(this,Ee,"f");if(!t)throw new A("request ended without sending any chunks");return P(this,Ee,void 0,"f"),P(this,Lt,[],"f"),Aa(t,u(this,be,"f"))},Nn=function(){let t=u(this,be,"f")?.response_format;return Yr(t)?t:null},Xo=function(t){var r,n,o,i;let c=u(this,Ee,"f"),{choices:d,...h}=t;c?Object.assign(c,h):c=P(this,Ee,{...h,choices:[]},"f");for(let{delta:g,finish_reason:m,index:_,logprobs:f=null,...y}of t.choices){let w=c.choices[_];if(w||(w=c.choices[_]={finish_reason:m,index:_,message:{},logprobs:f,...y}),f)if(!w.logprobs)w.logprobs=Object.assign({},f);else{let{content:L,refusal:q,...C}=f;Object.assign(w.logprobs,C),L&&((r=w.logprobs).content??(r.content=[]),w.logprobs.content.push(...L)),q&&((n=w.logprobs).refusal??(n.refusal=[]),w.logprobs.refusal.push(...q))}if(m&&(w.finish_reason=m,u(this,be,"f")&&bn(u(this,be,"f")))){if(m==="length")throw new Ct;if(m==="content_filter")throw new Tt}if(Object.assign(w,y),!g)continue;let{content:O,refusal:E,function_call:b,role:S,tool_calls:k,...H}=g;if(Object.assign(w.message,H),E&&(w.message.refusal=(w.message.refusal||"")+E),S&&(w.message.role=S),b&&(w.message.function_call?(b.name&&(w.message.function_call.name=b.name),b.arguments&&((o=w.message.function_call).arguments??(o.arguments=""),w.message.function_call.arguments+=b.arguments)):w.message.function_call=b),O&&(w.message.content=(w.message.content||"")+O,!w.message.refusal&&u(this,U,"m",Nn).call(this)&&(w.message.parsed=Cn(w.message.content))),k){w.message.tool_calls||(w.message.tool_calls=[]);for(let{index:L,id:q,type:C,function:T,...$}of k){let M=(i=w.message.tool_calls)[L]??(i[L]={});Object.assign(M,$),q&&(M.id=q),C&&(M.type=C),T&&(M.function??(M.function={name:T.name??"",arguments:""})),T?.name&&(M.function.name=T.name),T?.arguments&&(M.function.arguments+=T.arguments,qo(u(this,be,"f"),M)&&(M.function.parsed_arguments=Cn(M.function.arguments)))}}}return c},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,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new he(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Aa(s,e){let{id:t,choices:r,created:n,model:o,system_fingerprint:i,...c}=s,d={...c,id:t,choices:r.map(({message:h,finish_reason:g,index:m,logprobs:_,...f})=>{if(!g)throw new A(`missing finish_reason for choice ${m}`);let{content:y=null,function_call:w,tool_calls:O,...E}=h,b=h.role;if(!b)throw new A(`missing role for choice ${m}`);if(w){let{arguments:S,name:k}=w;if(S==null)throw new A(`missing function_call.arguments for choice ${m}`);if(!k)throw new A(`missing function_call.name for choice ${m}`);return{...f,message:{content:y,function_call:{arguments:S,name:k},role:b,refusal:h.refusal??null},finish_reason:g,index:m,logprobs:_}}return O?{...f,index:m,finish_reason:g,logprobs:_,message:{...E,role:b,content:y,refusal:h.refusal??null,tool_calls:O.map((S,k)=>{let{function:H,type:L,id:q,...C}=S,{arguments:T,name:$,...M}=H||{};if(q==null)throw new A(`missing choices[${m}].tool_calls[${k}].id
12
- ${Ns(s)}`);if(L==null)throw new A(`missing choices[${m}].tool_calls[${k}].type
13
- ${Ns(s)}`);if($==null)throw new A(`missing choices[${m}].tool_calls[${k}].function.name
14
- ${Ns(s)}`);if(T==null)throw new A(`missing choices[${m}].tool_calls[${k}].function.arguments
15
- ${Ns(s)}`);return{...C,id:q,type:L,function:{...M,name:$,arguments:T}}})}}:{...f,message:{...E,content:y,role:b,refusal:h.refusal??null},finish_reason:g,index:m,logprobs:_}}),created:n,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Uo(d,e)}function Ns(s){return JSON.stringify(s)}var ns=class s extends Ye{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,o)),n}};var we=class extends l{constructor(){super(...arguments),this.messages=new Ve(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(a`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(a`/chat/completions/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chat/completions",x,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return Ho(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>Qr(r,e))}runTools(e,t){return e.stream?ns.runTools(this._client,e,t):ss.runTools(this._client,e,t)}stream(e,t){return Ye.createChatCompletion(this._client,e,t)}};we.Messages=Ve;var $e=class extends l{constructor(){super(...arguments),this.completions=new we(this._client)}};$e.Completions=we;var Ft=class extends l{create(e,t){return this._client.post("/organization/admin_api_keys",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(a`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/admin_api_keys",x,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Kt=class extends l{list(e={},t){return this._client.getAPIList("/organization/audit_logs",v,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}};var Bt=class extends l{create(e,t){return this._client.post("/organization/certificates",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},r){return this._client.get(a`/organization/certificates/${e}`,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(a`/organization/certificates/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/certificates",v,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList("/organization/certificates/activate",X,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList("/organization/certificates/deactivate",X,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}};var zt=class extends l{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 Ut=class extends l{create(e,t){return this._client.post("/organization/invites",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(a`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/invites",v,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var qt=class extends l{create(e,t){return this._client.post("/organization/roles",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(a`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(a`/organization/roles/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/roles",K,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Dt=class extends l{create(e,t){return this._client.post("/organization/spend_alerts",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(a`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(a`/organization/spend_alerts/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/spend_alerts",v,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Ht=class extends l{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 Wt=class extends l{create(e,t,r){return this._client.post(a`/organization/groups/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{group_id:n}=t;return this._client.get(a`/organization/groups/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/organization/groups/${e}/roles`,K,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{group_id:n}=t;return this._client.delete(a`/organization/groups/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Jt=class extends l{create(e,t,r){return this._client.post(a`/organization/groups/${e}/users`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{group_id:n}=t;return this._client.get(a`/organization/groups/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/organization/groups/${e}/users`,K,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{group_id:n}=t;return this._client.delete(a`/organization/groups/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Oe=class extends l{constructor(){super(...arguments),this.users=new Jt(this._client),this.roles=new Wt(this._client)}create(e,t){return this._client.post("/organization/groups",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(a`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(a`/organization/groups/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/groups",K,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};Oe.Users=Jt;Oe.Roles=Wt;var Gt=class extends l{retrieve(e,t,r){let{project_id:n}=t;return this._client.get(a`/organization/projects/${n}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/organization/projects/${e}/api_keys`,v,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(a`/organization/projects/${n}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Vt=class extends l{list(e,t={},r){return this._client.getAPIList(a`/organization/projects/${e}/certificates`,v,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}activate(e,t,r){return this._client.getAPIList(a`/organization/projects/${e}/certificates/activate`,X,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,r){return this._client.getAPIList(a`/organization/projects/${e}/certificates/deactivate`,X,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var Xt=class extends l{retrieve(e,t){return this._client.get(a`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(a`/organization/projects/${e}/data_retention`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}};var Yt=class extends l{retrieve(e,t){return this._client.get(a`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(a`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}};var Qt=class extends l{retrieve(e,t){return this._client.get(a`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(a`/organization/projects/${e}/model_permissions`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Zt=class extends l{listRateLimits(e,t={},r){return this._client.getAPIList(a`/organization/projects/${e}/rate_limits`,v,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,r){let{project_id:n,...o}=t;return this._client.post(a`/organization/projects/${n}/rate_limits/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}};var er=class extends l{create(e,t,r){return this._client.post(a`/projects/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(a`/projects/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(a`/projects/${n}/roles/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/projects/${e}/roles`,K,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(a`/projects/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var tr=class extends l{create(e,t,r){return this._client.post(a`/organization/projects/${e}/service_accounts`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(a`/organization/projects/${n}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(a`/organization/projects/${n}/service_accounts/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/organization/projects/${e}/service_accounts`,v,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(a`/organization/projects/${n}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var rr=class extends l{create(e,t,r){return this._client.post(a`/organization/projects/${e}/spend_alerts`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(a`/organization/projects/${n}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(a`/organization/projects/${n}/spend_alerts/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/organization/projects/${e}/spend_alerts`,v,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(a`/organization/projects/${n}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var sr=class extends l{create(e,t,r){let{project_id:n,...o}=t;return this._client.post(a`/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(a`/projects/${n}/groups/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t,r){let{project_id:n,...o}=t;return this._client.getAPIList(a`/projects/${n}/groups/${e}/roles`,K,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n,group_id:o}=t;return this._client.delete(a`/projects/${n}/groups/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Qe=class extends l{constructor(){super(...arguments),this.roles=new sr(this._client)}create(e,t,r){return this._client.post(a`/organization/projects/${e}/groups`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n,...o}=t;return this._client.get(a`/organization/projects/${n}/groups/${e}`,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/organization/projects/${e}/groups`,K,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(a`/organization/projects/${n}/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Qe.Roles=sr;var nr=class extends l{create(e,t,r){let{project_id:n,...o}=t;return this._client.post(a`/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(a`/projects/${n}/users/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t,r){let{project_id:n,...o}=t;return this._client.getAPIList(a`/projects/${n}/users/${e}/roles`,K,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n,user_id:o}=t;return this._client.delete(a`/projects/${n}/users/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Ze=class extends l{constructor(){super(...arguments),this.roles=new nr(this._client)}create(e,t,r){return this._client.post(a`/organization/projects/${e}/users`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(a`/organization/projects/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(a`/organization/projects/${n}/users/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/organization/projects/${e}/users`,v,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(a`/organization/projects/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Ze.Roles=nr;var W=class extends l{constructor(){super(...arguments),this.users=new Ze(this._client),this.serviceAccounts=new tr(this._client),this.apiKeys=new Gt(this._client),this.rateLimits=new Zt(this._client),this.modelPermissions=new Qt(this._client),this.hostedToolPermissions=new Yt(this._client),this.groups=new Qe(this._client),this.roles=new er(this._client),this.dataRetention=new Xt(this._client),this.spendAlerts=new rr(this._client),this.certificates=new Vt(this._client)}create(e,t){return this._client.post("/organization/projects",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(a`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(a`/organization/projects/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/projects",v,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(a`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};W.Users=Ze;W.ServiceAccounts=tr;W.APIKeys=Gt;W.RateLimits=Zt;W.ModelPermissions=Qt;W.HostedToolPermissions=Yt;W.Groups=Qe;W.Roles=er;W.DataRetention=Xt;W.SpendAlerts=rr;W.Certificates=Vt;var or=class extends l{create(e,t,r){return this._client.post(a`/organization/users/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{user_id:n}=t;return this._client.get(a`/organization/users/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/organization/users/${e}/roles`,K,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{user_id:n}=t;return this._client.delete(a`/organization/users/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var et=class extends l{constructor(){super(...arguments),this.roles=new or(this._client)}retrieve(e,t){return this._client.get(a`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(a`/organization/users/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/users",v,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};et.Roles=or;var J=class extends l{constructor(){super(...arguments),this.auditLogs=new Kt(this._client),this.adminAPIKeys=new Ft(this._client),this.usage=new Ht(this._client),this.invites=new Ut(this._client),this.users=new et(this._client),this.groups=new Oe(this._client),this.roles=new qt(this._client),this.dataRetention=new zt(this._client),this.spendAlerts=new Dt(this._client),this.certificates=new Bt(this._client),this.projects=new W(this._client)}};J.AuditLogs=Kt;J.AdminAPIKeys=Ft;J.Usage=Ht;J.Invites=Ut;J.Users=et;J.Groups=Oe;J.Roles=qt;J.DataRetention=zt;J.SpendAlerts=Dt;J.Certificates=Bt;J.Projects=W;var Ne=class extends l{constructor(){super(...arguments),this.organization=new J(this._client)}};Ne.Organization=J;var Yo=Symbol("brand.privateNullableHeaders");function*Va(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():en(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=en(r[1])?r[1]:[r[1]],i=!1;for(let c of o)c!==void 0&&(e&&!i&&(i=!0,yield[n,null]),yield[n,c])}}var p=s=>{let e=new Headers,t=new Set;for(let r of s){let n=new Set;for(let[o,i]of Va(r)){let c=o.toLowerCase();n.has(c)||(e.delete(o),n.add(c)),i===null?(e.delete(o),t.add(c)):(e.append(o,i),t.delete(c))}}return{[Yo]:!0,values:e,nulls:t}};var ir=class extends l{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:p([{Accept:"application/octet-stream"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var ar=class extends l{create(e,t){return this._client.post("/audio/transcriptions",Y({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var cr=class extends l{create(e,t){return this._client.post("/audio/translations",Y({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var me=class extends l{constructor(){super(...arguments),this.transcriptions=new ar(this._client),this.translations=new cr(this._client),this.speech=new ir(this._client)}};me.Transcriptions=ar;me.Translations=cr;me.Speech=ir;var tt=class extends l{create(e,t){return this._client.post("/batches",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/batches",x,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(a`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}};var lr=class extends l{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/assistants/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(a`/assistants/${e}`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/assistants",x,{query:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/assistants/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var ur=class extends l{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var dr=class extends l{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var Me=class extends l{constructor(){super(...arguments),this.sessions=new ur(this._client),this.transcriptionSessions=new dr(this._client)}};Me.Sessions=ur;Me.TranscriptionSessions=dr;var hr=class extends l{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(a`/chatkit/sessions/${e}/cancel`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}};var mr=class extends l{retrieve(e,t){return this._client.get(a`/chatkit/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chatkit/threads",v,{query:e,...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/chatkit/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},r){return this._client.getAPIList(a`/chatkit/threads/${e}/items`,v,{query:t,...r,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var je=class extends l{constructor(){super(...arguments),this.sessions=new hr(this._client),this.threads=new mr(this._client)}};je.Sessions=hr;je.Threads=mr;var fr=class extends l{create(e,t,r){return this._client.post(a`/threads/${e}/messages`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(a`/threads/${n}/messages/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(a`/threads/${n}/messages/${e}`,{body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/threads/${e}/messages`,x,{query:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){let{thread_id:n}=t;return this._client.delete(a`/threads/${n}/messages/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var pr=class extends l{retrieve(e,t,r){let{thread_id:n,run_id:o,...i}=t;return this._client.get(a`/threads/${n}/runs/${o}/steps/${e}`,{query:i,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t,r){let{thread_id:n,...o}=t;return this._client.getAPIList(a`/threads/${n}/runs/${e}/steps`,x,{query:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Qo=s=>{if(typeof Buffer<"u"){let e=Buffer.from(s,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(s),t=e.length,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);return Array.from(new Float32Array(r.buffer))}};var ne=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 G,st,Mn,fe,Ms,oe,nt,gr,rt,Fs,re,js,Ls,as,os,is,Zo,ei,ti,ri,si,ni,oi,Pe=class extends Te{constructor(){super(...arguments),G.add(this),Mn.set(this,[]),fe.set(this,{}),Ms.set(this,{}),oe.set(this,void 0),nt.set(this,void 0),gr.set(this,void 0),rt.set(this,void 0),Fs.set(this,void 0),re.set(this,void 0),js.set(this,void 0),Ls.set(this,void 0),as.set(this,void 0)}[(Mn=new WeakMap,fe=new WeakMap,Ms=new WeakMap,oe=new WeakMap,nt=new WeakMap,gr=new WeakMap,rt=new WeakMap,Fs=new WeakMap,re=new WeakMap,js=new WeakMap,Ls=new WeakMap,as=new WeakMap,G=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,i)=>t.push({resolve:o,reject:i})).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 st;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();let n=he.fromReadableStream(e,this.controller);for await(let o of n)u(this,G,"m",os).call(this,o);if(n.controller.signal?.aborted)throw new F;return this._addRun(u(this,G,"m",is).call(this))}toReadableStream(){return new he(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n){let o=new st;return o._run(()=>o._runToolAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},c=await e.submitToolOutputs(t,i,{...n,signal:this.controller.signal});this._connected();for await(let d of c)u(this,G,"m",os).call(this,d);if(c.controller.signal?.aborted)throw new F;return this._addRun(u(this,G,"m",is).call(this))}static createThreadAssistantStream(e,t,r){let n=new st;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 st;return o._run(()=>o._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return u(this,js,"f")}currentRun(){return u(this,Ls,"f")}currentMessageSnapshot(){return u(this,oe,"f")}currentRunStepSnapshot(){return u(this,as,"f")}async finalRunSteps(){return await this.done(),Object.values(u(this,fe,"f"))}async finalMessages(){return await this.done(),Object.values(u(this,Ms,"f"))}async finalRun(){if(await this.done(),!u(this,nt,"f"))throw Error("Final run was not received.");return u(this,nt,"f")}async _createThreadAssistantStream(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort()));let o={...t,stream:!0},i=await e.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(let c of i)u(this,G,"m",os).call(this,c);if(i.controller.signal?.aborted)throw new F;return this._addRun(u(this,G,"m",is).call(this))}async _createAssistantStream(e,t,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},c=await e.create(t,i,{...n,signal:this.controller.signal});this._connected();for await(let d of c)u(this,G,"m",os).call(this,d);if(c.controller.signal?.aborted)throw new F;return this._addRun(u(this,G,"m",is).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(Dr(o)&&Dr(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...n);continue}for(let i of n){if(!Dr(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let c=i.index;if(c==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof c!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${c}`);let d=o[c];d==null?o.push(i):o[c]=this.accumulateDelta(d,i)}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)}};st=Pe,os=function(e){if(!this.ended)switch(P(this,js,e,"f"),u(this,G,"m",ti).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,G,"m",oi).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,G,"m",ei).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,G,"m",Zo).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},is=function(){if(this.ended)throw new A("stream has ended, this shouldn't happen");if(!u(this,nt,"f"))throw Error("Final run has not been received");return u(this,nt,"f")},Zo=function(e){let[t,r]=u(this,G,"m",si).call(this,e,u(this,oe,"f"));P(this,oe,t,"f"),u(this,Ms,"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,i=t.content[n.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=u(this,gr,"f")){if(u(this,rt,"f"))switch(u(this,rt,"f").type){case"text":this._emit("textDone",u(this,rt,"f").text,u(this,oe,"f"));break;case"image_file":this._emit("imageFileDone",u(this,rt,"f").image_file,u(this,oe,"f"));break}P(this,gr,n.index,"f")}P(this,rt,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(u(this,gr,"f")!==void 0){let n=e.data.content[u(this,gr,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,u(this,oe,"f"));break;case"text":this._emit("textDone",n.text,u(this,oe,"f"));break}}u(this,oe,"f")&&this._emit("messageDone",e.data),P(this,oe,void 0,"f")}},ei=function(e){let t=u(this,G,"m",ri).call(this,e);switch(P(this,as,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,Fs,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(u(this,re,"f")&&this._emit("toolCallDone",u(this,re,"f")),P(this,Fs,o.index,"f"),P(this,re,t.step_details.tool_calls[o.index],"f"),u(this,re,"f")&&this._emit("toolCallCreated",u(this,re,"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,as,void 0,"f"),e.data.step_details.type=="tool_calls"&&u(this,re,"f")&&(this._emit("toolCallDone",u(this,re,"f")),P(this,re,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},ti=function(e){u(this,Mn,"f").push(e),this._emit("event",e)},ri=function(e){switch(e.event){case"thread.run.step.created":return u(this,fe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=u(this,fe,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let n=st.accumulateDelta(t,r.delta);u(this,fe,"f")[e.data.id]=n}return u(this,fe,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":u(this,fe,"f")[e.data.id]=e.data;break}if(u(this,fe,"f")[e.data.id])return u(this,fe,"f")[e.data.id];throw new Error("No snapshot available")},si=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 i=t.content[o.index];t.content[o.index]=u(this,G,"m",ni).call(this,o,i)}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")},ni=function(e,t){return st.accumulateDelta(t,e)},oi=function(e){switch(P(this,Ls,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,nt,e.data,"f"),u(this,re,"f")&&(this._emit("toolCallDone",u(this,re,"f")),P(this,re,void 0,"f"));break;case"thread.run.cancelling":break}};var ot=class extends l{constructor(){super(...arguments),this.steps=new pr(this._client)}create(e,t,r){let{include:n,...o}=t;return this._client.post(a`/threads/${e}/runs`,{query:{include:n},body:o,...r,headers:p([{"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(a`/threads/${n}/runs/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(a`/threads/${n}/runs/${e}`,{body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/threads/${e}/runs`,x,{query:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,r){let{thread_id:n}=t;return this._client.post(a`/threads/${n}/runs/${e}/cancel`,{...r,headers:p([{"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 Pe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let n=p([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let c=5e3;if(r?.pollIntervalMs)c=r.pollIntervalMs;else{let d=i.headers.get("openai-poll-after-ms");if(d){let h=parseInt(d);isNaN(h)||(c=h)}}await ue(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return Pe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:n,...o}=t;return this._client.post(a`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:p([{"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 Pe.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};ot.Steps=pr;var Le=class extends l{constructor(){super(...arguments),this.runs=new ot(this._client),this.messages=new fr(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(a`/threads/${e}`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return Pe.createThreadAssistantStream(e,this._client.beta.threads,t)}};Le.Runs=ot;Le.Messages=fr;var ie=class extends l{constructor(){super(...arguments),this.realtime=new Me(this._client),this.chatkit=new je(this._client),this.assistants=new lr(this._client),this.threads=new Le(this._client)}};ie.Realtime=Me;ie.ChatKit=je;ie.Assistants=lr;ie.Threads=Le;var it=class extends l{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var _r=class extends l{retrieve(e,t,r){let{container_id:n}=t;return this._client.get(a`/containers/${n}/files/${e}/content`,{...r,headers:p([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var at=class extends l{constructor(){super(...arguments),this.content=new _r(this._client)}create(e,t,r){return this._client.post(a`/containers/${e}/files`,Ce({body:t,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,r){let{container_id:n}=t;return this._client.get(a`/containers/${n}/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/containers/${e}/files`,x,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{container_id:n}=t;return this._client.delete(a`/containers/${n}/files/${e}`,{...r,headers:p([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};at.Content=_r;var Fe=class extends l{constructor(){super(...arguments),this.files=new at(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/containers",x,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/containers/${e}`,{...t,headers:p([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}};Fe.Files=at;var yr=class extends l{create(e,t,r){let{include:n,...o}=t;return this._client.post(a`/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(a`/conversations/${n}/items/${e}`,{query:o,...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/conversations/${e}/items`,v,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{conversation_id:n}=t;return this._client.delete(a`/conversations/${n}/items/${e}`,{...r,__security:{bearerAuth:!0}})}};var Ke=class extends l{constructor(){super(...arguments),this.items=new yr(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(a`/conversations/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};Ke.Items=yr;var ct=class extends l{create(e,t){let r=!!e.encoding_format,n=r?e.encoding_format:"base64";r&&j(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:(j(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(c=>{let d=c.embedding;c.embedding=Qo(d)}),i)))}};var Ar=class extends l{retrieve(e,t,r){let{eval_id:n,run_id:o}=t;return this._client.get(a`/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(a`/evals/${n}/runs/${e}/output_items`,x,{query:o,...r,__security:{bearerAuth:!0}})}};var lt=class extends l{constructor(){super(...arguments),this.outputItems=new Ar(this._client)}create(e,t,r){return this._client.post(a`/evals/${e}/runs`,{body:t,...r,__security:{bearerAuth:!0}})}retrieve(e,t,r){let{eval_id:n}=t;return this._client.get(a`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/evals/${e}/runs`,x,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{eval_id:n}=t;return this._client.delete(a`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}cancel(e,t,r){let{eval_id:n}=t;return this._client.post(a`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}};lt.OutputItems=Ar;var Be=class extends l{constructor(){super(...arguments),this.runs=new lt(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(a`/evals/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/evals",x,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};Be.Runs=lt;var ut=class extends l{create(e,t){return this._client.post("/files",Y({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(a`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/files",x,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(a`/files/${e}/content`,{...t,headers:p([{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(),i=await this.retrieve(e);for(;!i.status||!n.has(i.status);)if(await ue(t),i=await this.retrieve(e),Date.now()-o>r)throw new Re({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};var br=class extends l{};var wr=class extends l{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t,__security:{bearerAuth:!0}})}};var dt=class extends l{constructor(){super(...arguments),this.graders=new wr(this._client)}};dt.Graders=wr;var Pr=class extends l{create(e,t,r){return this._client.getAPIList(a`/fine_tuning/checkpoints/${e}/permissions`,X,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},r){return this._client.get(a`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/fine_tuning/checkpoints/${e}/permissions`,v,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{fine_tuned_model_checkpoint:n}=t;return this._client.delete(a`/fine_tuning/checkpoints/${n}/permissions/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var ht=class extends l{constructor(){super(...arguments),this.permissions=new Pr(this._client)}};ht.Permissions=Pr;var Ir=class extends l{list(e,t={},r){return this._client.getAPIList(a`/fine_tuning/jobs/${e}/checkpoints`,x,{query:t,...r,__security:{bearerAuth:!0}})}};var mt=class extends l{constructor(){super(...arguments),this.checkpoints=new Ir(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(a`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",x,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(a`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},r){return this._client.getAPIList(a`/fine_tuning/jobs/${e}/events`,x,{query:t,...r,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(a`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(a`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}};mt.Checkpoints=Ir;var ae=class extends l{constructor(){super(...arguments),this.methods=new br(this._client),this.jobs=new mt(this._client),this.checkpoints=new ht(this._client),this.alpha=new dt(this._client)}};ae.Methods=br;ae.Jobs=mt;ae.Checkpoints=ht;ae.Alpha=dt;var xr=class extends l{};var ze=class extends l{constructor(){super(...arguments),this.graderModels=new xr(this._client)}};ze.GraderModels=xr;var ft=class extends l{createVariation(e,t){return this._client.post("/images/variations",Y({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post("/images/edits",Y({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 pt=class extends l{retrieve(e,t){return this._client.get(a`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",X,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/models/${e}`,{...t,__security:{bearerAuth:!0}})}};var gt=class extends l{create(e,t){return this._client.post("/moderations",{body:e,...t,__security:{bearerAuth:!0}})}};var vr=class extends l{accept(e,t,r){return this._client.post(a`/realtime/calls/${e}/accept`,{body:t,...r,headers:p([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(a`/realtime/calls/${e}/hangup`,{...t,headers:p([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,r){return this._client.post(a`/realtime/calls/${e}/refer`,{body:t,...r,headers:p([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},r){return this._client.post(a`/realtime/calls/${e}/reject`,{body:t,...r,headers:p([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};var Sr=class extends l{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t,__security:{bearerAuth:!0}})}};var Ie=class extends l{constructor(){super(...arguments),this.clientSecrets=new Sr(this._client),this.calls=new vr(this._client)}};Ie.ClientSecrets=Sr;Ie.Calls=vr;function ii(s,e){return!e||!Sc(e)?{...s,output_parsed:null,output:s.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:jn(s,e)}function jn(s,e){let t=s.output.map(n=>{if(n.type==="function_call")return{...n,parsed_arguments:Cc(e,n)};if(n.type==="message"){let o=n.content.map(i=>i.type==="output_text"?{...i,parsed:vc(e,i.text)}:i);return{...n,content:o}}return n}),r=Object.assign({},s,{output:t});return Object.getOwnPropertyDescriptor(s,"output_text")||cs(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(let n of r.output)if(n.type==="message"){for(let o of n.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),r}function vc(s,e){return s.text?.format?.type!=="json_schema"?null:"$parseRaw"in s.text?.format?(s.text?.format).$parseRaw(e):JSON.parse(e)}function Sc(s){return!!Yr(s.text?.format)}function Rc(s){return s?.$brand==="auto-parseable-tool"}function kc(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function Cc(s,e){let t=kc(s.tools??[],e.name);return{...e,...e,parsed_arguments:Rc(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function cs(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("")}var Rr,Ks,Ue,Bs,ai,ci,li,ui,zs=class s extends Te{constructor(e){super(),Rr.add(this),Ks.set(this,void 0),Ue.set(this,void 0),Bs.set(this,void 0),P(this,Ks,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){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),u(this,Rr,"m",ai).call(this);let o,i=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let c of o)u(this,Rr,"m",ci).call(this,c,i);if(o.controller.signal?.aborted)throw new F;return u(this,Rr,"m",li).call(this)}[(Ks=new WeakMap,Ue=new WeakMap,Bs=new WeakMap,Rr=new WeakSet,ai=function(){this.ended||P(this,Ue,void 0,"f")},ci=function(t,r){if(this.ended)return;let n=(i,c)=>{(r==null||c.sequence_number>r)&&this._emit(i,c)},o=u(this,Rr,"m",ui).call(this,t);switch(n("event",t),t.type){case"response.output_text.delta":{let i=o.output[t.output_index];if(!i)throw new A(`missing output at index ${t.output_index}`);if(i.type==="message"){let c=i.content[t.content_index];if(!c)throw new A(`missing content at index ${t.content_index}`);if(c.type!=="output_text")throw new A(`expected content to be 'output_text', got ${c.type}`);n("response.output_text.delta",{...t,snapshot:c.text})}break}case"response.function_call_arguments.delta":{let i=o.output[t.output_index];if(!i)throw new A(`missing output at index ${t.output_index}`);i.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:n(t.type,t);break}},li=function(){if(this.ended)throw new A("stream has ended, this shouldn't happen");let t=u(this,Ue,"f");if(!t)throw new A("request ended without sending any events");P(this,Ue,void 0,"f");let r=Tc(t,u(this,Ks,"f"));return P(this,Bs,r,"f"),r},ui=function(t){let r=u(this,Ue,"f");if(!r){if(t.type!=="response.created")throw new A(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=P(this,Ue,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let n=r.output[t.output_index];if(!n)throw new A(`missing output at index ${t.output_index}`);let o=n.type,i=t.part;o==="message"&&i.type!=="reasoning_text"?n.content.push(i):o==="reasoning"&&i.type==="reasoning_text"&&(n.content||(n.content=[]),n.content.push(i));break}case"response.output_text.delta":{let n=r.output[t.output_index];if(!n)throw new A(`missing output at index ${t.output_index}`);if(n.type==="message"){let o=n.content[t.content_index];if(!o)throw new A(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new A(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{let n=r.output[t.output_index];if(!n)throw new A(`missing output at index ${t.output_index}`);n.type==="function_call"&&(n.arguments+=t.delta);break}case"response.reasoning_text.delta":{let n=r.output[t.output_index];if(!n)throw new A(`missing output at index ${t.output_index}`);if(n.type==="reasoning"){let o=n.content?.[t.content_index];if(!o)throw new A(`missing content at index ${t.content_index}`);if(o.type!=="reasoning_text")throw new A(`expected content to be 'reasoning_text', got ${o.type}`);o.text+=t.delta}break}case"response.completed":{P(this,Ue,t.response,"f");break}}return 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,i)=>t.push({resolve:o,reject:i})).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,Bs,"f");if(!e)throw new A("stream ended without producing a ChatCompletion");return e}};function Tc(s,e){return ii(s,e)}var kr=class extends l{list(e,t={},r){return this._client.getAPIList(a`/responses/${e}/input_items`,x,{query:t,...r,__security:{bearerAuth:!0}})}};var Cr=class extends l{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t,__security:{bearerAuth:!0}})}};var pe=class extends l{constructor(){super(...arguments),this.inputItems=new kr(this._client),this.inputTokens=new Cr(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"&&cs(r),r))}retrieve(e,t={},r){return this._client.get(a`/responses/${e}`,{query:t,...r,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&cs(n),n))}delete(e,t){return this._client.delete(a`/responses/${e}`,{...t,headers:p([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>jn(r,e))}stream(e,t){return zs.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(a`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post("/responses/compact",{body:e,...t,__security:{bearerAuth:!0}})}};pe.InputItems=kr;pe.InputTokens=Cr;var Tr=class extends l{retrieve(e,t){return this._client.get(a`/skills/${e}/content`,{...t,headers:p([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Er=class extends l{retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(a`/skills/${n}/versions/${e}/content`,{...r,headers:p([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var _t=class extends l{constructor(){super(...arguments),this.content=new Er(this._client)}create(e,t={},r){return this._client.post(a`/skills/${e}/versions`,Ce({body:t,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(a`/skills/${n}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/skills/${e}/versions`,x,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{skill_id:n}=t;return this._client.delete(a`/skills/${n}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}};_t.Content=Er;var xe=class extends l{constructor(){super(...arguments),this.content=new Tr(this._client),this.versions=new _t(this._client)}create(e={},t){return this._client.post("/skills",Ce({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(a`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(a`/skills/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/skills",x,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};xe.Content=Tr;xe.Versions=_t;var $r=class extends l{create(e,t,r){return this._client.post(a`/uploads/${e}/parts`,Y({body:t,...r,__security:{bearerAuth:!0}},this._client))}};var qe=class extends l{constructor(){super(...arguments),this.parts=new $r(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(a`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,r){return this._client.post(a`/uploads/${e}/complete`,{body:t,...r,__security:{bearerAuth:!0}})}};qe.Parts=$r;var di=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 Or=class extends l{create(e,t,r){return this._client.post(a`/vector_stores/${e}/file_batches`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(a`/vector_stores/${n}/file_batches/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,r){let{vector_store_id:n}=t;return this._client.post(a`/vector_stores/${n}/file_batches/${e}/cancel`,{...r,headers:p([{"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(a`/vector_stores/${n}/file_batches/${e}/files`,x,{query:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,r){let n=p([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse();switch(o.status){case"in_progress":let c=5e3;if(r?.pollIntervalMs)c=r.pollIntervalMs;else{let d=i.headers.get("openai-poll-after-ms");if(d){let h=parseInt(d);isNaN(h)||(c=h)}}await ue(c);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,i=Math.min(o,t.length),c=this._client,d=t.values(),h=[...r];async function g(_){for(let f of _){let y=await c.files.create({file:f,purpose:"assistants"},n);h.push(y.id)}}let m=Array(i).fill(d).map(g);return await di(m),await this.createAndPoll(e,{file_ids:h})}};var Nr=class extends l{create(e,t,r){return this._client.post(a`/vector_stores/${e}/files`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(a`/vector_stores/${n}/files/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{vector_store_id:n,...o}=t;return this._client.post(a`/vector_stores/${n}/files/${e}`,{body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/vector_stores/${e}/files`,x,{query:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){let{vector_store_id:n}=t;return this._client.delete(a`/vector_stores/${n}/files/${e}`,{...r,headers:p([{"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=p([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(),i=o.data;switch(i.status){case"in_progress":let c=5e3;if(r?.pollIntervalMs)c=r.pollIntervalMs;else{let d=o.response.headers.get("openai-poll-after-ms");if(d){let h=parseInt(d);isNaN(h)||(c=h)}}await ue(c);break;case"failed":case"completed":return i}}}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(a`/vector_stores/${n}/files/${e}/content`,X,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var ve=class extends l{constructor(){super(...arguments),this.files=new Nr(this._client),this.fileBatches=new Or(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/vector_stores/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(a`/vector_stores/${e}`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vector_stores",x,{query:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/vector_stores/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,r){return this._client.getAPIList(a`/vector_stores/${e}/search`,X,{body:t,method:"post",...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};ve.Files=Nr;ve.FileBatches=Or;var yt=class extends l{create(e,t){return this._client.post("/videos",Y({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(a`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/videos",v,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post("/videos/characters",Y({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},r){return this._client.get(a`/videos/${e}/content`,{query:t,...r,headers:p([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post("/videos/edits",Y({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post("/videos/extensions",Y({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(a`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,r){return this._client.post(a`/videos/${e}/remix`,Ce({body:t,...r,__security:{bearerAuth:!0}},this._client))}};var Mr,hi,Us,At=class extends l{constructor(){super(...arguments),Mr.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,Mr,"m",hi).call(this,r);let o=p([t]).values,i=u(this,Mr,"m",Us).call(this,o,"webhook-signature"),c=u(this,Mr,"m",Us).call(this,o,"webhook-timestamp"),d=u(this,Mr,"m",Us).call(this,o,"webhook-id"),h=parseInt(c,10);if(isNaN(h))throw new le("Invalid webhook timestamp format");let g=Math.floor(Date.now()/1e3);if(g-h>n)throw new le("Webhook timestamp is too old");if(h>g+n)throw new le("Webhook timestamp is too new");let m=i.split(" ").map(w=>w.startsWith("v1,")?w.substring(3):w),_=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),f=d?`${d}.${c}.${e}`:`${c}.${e}`,y=await crypto.subtle.importKey("raw",_,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let w of m)try{let O=Buffer.from(w,"base64");if(await crypto.subtle.verify("HMAC",y,O,new TextEncoder().encode(f)))return}catch{continue}throw new le("The given webhook signature does not match the expected signature")}};Mr=new WeakSet,hi=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")},Us=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 Ln,Fn,qs,fi,Kc="workload-identity-auth",I=class{constructor({baseURL:e=ne("OPENAI_BASE_URL"),apiKey:t=ne("OPENAI_API_KEY")??null,adminAPIKey:r=ne("OPENAI_ADMIN_KEY")??null,organization:n=ne("OPENAI_ORG_ID")??null,project:o=ne("OPENAI_PROJECT_ID")??null,webhookSecret:i=ne("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:c,...d}={}){Ln.add(this),qs.set(this,void 0),this.completions=new it(this),this.chat=new $e(this),this.embeddings=new ct(this),this.files=new ut(this),this.images=new ft(this),this.audio=new me(this),this.moderations=new gt(this),this.models=new pt(this),this.fineTuning=new ae(this),this.graders=new ze(this),this.vectorStores=new ve(this),this.webhooks=new At(this),this.beta=new ie(this),this.batches=new tt(this),this.uploads=new qe(this),this.admin=new Ne(this),this.responses=new pe(this),this.realtime=new Ie(this),this.conversations=new Ke(this),this.evals=new Be(this),this.containers=new Fe(this),this.skills=new xe(this),this.videos=new yt(this);let h={apiKey:t,adminAPIKey:r,organization:n,project:o,webhookSecret:i,workloadIdentity:c,...d,baseURL:e||"https://api.openai.com/v1"};if(t&&c)throw new A("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!t&&!r&&!c)throw new A("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!h.dangerouslyAllowBrowser&&_o())throw new A(`It looks like you're running in a browser-like environment.
10
+ ${m}`)}return i},a=Aa(Ho);var Xe=class extends l{list(e,t={},r){return this._client.getAPIList(a`/chat/completions/${e}/messages`,v,{query:t,...r,__security:{bearerAuth:!0}})}};function Zr(s){return s!==void 0&&"function"in s&&s.function!==void 0}function es(s){return s?.$brand==="auto-parseable-response-format"}function Ye(s){return s?.$brand==="auto-parseable-tool"}function Jo(s,e){return!e||!In(e)?{...s,choices:s.choices.map(t=>(Vo(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:ts(s,e)}function ts(s,e){let t=s.choices.map(r=>{if(r.finish_reason==="length")throw new Et;if(r.finish_reason==="content_filter")throw new $t;return Vo(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(n=>Pa(e,n))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?wa(e,r.message.content):null}}});return{...s,choices:t}}function wa(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 Pa(s,e){let t=s.tools?.find(r=>Zr(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ye(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function Go(s,e){if(!s||!("tools"in s)||!s.tools)return!1;let t=s.tools?.find(r=>Zr(r)&&r.function?.name===e.function.name);return Zr(t)&&(Ye(t)||t?.function.strict||!1)}function In(s){return es(s.response_format)?!0:s.tools?.some(e=>Ye(e)||e.type==="function"&&e.function.strict===!0)??!1}function Vo(s){for(let e of s||[])if(e.type!=="function")throw new A(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Xo(s){for(let e of s??[]){if(e.type!=="function")throw new A(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new A(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var jt=s=>s?.role==="assistant",vn=s=>s?.role==="tool";var xn,ks,Cs,rs,ss,Ts,ns,Ae,os,Es,$s,Lt,Yo,Te=class{constructor(){xn.add(this),this.controller=new AbortController,ks.set(this,void 0),Cs.set(this,()=>{}),rs.set(this,()=>{}),ss.set(this,void 0),Ts.set(this,()=>{}),ns.set(this,()=>{}),Ae.set(this,{}),os.set(this,!1),Es.set(this,!1),$s.set(this,!1),Lt.set(this,!1),P(this,ks,new Promise((e,t)=>{P(this,Cs,e,"f"),P(this,rs,t,"f")}),"f"),P(this,ss,new Promise((e,t)=>{P(this,Ts,e,"f"),P(this,ns,t,"f")}),"f"),u(this,ks,"f").catch(()=>{}),u(this,ss,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},u(this,xn,"m",Yo).bind(this))},0)}_connected(){this.ended||(u(this,Cs,"f").call(this),this._emit("connect"))}get ended(){return u(this,os,"f")}get errored(){return u(this,Es,"f")}get aborted(){return u(this,$s,"f")}abort(){this.controller.abort()}on(e,t){return(u(this,Ae,"f")[e]||(u(this,Ae,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=u(this,Ae,"f")[e];if(!r)return this;let n=r.findIndex(o=>o.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(u(this,Ae,"f")[e]||(u(this,Ae,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{P(this,Lt,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){P(this,Lt,!0,"f"),await u(this,ss,"f")}_emit(e,...t){if(u(this,os,"f"))return;e==="end"&&(P(this,os,!0,"f"),u(this,Ts,"f").call(this));let r=u(this,Ae,"f")[e];if(r&&(u(this,Ae,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!u(this,Lt,"f")&&!r?.length&&Promise.reject(n),u(this,rs,"f").call(this,n),u(this,ns,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!u(this,Lt,"f")&&!r?.length&&Promise.reject(n),u(this,rs,"f").call(this,n),u(this,ns,"f").call(this,n),this._emit("end")}}_emitFinal(){}};ks=new WeakMap,Cs=new WeakMap,rs=new WeakMap,ss=new WeakMap,Ts=new WeakMap,ns=new WeakMap,Ae=new WeakMap,os=new WeakMap,Es=new WeakMap,$s=new WeakMap,Lt=new WeakMap,xn=new WeakSet,Yo=function(e){if(P(this,Es,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new F),e instanceof F)return P(this,$s,!0,"f"),this._emit("abort",e);if(e instanceof A)return this._emit("error",e);if(e instanceof Error){let t=new A(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new A(String(e)))};function Qo(s){return typeof s.parse=="function"}var Z,Sn,Os,Rn,kn,Cn,Zo,ei,Ia=10,Ft=class extends Te{constructor(){super(...arguments),Z.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),vn(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(jt(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 A("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),u(this,Z,"m",Sn).call(this)}async finalMessage(){return await this.done(),u(this,Z,"m",Os).call(this)}async finalFunctionToolCall(){return await this.done(),u(this,Z,"m",Rn).call(this)}async finalFunctionToolCallResult(){return await this.done(),u(this,Z,"m",kn).call(this)}async totalUsage(){return await this.done(),u(this,Z,"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,Z,"m",Os).call(this);t&&this._emit("finalMessage",t);let r=u(this,Z,"m",Sn).call(this);r&&this._emit("finalContent",r);let n=u(this,Z,"m",Rn).call(this);n&&this._emit("finalFunctionToolCall",n);let o=u(this,Z,"m",kn).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",u(this,Z,"m",Cn).call(this))}async _createChatCompletion(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),u(this,Z,"m",Zo).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(ts(o,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){let n="tool",{tool_choice:o="auto",stream:i,...c}=t,d=typeof o!="string"&&o.type==="function"&&o?.function?.name,{maxChatCompletions:h=Ia}=r||{},g=t.tools.map(f=>{if(Ye(f)){if(!f.$callback)throw new A("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:f.$callback,name:f.function.name,description:f.function.description||"",parameters:f.function.parameters,parse:f.$parseRaw,strict:!0}}}return f}),m={};for(let f of g)f.type==="function"&&(m[f.function.name||f.function.function.name]=f.function);let _="tools"in t?g.map(f=>f.type==="function"?{type:"function",function:{name:f.function.name||f.function.function.name,parameters:f.function.parameters,description:f.function.description,strict:f.function.strict}}:f):void 0;for(let f of t.messages)this._addMessage(f,!1);for(let f=0;f<h;++f){let w=(await this._createChatCompletion(e,{...c,tool_choice:o,tools:_,messages:[...this.messages]},r)).choices[0]?.message;if(!w)throw new A("missing message in ChatCompletion response");if(!w.tool_calls?.length)return;for(let O of w.tool_calls){if(O.type!=="function")continue;let E=O.id,{name:b,arguments:S}=O.function,k=m[b];if(k){if(d&&d!==b){let C=`Invalid tool_call: ${JSON.stringify(b)}. ${JSON.stringify(d)} requested. Please try again`;this._addMessage({role:n,tool_call_id:E,content:C});continue}}else{let C=`Invalid tool_call: ${JSON.stringify(b)}. Available options are: ${Object.keys(m).map(T=>JSON.stringify(T)).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:E,content:C});continue}let H;try{H=Qo(k)?await k.parse(S):S}catch(C){let T=C instanceof Error?C.message:String(C);this._addMessage({role:n,tool_call_id:E,content:T});continue}let L=await k.function(H,this),q=u(this,Z,"m",ei).call(this,L);if(this._addMessage({role:n,tool_call_id:E,content:q}),d)return}}}};Z=new WeakSet,Sn=function(){return u(this,Z,"m",Os).call(this).content??null},Os=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(jt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new A("stream ended without producing a ChatCompletionMessage with role=assistant")},Rn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(jt(t)&&t?.tool_calls?.length)for(let r=t.tool_calls.length-1;r>=0;r--){let n=t.tool_calls[r];if(n?.type==="function")return n.function}}},kn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(vn(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},Zo=function(e){if(e.n!=null&&e.n>1)throw new A("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},ei=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var is=class s extends Ft{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,o)),n}_addMessage(e,t=!0){super._addMessage(e,t),jt(e)&&e.content&&this._emit("content",e.content)}};var D={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},Tn=class extends Error{},En=class extends Error{};function va(s,e=D.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return xa(s.trim(),e)}var xa=(s,e)=>{let t=s.length,r=0,n=_=>{throw new Tn(`${_} at position ${r}`)},o=_=>{throw new En(`${_} at position ${r}`)},i=()=>(m(),r>=t&&n("Unexpected end of input"),s[r]==='"'?c():s[r]==="{"?d():s[r]==="["?h():s.substring(r,r+4)==="null"||D.NULL&e&&t-r<4&&"null".startsWith(s.substring(r))?(r+=4,null):s.substring(r,r+4)==="true"||D.BOOL&e&&t-r<4&&"true".startsWith(s.substring(r))?(r+=4,!0):s.substring(r,r+5)==="false"||D.BOOL&e&&t-r<5&&"false".startsWith(s.substring(r))?(r+=5,!1):s.substring(r,r+8)==="Infinity"||D.INFINITY&e&&t-r<8&&"Infinity".startsWith(s.substring(r))?(r+=8,1/0):s.substring(r,r+9)==="-Infinity"||D.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(s.substring(r))?(r+=9,-1/0):s.substring(r,r+3)==="NaN"||D.NAN&e&&t-r<3&&"NaN".startsWith(s.substring(r))?(r+=3,NaN):g()),c=()=>{let _=r,f=!1;for(r++;r<t&&(s[r]!=='"'||f&&s[r-1]==="\\");)f=s[r]==="\\"?!f:!1,r++;if(s.charAt(r)=='"')try{return JSON.parse(s.substring(_,++r-Number(f)))}catch(y){o(String(y))}else if(D.STR&e)try{return JSON.parse(s.substring(_,r-Number(f))+'"')}catch{return JSON.parse(s.substring(_,s.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},d=()=>{r++,m();let _={};try{for(;s[r]!=="}";){if(m(),r>=t&&D.OBJ&e)return _;let f=c();m(),r++;try{let y=i();Object.defineProperty(_,f,{value:y,writable:!0,enumerable:!0,configurable:!0})}catch(y){if(D.OBJ&e)return _;throw y}m(),s[r]===","&&r++}}catch{if(D.OBJ&e)return _;n("Expected '}' at end of object")}return r++,_},h=()=>{r++;let _=[];try{for(;s[r]!=="]";)_.push(i()),m(),s[r]===","&&r++}catch{if(D.ARR&e)return _;n("Expected ']' at end of array")}return r++,_},g=()=>{if(r===0){s==="-"&&D.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s)}catch(f){if(D.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(f))}}let _=r;for(s[r]==="-"&&r++;s[r]&&!",]}".includes(s[r]);)r++;r==t&&!(D.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(s.substring(_,r))}catch{s.substring(_,r)==="-"&&D.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s.substring(_,s.lastIndexOf("e")))}catch(y){o(String(y))}}},m=()=>{for(;r<t&&`
11
+ \r `.includes(s[r]);)r++};return i()},$n=s=>va(s,D.ALL^D.NUM);var U,be,Bt,Ee,On,Ns,Nn,Mn,jn,Ms,Ln,ti,Qe=class s extends Ft{constructor(e){super(),U.add(this),be.set(this,void 0),Bt.set(this,void 0),Ee.set(this,void 0),P(this,be,e,"f"),P(this,Bt,[],"f")}get currentChatCompletionSnapshot(){return u(this,Ee,"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;let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),u(this,U,"m",On).call(this);let o=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let i of o)u(this,U,"m",Nn).call(this,i);if(o.controller.signal?.aborted)throw new F;return this._addChatCompletion(u(this,U,"m",Ms).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),u(this,U,"m",On).call(this),this._connected();let n=me.fromReadableStream(e,this.controller),o;for await(let i of n)o&&o!==i.id&&this._addChatCompletion(u(this,U,"m",Ms).call(this)),u(this,U,"m",Nn).call(this,i),o=i.id;if(n.controller.signal?.aborted)throw new F;return this._addChatCompletion(u(this,U,"m",Ms).call(this))}[(be=new WeakMap,Bt=new WeakMap,Ee=new WeakMap,U=new WeakSet,On=function(){this.ended||P(this,Ee,void 0,"f")},Ns=function(t){let r=u(this,Bt,"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,Bt,"f")[t.index]=r,r)},Nn=function(t){if(this.ended)return;let r=u(this,U,"m",ti).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 i=u(this,U,"m",Ns).call(this,o);o.finish_reason&&(u(this,U,"m",jn).call(this,o),i.current_tool_call_index!=null&&u(this,U,"m",Mn).call(this,o,i.current_tool_call_index));for(let c of n.delta.tool_calls??[])i.current_tool_call_index!==c.index&&(u(this,U,"m",jn).call(this,o),i.current_tool_call_index!=null&&u(this,U,"m",Mn).call(this,o,i.current_tool_call_index)),i.current_tool_call_index=c.index;for(let c of n.delta.tool_calls??[]){let d=o.message.tool_calls?.[c.index];d?.type&&(d?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:d.function?.name,index:c.index,arguments:d.function.arguments,parsed_arguments:d.function.parsed_arguments,arguments_delta:c.function?.arguments??""}):(d?.type,void 0))}}},Mn=function(t,r){if(u(this,U,"m",Ns).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 i=u(this,be,"f")?.tools?.find(c=>Zr(c)&&c.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:r,arguments:o.function.arguments,parsed_arguments:Ye(i)?i.$parseRaw(o.function.arguments):i?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},jn=function(t){let r=u(this,U,"m",Ns).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let n=u(this,U,"m",Ln).call(this);this._emit("content.done",{content:t.message.content,parsed:n?n.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Ms=function(){if(this.ended)throw new A("stream has ended, this shouldn't happen");let t=u(this,Ee,"f");if(!t)throw new A("request ended without sending any chunks");return P(this,Ee,void 0,"f"),P(this,Bt,[],"f"),Sa(t,u(this,be,"f"))},Ln=function(){let t=u(this,be,"f")?.response_format;return es(t)?t:null},ti=function(t){var r,n,o,i;let c=u(this,Ee,"f"),{choices:d,...h}=t;c?Object.assign(c,h):c=P(this,Ee,{...h,choices:[]},"f");for(let{delta:g,finish_reason:m,index:_,logprobs:f=null,...y}of t.choices){let w=c.choices[_];if(w||(w=c.choices[_]={finish_reason:m,index:_,message:{},logprobs:f,...y}),f)if(!w.logprobs)w.logprobs=Object.assign({},f);else{let{content:L,refusal:q,...C}=f;Object.assign(w.logprobs,C),L&&((r=w.logprobs).content??(r.content=[]),w.logprobs.content.push(...L)),q&&((n=w.logprobs).refusal??(n.refusal=[]),w.logprobs.refusal.push(...q))}if(m&&(w.finish_reason=m,u(this,be,"f")&&In(u(this,be,"f")))){if(m==="length")throw new Et;if(m==="content_filter")throw new $t}if(Object.assign(w,y),!g)continue;let{content:O,refusal:E,function_call:b,role:S,tool_calls:k,...H}=g;if(Object.assign(w.message,H),E&&(w.message.refusal=(w.message.refusal||"")+E),S&&(w.message.role=S),b&&(w.message.function_call?(b.name&&(w.message.function_call.name=b.name),b.arguments&&((o=w.message.function_call).arguments??(o.arguments=""),w.message.function_call.arguments+=b.arguments)):w.message.function_call=b),O&&(w.message.content=(w.message.content||"")+O,!w.message.refusal&&u(this,U,"m",Ln).call(this)&&(w.message.parsed=$n(w.message.content))),k){w.message.tool_calls||(w.message.tool_calls=[]);for(let{index:L,id:q,type:C,function:T,...$}of k){let M=(i=w.message.tool_calls)[L]??(i[L]={});Object.assign(M,$),q&&(M.id=q),C&&(M.type=C),T&&(M.function??(M.function={name:T.name??"",arguments:""})),T?.name&&(M.function.name=T.name),T?.arguments&&(M.function.arguments+=T.arguments,Go(u(this,be,"f"),M)&&(M.function.parsed_arguments=$n(M.function.arguments)))}}}return c},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,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new me(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Sa(s,e){let{id:t,choices:r,created:n,model:o,system_fingerprint:i,...c}=s,d={...c,id:t,choices:r.map(({message:h,finish_reason:g,index:m,logprobs:_,...f})=>{if(!g)throw new A(`missing finish_reason for choice ${m}`);let{content:y=null,function_call:w,tool_calls:O,...E}=h,b=h.role;if(!b)throw new A(`missing role for choice ${m}`);if(w){let{arguments:S,name:k}=w;if(S==null)throw new A(`missing function_call.arguments for choice ${m}`);if(!k)throw new A(`missing function_call.name for choice ${m}`);return{...f,message:{content:y,function_call:{arguments:S,name:k},role:b,refusal:h.refusal??null},finish_reason:g,index:m,logprobs:_}}return O?{...f,index:m,finish_reason:g,logprobs:_,message:{...E,role:b,content:y,refusal:h.refusal??null,tool_calls:O.map((S,k)=>{let{function:H,type:L,id:q,...C}=S,{arguments:T,name:$,...M}=H||{};if(q==null)throw new A(`missing choices[${m}].tool_calls[${k}].id
12
+ ${js(s)}`);if(L==null)throw new A(`missing choices[${m}].tool_calls[${k}].type
13
+ ${js(s)}`);if($==null)throw new A(`missing choices[${m}].tool_calls[${k}].function.name
14
+ ${js(s)}`);if(T==null)throw new A(`missing choices[${m}].tool_calls[${k}].function.arguments
15
+ ${js(s)}`);return{...C,id:q,type:L,function:{...M,name:$,arguments:T}}})}}:{...f,message:{...E,content:y,role:b,refusal:h.refusal??null},finish_reason:g,index:m,logprobs:_}}),created:n,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Jo(d,e)}function js(s){return JSON.stringify(s)}var as=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,o)),n}};var we=class extends l{constructor(){super(...arguments),this.messages=new Xe(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(a`/chat/completions/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chat/completions",v,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return Xo(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>ts(r,e))}runTools(e,t){return e.stream?as.runTools(this._client,e,t):is.runTools(this._client,e,t)}stream(e,t){return Qe.createChatCompletion(this._client,e,t)}};we.Messages=Xe;var $e=class extends l{constructor(){super(...arguments),this.completions=new we(this._client)}};$e.Completions=we;var Kt=class extends l{create(e,t){return this._client.post("/organization/admin_api_keys",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(a`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/admin_api_keys",v,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var zt=class extends l{list(e={},t){return this._client.getAPIList("/organization/audit_logs",x,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}};var Ut=class extends l{create(e,t){return this._client.post("/organization/certificates",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},r){return this._client.get(a`/organization/certificates/${e}`,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(a`/organization/certificates/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/certificates",x,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList("/organization/certificates/activate",X,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList("/organization/certificates/deactivate",X,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}};var qt=class extends l{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 Dt=class extends l{create(e,t){return this._client.post("/organization/invites",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(a`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/invites",x,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Ht=class extends l{create(e,t){return this._client.post("/organization/roles",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(a`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(a`/organization/roles/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/roles",B,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Wt=class extends l{create(e,t){return this._client.post("/organization/spend_alerts",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(a`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(a`/organization/spend_alerts/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/spend_alerts",x,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Jt=class extends l{audioSpeeches(e,t){return this._client.get("/organization/usage/audio_speeches",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,t){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,t){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}completions(e,t){return this._client.get("/organization/usage/completions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}costs(e,t){return this._client.get("/organization/costs",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}embeddings(e,t){return this._client.get("/organization/usage/embeddings",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,t){return this._client.get("/organization/usage/file_search_calls",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}images(e,t){return this._client.get("/organization/usage/images",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}moderations(e,t){return this._client.get("/organization/usage/moderations",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,t){return this._client.get("/organization/usage/vector_stores",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,t){return this._client.get("/organization/usage/web_search_calls",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}};var Gt=class extends l{create(e,t,r){return this._client.post(a`/organization/groups/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{group_id:n}=t;return this._client.get(a`/organization/groups/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/organization/groups/${e}/roles`,B,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{group_id:n}=t;return this._client.delete(a`/organization/groups/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Vt=class extends l{create(e,t,r){return this._client.post(a`/organization/groups/${e}/users`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{group_id:n}=t;return this._client.get(a`/organization/groups/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/organization/groups/${e}/users`,B,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{group_id:n}=t;return this._client.delete(a`/organization/groups/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Oe=class extends l{constructor(){super(...arguments),this.users=new Vt(this._client),this.roles=new Gt(this._client)}create(e,t){return this._client.post("/organization/groups",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(a`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(a`/organization/groups/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/groups",B,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};Oe.Users=Vt;Oe.Roles=Gt;var Xt=class extends l{retrieve(e,t,r){let{project_id:n}=t;return this._client.get(a`/organization/projects/${n}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/organization/projects/${e}/api_keys`,x,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(a`/organization/projects/${n}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Yt=class extends l{list(e,t={},r){return this._client.getAPIList(a`/organization/projects/${e}/certificates`,x,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}activate(e,t,r){return this._client.getAPIList(a`/organization/projects/${e}/certificates/activate`,X,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,r){return this._client.getAPIList(a`/organization/projects/${e}/certificates/deactivate`,X,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var Qt=class extends l{retrieve(e,t){return this._client.get(a`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(a`/organization/projects/${e}/data_retention`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}};var Zt=class extends l{retrieve(e,t){return this._client.get(a`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(a`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}};var er=class extends l{retrieve(e,t){return this._client.get(a`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(a`/organization/projects/${e}/model_permissions`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}};var tr=class extends l{listRateLimits(e,t={},r){return this._client.getAPIList(a`/organization/projects/${e}/rate_limits`,x,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,r){let{project_id:n,...o}=t;return this._client.post(a`/organization/projects/${n}/rate_limits/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}};var rr=class extends l{create(e,t,r){return this._client.post(a`/projects/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(a`/projects/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(a`/projects/${n}/roles/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/projects/${e}/roles`,B,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(a`/projects/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var sr=class extends l{create(e,t,r){return this._client.post(a`/organization/projects/${e}/service_accounts`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(a`/organization/projects/${n}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(a`/organization/projects/${n}/service_accounts/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/organization/projects/${e}/service_accounts`,x,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(a`/organization/projects/${n}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var nr=class extends l{create(e,t,r){return this._client.post(a`/organization/projects/${e}/spend_alerts`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(a`/organization/projects/${n}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(a`/organization/projects/${n}/spend_alerts/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/organization/projects/${e}/spend_alerts`,x,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(a`/organization/projects/${n}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var or=class extends l{create(e,t,r){let{project_id:n,...o}=t;return this._client.post(a`/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(a`/projects/${n}/groups/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t,r){let{project_id:n,...o}=t;return this._client.getAPIList(a`/projects/${n}/groups/${e}/roles`,B,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n,group_id:o}=t;return this._client.delete(a`/projects/${n}/groups/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Ze=class extends l{constructor(){super(...arguments),this.roles=new or(this._client)}create(e,t,r){return this._client.post(a`/organization/projects/${e}/groups`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n,...o}=t;return this._client.get(a`/organization/projects/${n}/groups/${e}`,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/organization/projects/${e}/groups`,B,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(a`/organization/projects/${n}/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Ze.Roles=or;var ir=class extends l{create(e,t,r){let{project_id:n,...o}=t;return this._client.post(a`/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(a`/projects/${n}/users/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t,r){let{project_id:n,...o}=t;return this._client.getAPIList(a`/projects/${n}/users/${e}/roles`,B,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n,user_id:o}=t;return this._client.delete(a`/projects/${n}/users/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var et=class extends l{constructor(){super(...arguments),this.roles=new ir(this._client)}create(e,t,r){return this._client.post(a`/organization/projects/${e}/users`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(a`/organization/projects/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(a`/organization/projects/${n}/users/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/organization/projects/${e}/users`,x,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(a`/organization/projects/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};et.Roles=ir;var W=class extends l{constructor(){super(...arguments),this.users=new et(this._client),this.serviceAccounts=new sr(this._client),this.apiKeys=new Xt(this._client),this.rateLimits=new tr(this._client),this.modelPermissions=new er(this._client),this.hostedToolPermissions=new Zt(this._client),this.groups=new Ze(this._client),this.roles=new rr(this._client),this.dataRetention=new Qt(this._client),this.spendAlerts=new nr(this._client),this.certificates=new Yt(this._client)}create(e,t){return this._client.post("/organization/projects",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(a`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(a`/organization/projects/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/projects",x,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(a`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};W.Users=et;W.ServiceAccounts=sr;W.APIKeys=Xt;W.RateLimits=tr;W.ModelPermissions=er;W.HostedToolPermissions=Zt;W.Groups=Ze;W.Roles=rr;W.DataRetention=Qt;W.SpendAlerts=nr;W.Certificates=Yt;var ar=class extends l{create(e,t,r){return this._client.post(a`/organization/users/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{user_id:n}=t;return this._client.get(a`/organization/users/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/organization/users/${e}/roles`,B,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{user_id:n}=t;return this._client.delete(a`/organization/users/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var tt=class extends l{constructor(){super(...arguments),this.roles=new ar(this._client)}retrieve(e,t){return this._client.get(a`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(a`/organization/users/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/users",x,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};tt.Roles=ar;var J=class extends l{constructor(){super(...arguments),this.auditLogs=new zt(this._client),this.adminAPIKeys=new Kt(this._client),this.usage=new Jt(this._client),this.invites=new Dt(this._client),this.users=new tt(this._client),this.groups=new Oe(this._client),this.roles=new Ht(this._client),this.dataRetention=new qt(this._client),this.spendAlerts=new Wt(this._client),this.certificates=new Ut(this._client),this.projects=new W(this._client)}};J.AuditLogs=zt;J.AdminAPIKeys=Kt;J.Usage=Jt;J.Invites=Dt;J.Users=tt;J.Groups=Oe;J.Roles=Ht;J.DataRetention=qt;J.SpendAlerts=Wt;J.Certificates=Ut;J.Projects=W;var Ne=class extends l{constructor(){super(...arguments),this.organization=new J(this._client)}};Ne.Organization=J;var ri=Symbol("brand.privateNullableHeaders");function*rc(s){if(!s)return;if(ri in s){let{values:r,nulls:n}=s;yield*r.entries();for(let o of n)yield[o,null];return}let e=!1,t;s instanceof Headers?t=s.entries():sn(s)?t=s:(e=!0,t=Object.entries(s??{}));for(let r of t){let n=r[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let o=sn(r[1])?r[1]:[r[1]],i=!1;for(let c of o)c!==void 0&&(e&&!i&&(i=!0,yield[n,null]),yield[n,c])}}var p=s=>{let e=new Headers,t=new Set;for(let r of s){let n=new Set;for(let[o,i]of rc(r)){let c=o.toLowerCase();n.has(c)||(e.delete(o),n.add(c)),i===null?(e.delete(o),t.add(c)):(e.append(o,i),t.delete(c))}}return{[ri]:!0,values:e,nulls:t}};var cr=class extends l{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:p([{Accept:"application/octet-stream"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var lr=class extends l{create(e,t){return this._client.post("/audio/transcriptions",Y({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var ur=class extends l{create(e,t){return this._client.post("/audio/translations",Y({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var fe=class extends l{constructor(){super(...arguments),this.transcriptions=new lr(this._client),this.translations=new ur(this._client),this.speech=new cr(this._client)}};fe.Transcriptions=lr;fe.Translations=ur;fe.Speech=cr;var rt=class extends l{create(e,t){return this._client.post("/batches",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/batches",v,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(a`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}};var dr=class extends l{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/assistants/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(a`/assistants/${e}`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/assistants",v,{query:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/assistants/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var hr=class extends l{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var mr=class extends l{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var Me=class extends l{constructor(){super(...arguments),this.sessions=new hr(this._client),this.transcriptionSessions=new mr(this._client)}};Me.Sessions=hr;Me.TranscriptionSessions=mr;var fr=class extends l{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(a`/chatkit/sessions/${e}/cancel`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}};var pr=class extends l{retrieve(e,t){return this._client.get(a`/chatkit/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chatkit/threads",x,{query:e,...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/chatkit/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},r){return this._client.getAPIList(a`/chatkit/threads/${e}/items`,x,{query:t,...r,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var je=class extends l{constructor(){super(...arguments),this.sessions=new fr(this._client),this.threads=new pr(this._client)}};je.Sessions=fr;je.Threads=pr;var gr=class extends l{create(e,t,r){return this._client.post(a`/threads/${e}/messages`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(a`/threads/${n}/messages/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(a`/threads/${n}/messages/${e}`,{body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/threads/${e}/messages`,v,{query:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){let{thread_id:n}=t;return this._client.delete(a`/threads/${n}/messages/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var _r=class extends l{retrieve(e,t,r){let{thread_id:n,run_id:o,...i}=t;return this._client.get(a`/threads/${n}/runs/${o}/steps/${e}`,{query:i,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t,r){let{thread_id:n,...o}=t;return this._client.getAPIList(a`/threads/${n}/runs/${e}/steps`,v,{query:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var si=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 ne=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 G,nt,Fn,pe,Ls,oe,ot,yr,st,Ks,re,Fs,Bs,us,cs,ls,ni,oi,ii,ai,ci,li,ui,Pe=class extends Te{constructor(){super(...arguments),G.add(this),Fn.set(this,[]),pe.set(this,{}),Ls.set(this,{}),oe.set(this,void 0),ot.set(this,void 0),yr.set(this,void 0),st.set(this,void 0),Ks.set(this,void 0),re.set(this,void 0),Fs.set(this,void 0),Bs.set(this,void 0),us.set(this,void 0)}[(Fn=new WeakMap,pe=new WeakMap,Ls=new WeakMap,oe=new WeakMap,ot=new WeakMap,yr=new WeakMap,st=new WeakMap,Ks=new WeakMap,re=new WeakMap,Fs=new WeakMap,Bs=new WeakMap,us=new WeakMap,G=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,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new nt;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();let n=me.fromReadableStream(e,this.controller);for await(let o of n)u(this,G,"m",cs).call(this,o);if(n.controller.signal?.aborted)throw new F;return this._addRun(u(this,G,"m",ls).call(this))}toReadableStream(){return new me(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n){let o=new nt;return o._run(()=>o._runToolAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},c=await e.submitToolOutputs(t,i,{...n,signal:this.controller.signal});this._connected();for await(let d of c)u(this,G,"m",cs).call(this,d);if(c.controller.signal?.aborted)throw new F;return this._addRun(u(this,G,"m",ls).call(this))}static createThreadAssistantStream(e,t,r){let n=new nt;return n._run(()=>n._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,r,n){let o=new nt;return o._run(()=>o._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return u(this,Fs,"f")}currentRun(){return u(this,Bs,"f")}currentMessageSnapshot(){return u(this,oe,"f")}currentRunStepSnapshot(){return u(this,us,"f")}async finalRunSteps(){return await this.done(),Object.values(u(this,pe,"f"))}async finalMessages(){return await this.done(),Object.values(u(this,Ls,"f"))}async finalRun(){if(await this.done(),!u(this,ot,"f"))throw Error("Final run was not received.");return u(this,ot,"f")}async _createThreadAssistantStream(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort()));let o={...t,stream:!0},i=await e.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(let c of i)u(this,G,"m",cs).call(this,c);if(i.controller.signal?.aborted)throw new F;return this._addRun(u(this,G,"m",ls).call(this))}async _createAssistantStream(e,t,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},c=await e.create(t,i,{...n,signal:this.controller.signal});this._connected();for await(let d of c)u(this,G,"m",cs).call(this,d);if(c.controller.signal?.aborted)throw new F;return this._addRun(u(this,G,"m",ls).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(Jr(o)&&Jr(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...n);continue}for(let i of n){if(!Jr(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let c=i.index;if(c==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof c!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${c}`);let d=o[c];d==null?o.push(i):o[c]=this.accumulateDelta(d,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${n}, accValue: ${o}`);e[r]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n){return await this._createToolAssistantStream(t,e,r,n)}};nt=Pe,cs=function(e){if(!this.ended)switch(P(this,Fs,e,"f"),u(this,G,"m",ii).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,G,"m",ui).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,G,"m",oi).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,G,"m",ni).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},ls=function(){if(this.ended)throw new A("stream has ended, this shouldn't happen");if(!u(this,ot,"f"))throw Error("Final run has not been received");return u(this,ot,"f")},ni=function(e){let[t,r]=u(this,G,"m",ci).call(this,e,u(this,oe,"f"));P(this,oe,t,"f"),u(this,Ls,"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,i=t.content[n.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=u(this,yr,"f")){if(u(this,st,"f"))switch(u(this,st,"f").type){case"text":this._emit("textDone",u(this,st,"f").text,u(this,oe,"f"));break;case"image_file":this._emit("imageFileDone",u(this,st,"f").image_file,u(this,oe,"f"));break}P(this,yr,n.index,"f")}P(this,st,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(u(this,yr,"f")!==void 0){let n=e.data.content[u(this,yr,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,u(this,oe,"f"));break;case"text":this._emit("textDone",n.text,u(this,oe,"f"));break}}u(this,oe,"f")&&this._emit("messageDone",e.data),P(this,oe,void 0,"f")}},oi=function(e){let t=u(this,G,"m",ai).call(this,e);switch(P(this,us,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,Ks,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(u(this,re,"f")&&this._emit("toolCallDone",u(this,re,"f")),P(this,Ks,o.index,"f"),P(this,re,t.step_details.tool_calls[o.index],"f"),u(this,re,"f")&&this._emit("toolCallCreated",u(this,re,"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,us,void 0,"f"),e.data.step_details.type=="tool_calls"&&u(this,re,"f")&&(this._emit("toolCallDone",u(this,re,"f")),P(this,re,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},ii=function(e){u(this,Fn,"f").push(e),this._emit("event",e)},ai=function(e){switch(e.event){case"thread.run.step.created":return u(this,pe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=u(this,pe,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let n=nt.accumulateDelta(t,r.delta);u(this,pe,"f")[e.data.id]=n}return u(this,pe,"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,pe,"f")[e.data.id]=e.data;break}if(u(this,pe,"f")[e.data.id])return u(this,pe,"f")[e.data.id];throw new Error("No snapshot available")},ci=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 i=t.content[o.index];t.content[o.index]=u(this,G,"m",li).call(this,o,i)}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")},li=function(e,t){return nt.accumulateDelta(t,e)},ui=function(e){switch(P(this,Bs,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,ot,e.data,"f"),u(this,re,"f")&&(this._emit("toolCallDone",u(this,re,"f")),P(this,re,void 0,"f"));break;case"thread.run.cancelling":break}};var it=class extends l{constructor(){super(...arguments),this.steps=new _r(this._client)}create(e,t,r){let{include:n,...o}=t;return this._client.post(a`/threads/${e}/runs`,{query:{include:n},body:o,...r,headers:p([{"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(a`/threads/${n}/runs/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(a`/threads/${n}/runs/${e}`,{body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/threads/${e}/runs`,v,{query:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,r){let{thread_id:n}=t;return this._client.post(a`/threads/${n}/runs/${e}/cancel`,{...r,headers:p([{"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 Pe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let n=p([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let c=5e3;if(r?.pollIntervalMs)c=r.pollIntervalMs;else{let d=i.headers.get("openai-poll-after-ms");if(d){let h=parseInt(d);isNaN(h)||(c=h)}}await de(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return Pe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:n,...o}=t;return this._client.post(a`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:p([{"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 Pe.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};it.Steps=_r;var Le=class extends l{constructor(){super(...arguments),this.runs=new it(this._client),this.messages=new gr(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(a`/threads/${e}`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return Pe.createThreadAssistantStream(e,this._client.beta.threads,t)}};Le.Runs=it;Le.Messages=gr;var ie=class extends l{constructor(){super(...arguments),this.realtime=new Me(this._client),this.chatkit=new je(this._client),this.assistants=new dr(this._client),this.threads=new Le(this._client)}};ie.Realtime=Me;ie.ChatKit=je;ie.Assistants=dr;ie.Threads=Le;var at=class extends l{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var Ar=class extends l{retrieve(e,t,r){let{container_id:n}=t;return this._client.get(a`/containers/${n}/files/${e}/content`,{...r,headers:p([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var ct=class extends l{constructor(){super(...arguments),this.content=new Ar(this._client)}create(e,t,r){return this._client.post(a`/containers/${e}/files`,Ce({body:t,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,r){let{container_id:n}=t;return this._client.get(a`/containers/${n}/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/containers/${e}/files`,v,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{container_id:n}=t;return this._client.delete(a`/containers/${n}/files/${e}`,{...r,headers:p([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};ct.Content=Ar;var Fe=class extends l{constructor(){super(...arguments),this.files=new ct(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/containers",v,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/containers/${e}`,{...t,headers:p([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}};Fe.Files=ct;var br=class extends l{create(e,t,r){let{include:n,...o}=t;return this._client.post(a`/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(a`/conversations/${n}/items/${e}`,{query:o,...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/conversations/${e}/items`,x,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{conversation_id:n}=t;return this._client.delete(a`/conversations/${n}/items/${e}`,{...r,__security:{bearerAuth:!0}})}};var Be=class extends l{constructor(){super(...arguments),this.items=new br(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(a`/conversations/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};Be.Items=br;var lt=class extends l{create(e,t){let r=!!e.encoding_format,n=r?e.encoding_format:"base64";r&&j(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:(j(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(c=>{let d=c.embedding;c.embedding=si(d)}),i)))}};var wr=class extends l{retrieve(e,t,r){let{eval_id:n,run_id:o}=t;return this._client.get(a`/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(a`/evals/${n}/runs/${e}/output_items`,v,{query:o,...r,__security:{bearerAuth:!0}})}};var ut=class extends l{constructor(){super(...arguments),this.outputItems=new wr(this._client)}create(e,t,r){return this._client.post(a`/evals/${e}/runs`,{body:t,...r,__security:{bearerAuth:!0}})}retrieve(e,t,r){let{eval_id:n}=t;return this._client.get(a`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/evals/${e}/runs`,v,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{eval_id:n}=t;return this._client.delete(a`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}cancel(e,t,r){let{eval_id:n}=t;return this._client.post(a`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}};ut.OutputItems=wr;var Ke=class extends l{constructor(){super(...arguments),this.runs=new ut(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(a`/evals/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/evals",v,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};Ke.Runs=ut;var dt=class extends l{create(e,t){return this._client.post("/files",Y({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(a`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/files",v,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(a`/files/${e}/content`,{...t,headers:p([{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(),i=await this.retrieve(e);for(;!i.status||!n.has(i.status);)if(await de(t),i=await this.retrieve(e),Date.now()-o>r)throw new Re({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};var Pr=class extends l{};var Ir=class extends l{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 ht=class extends l{constructor(){super(...arguments),this.graders=new Ir(this._client)}};ht.Graders=Ir;var vr=class extends l{create(e,t,r){return this._client.getAPIList(a`/fine_tuning/checkpoints/${e}/permissions`,X,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},r){return this._client.get(a`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/fine_tuning/checkpoints/${e}/permissions`,x,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{fine_tuned_model_checkpoint:n}=t;return this._client.delete(a`/fine_tuning/checkpoints/${n}/permissions/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var mt=class extends l{constructor(){super(...arguments),this.permissions=new vr(this._client)}};mt.Permissions=vr;var xr=class extends l{list(e,t={},r){return this._client.getAPIList(a`/fine_tuning/jobs/${e}/checkpoints`,v,{query:t,...r,__security:{bearerAuth:!0}})}};var ft=class extends l{constructor(){super(...arguments),this.checkpoints=new xr(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(a`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",v,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(a`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},r){return this._client.getAPIList(a`/fine_tuning/jobs/${e}/events`,v,{query:t,...r,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(a`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(a`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}};ft.Checkpoints=xr;var ae=class extends l{constructor(){super(...arguments),this.methods=new Pr(this._client),this.jobs=new ft(this._client),this.checkpoints=new mt(this._client),this.alpha=new ht(this._client)}};ae.Methods=Pr;ae.Jobs=ft;ae.Checkpoints=mt;ae.Alpha=ht;var Sr=class extends l{};var ze=class extends l{constructor(){super(...arguments),this.graderModels=new Sr(this._client)}};ze.GraderModels=Sr;var pt=class extends l{createVariation(e,t){return this._client.post("/images/variations",Y({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post("/images/edits",Y({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 gt=class extends l{retrieve(e,t){return this._client.get(a`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",X,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/models/${e}`,{...t,__security:{bearerAuth:!0}})}};var _t=class extends l{create(e,t){return this._client.post("/moderations",{body:e,...t,__security:{bearerAuth:!0}})}};var Rr=class extends l{accept(e,t,r){return this._client.post(a`/realtime/calls/${e}/accept`,{body:t,...r,headers:p([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(a`/realtime/calls/${e}/hangup`,{...t,headers:p([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,r){return this._client.post(a`/realtime/calls/${e}/refer`,{body:t,...r,headers:p([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},r){return this._client.post(a`/realtime/calls/${e}/reject`,{body:t,...r,headers:p([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};var kr=class extends l{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t,__security:{bearerAuth:!0}})}};var Ie=class extends l{constructor(){super(...arguments),this.clientSecrets=new kr(this._client),this.calls=new Rr(this._client)}};Ie.ClientSecrets=kr;Ie.Calls=Rr;function di(s,e){return!e||!Oc(e)?{...s,output_parsed:null,output:s.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:Bn(s,e)}function Bn(s,e){let t=s.output.map(n=>{if(n.type==="function_call")return{...n,parsed_arguments:jc(e,n)};if(n.type==="message"){let o=n.content.map(i=>i.type==="output_text"?{...i,parsed:$c(e,i.text)}:i);return{...n,content:o}}return n}),r=Object.assign({},s,{output:t});return Object.getOwnPropertyDescriptor(s,"output_text")||ds(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(let n of r.output)if(n.type==="message"){for(let o of n.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),r}function $c(s,e){return s.text?.format?.type!=="json_schema"?null:"$parseRaw"in s.text?.format?(s.text?.format).$parseRaw(e):JSON.parse(e)}function Oc(s){return!!es(s.text?.format)}function Nc(s){return s?.$brand==="auto-parseable-tool"}function Mc(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function jc(s,e){let t=Mc(s.tools??[],e.name);return{...e,...e,parsed_arguments:Nc(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function ds(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("")}var Cr,zs,Ue,Us,hi,mi,fi,pi,qs=class s extends Te{constructor(e){super(),Cr.add(this),zs.set(this,void 0),Ue.set(this,void 0),Us.set(this,void 0),P(this,zs,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){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),u(this,Cr,"m",hi).call(this);let o,i=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let c of o)u(this,Cr,"m",mi).call(this,c,i);if(o.controller.signal?.aborted)throw new F;return u(this,Cr,"m",fi).call(this)}[(zs=new WeakMap,Ue=new WeakMap,Us=new WeakMap,Cr=new WeakSet,hi=function(){this.ended||P(this,Ue,void 0,"f")},mi=function(t,r){if(this.ended)return;let n=(i,c)=>{(r==null||c.sequence_number>r)&&this._emit(i,c)},o=u(this,Cr,"m",pi).call(this,t);switch(n("event",t),t.type){case"response.output_text.delta":{let i=o.output[t.output_index];if(!i)throw new A(`missing output at index ${t.output_index}`);if(i.type==="message"){let c=i.content[t.content_index];if(!c)throw new A(`missing content at index ${t.content_index}`);if(c.type!=="output_text")throw new A(`expected content to be 'output_text', got ${c.type}`);n("response.output_text.delta",{...t,snapshot:c.text})}break}case"response.function_call_arguments.delta":{let i=o.output[t.output_index];if(!i)throw new A(`missing output at index ${t.output_index}`);i.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:n(t.type,t);break}},fi=function(){if(this.ended)throw new A("stream has ended, this shouldn't happen");let t=u(this,Ue,"f");if(!t)throw new A("request ended without sending any events");P(this,Ue,void 0,"f");let r=Lc(t,u(this,zs,"f"));return P(this,Us,r,"f"),r},pi=function(t){let r=u(this,Ue,"f");if(!r){if(t.type!=="response.created")throw new A(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=P(this,Ue,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let n=r.output[t.output_index];if(!n)throw new A(`missing output at index ${t.output_index}`);let o=n.type,i=t.part;o==="message"&&i.type!=="reasoning_text"?n.content.push(i):o==="reasoning"&&i.type==="reasoning_text"&&(n.content||(n.content=[]),n.content.push(i));break}case"response.output_text.delta":{let n=r.output[t.output_index];if(!n)throw new A(`missing output at index ${t.output_index}`);if(n.type==="message"){let o=n.content[t.content_index];if(!o)throw new A(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new A(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{let n=r.output[t.output_index];if(!n)throw new A(`missing output at index ${t.output_index}`);n.type==="function_call"&&(n.arguments+=t.delta);break}case"response.reasoning_text.delta":{let n=r.output[t.output_index];if(!n)throw new A(`missing output at index ${t.output_index}`);if(n.type==="reasoning"){let o=n.content?.[t.content_index];if(!o)throw new A(`missing content at index ${t.content_index}`);if(o.type!=="reasoning_text")throw new A(`expected content to be 'reasoning_text', got ${o.type}`);o.text+=t.delta}break}case"response.completed":{P(this,Ue,t.response,"f");break}}return 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,i)=>t.push({resolve:o,reject:i})).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,Us,"f");if(!e)throw new A("stream ended without producing a ChatCompletion");return e}};function Lc(s,e){return di(s,e)}var Tr=class extends l{list(e,t={},r){return this._client.getAPIList(a`/responses/${e}/input_items`,v,{query:t,...r,__security:{bearerAuth:!0}})}};var Er=class extends l{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t,__security:{bearerAuth:!0}})}};var ge=class extends l{constructor(){super(...arguments),this.inputItems=new Tr(this._client),this.inputTokens=new Er(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"&&ds(r),r))}retrieve(e,t={},r){return this._client.get(a`/responses/${e}`,{query:t,...r,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&ds(n),n))}delete(e,t){return this._client.delete(a`/responses/${e}`,{...t,headers:p([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>Bn(r,e))}stream(e,t){return qs.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(a`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post("/responses/compact",{body:e,...t,__security:{bearerAuth:!0}})}};ge.InputItems=Tr;ge.InputTokens=Er;var $r=class extends l{retrieve(e,t){return this._client.get(a`/skills/${e}/content`,{...t,headers:p([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Or=class extends l{retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(a`/skills/${n}/versions/${e}/content`,{...r,headers:p([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var yt=class extends l{constructor(){super(...arguments),this.content=new Or(this._client)}create(e,t={},r){return this._client.post(a`/skills/${e}/versions`,Ce({body:t,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(a`/skills/${n}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/skills/${e}/versions`,v,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{skill_id:n}=t;return this._client.delete(a`/skills/${n}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}};yt.Content=Or;var ve=class extends l{constructor(){super(...arguments),this.content=new $r(this._client),this.versions=new yt(this._client)}create(e={},t){return this._client.post("/skills",Ce({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(a`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(a`/skills/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/skills",v,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};ve.Content=$r;ve.Versions=yt;var Nr=class extends l{create(e,t,r){return this._client.post(a`/uploads/${e}/parts`,Y({body:t,...r,__security:{bearerAuth:!0}},this._client))}};var qe=class extends l{constructor(){super(...arguments),this.parts=new Nr(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(a`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,r){return this._client.post(a`/uploads/${e}/complete`,{body:t,...r,__security:{bearerAuth:!0}})}};qe.Parts=Nr;var gi=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 Mr=class extends l{create(e,t,r){return this._client.post(a`/vector_stores/${e}/file_batches`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(a`/vector_stores/${n}/file_batches/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,r){let{vector_store_id:n}=t;return this._client.post(a`/vector_stores/${n}/file_batches/${e}/cancel`,{...r,headers:p([{"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(a`/vector_stores/${n}/file_batches/${e}/files`,v,{query:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,r){let n=p([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse();switch(o.status){case"in_progress":let c=5e3;if(r?.pollIntervalMs)c=r.pollIntervalMs;else{let d=i.headers.get("openai-poll-after-ms");if(d){let h=parseInt(d);isNaN(h)||(c=h)}}await de(c);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,i=Math.min(o,t.length),c=this._client,d=t.values(),h=[...r];async function g(_){for(let f of _){let y=await c.files.create({file:f,purpose:"assistants"},n);h.push(y.id)}}let m=Array(i).fill(d).map(g);return await gi(m),await this.createAndPoll(e,{file_ids:h})}};var jr=class extends l{create(e,t,r){return this._client.post(a`/vector_stores/${e}/files`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(a`/vector_stores/${n}/files/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{vector_store_id:n,...o}=t;return this._client.post(a`/vector_stores/${n}/files/${e}`,{body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a`/vector_stores/${e}/files`,v,{query:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){let{vector_store_id:n}=t;return this._client.delete(a`/vector_stores/${n}/files/${e}`,{...r,headers:p([{"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=p([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(),i=o.data;switch(i.status){case"in_progress":let c=5e3;if(r?.pollIntervalMs)c=r.pollIntervalMs;else{let d=o.response.headers.get("openai-poll-after-ms");if(d){let h=parseInt(d);isNaN(h)||(c=h)}}await de(c);break;case"failed":case"completed":return i}}}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(a`/vector_stores/${n}/files/${e}/content`,X,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var xe=class extends l{constructor(){super(...arguments),this.files=new jr(this._client),this.fileBatches=new Mr(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/vector_stores/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(a`/vector_stores/${e}`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vector_stores",v,{query:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/vector_stores/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,r){return this._client.getAPIList(a`/vector_stores/${e}/search`,X,{body:t,method:"post",...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};xe.Files=jr;xe.FileBatches=Mr;var At=class extends l{create(e,t){return this._client.post("/videos",Y({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(a`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/videos",x,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post("/videos/characters",Y({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},r){return this._client.get(a`/videos/${e}/content`,{query:t,...r,headers:p([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post("/videos/edits",Y({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post("/videos/extensions",Y({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(a`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,r){return this._client.post(a`/videos/${e}/remix`,Ce({body:t,...r,__security:{bearerAuth:!0}},this._client))}};var Lr,_i,Ds,bt=class extends l{constructor(){super(...arguments),Lr.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,Lr,"m",_i).call(this,r);let o=p([t]).values,i=u(this,Lr,"m",Ds).call(this,o,"webhook-signature"),c=u(this,Lr,"m",Ds).call(this,o,"webhook-timestamp"),d=u(this,Lr,"m",Ds).call(this,o,"webhook-id"),h=parseInt(c,10);if(isNaN(h))throw new ue("Invalid webhook timestamp format");let g=Math.floor(Date.now()/1e3);if(g-h>n)throw new ue("Webhook timestamp is too old");if(h>g+n)throw new ue("Webhook timestamp is too new");let m=i.split(" ").map(w=>w.startsWith("v1,")?w.substring(3):w),_=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),f=d?`${d}.${c}.${e}`:`${c}.${e}`,y=await crypto.subtle.importKey("raw",_,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let w of m)try{let O=Buffer.from(w,"base64");if(await crypto.subtle.verify("HMAC",y,O,new TextEncoder().encode(f)))return}catch{continue}throw new ue("The given webhook signature does not match the expected signature")}};Lr=new WeakSet,_i=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")},Ds=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 Kn,zn,Hs,Ai,Wc="workload-identity-auth",I=class{constructor({baseURL:e=ne("OPENAI_BASE_URL"),apiKey:t=ne("OPENAI_API_KEY")??null,adminAPIKey:r=ne("OPENAI_ADMIN_KEY")??null,organization:n=ne("OPENAI_ORG_ID")??null,project:o=ne("OPENAI_PROJECT_ID")??null,webhookSecret:i=ne("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:c,...d}={}){Kn.add(this),Hs.set(this,void 0),this.completions=new at(this),this.chat=new $e(this),this.embeddings=new lt(this),this.files=new dt(this),this.images=new pt(this),this.audio=new fe(this),this.moderations=new _t(this),this.models=new gt(this),this.fineTuning=new ae(this),this.graders=new ze(this),this.vectorStores=new xe(this),this.webhooks=new bt(this),this.beta=new ie(this),this.batches=new rt(this),this.uploads=new qe(this),this.admin=new Ne(this),this.responses=new ge(this),this.realtime=new Ie(this),this.conversations=new Be(this),this.evals=new Ke(this),this.containers=new Fe(this),this.skills=new ve(this),this.videos=new At(this);let h={apiKey:t,adminAPIKey:r,organization:n,project:o,webhookSecret:i,workloadIdentity:c,...d,baseURL:e||"https://api.openai.com/v1"};if(t&&c)throw new A("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!t&&!r&&!c)throw new A("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!h.dangerouslyAllowBrowser&&Po())throw new A(`It looks like you're running in a browser-like environment.
16
16
 
17
17
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
18
18
  If you understand the risks and have appropriate mitigations in place,
@@ -21,27 +21,28 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
21
21
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
22
22
 
23
23
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
24
- `);this.baseURL=h.baseURL,this.timeout=h.timeout??Fn.DEFAULT_TIMEOUT,this.logger=h.logger??console;let g="warn";this.logLevel=g,this.logLevel=mn(h.logLevel,"ClientOptions.logLevel",this)??mn(ne("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??g,this.fetchOptions=h.fetchOptions,this.maxRetries=h.maxRetries??2,this.fetch=h.fetch??gs(),P(this,qs,bo,"f");let m=ne("OPENAI_CUSTOM_HEADERS");if(m){let _={};for(let f of m.split(`
25
- `)){let y=f.indexOf(":");y>=0&&(_[f.substring(0,y).trim()]=f.substring(y+1).trim())}h.defaultHeaders=p([_,h.defaultHeaders])}this._options=h,c&&(this._workloadIdentityAuth=new Is(c,this.fetch)),this.apiKey=typeof t=="string"?t:null,this.adminAPIKey=r,this.organization=n,this.project=o,this.webhookSecret=i}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},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 p([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return p([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return p([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return p([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Co(e)}getUserAgent(){return`${this.constructor.name}/JS ${ke}`}defaultIdempotencyKey(){return`stainless-node-retry-${Zs()}`}makeStatusError(e,t,r,n){return N.generate(e,t,r,n)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(r){throw r instanceof A?r:new A(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!="string"||!t)throw new A(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let n=!u(this,Ln,"m",fi).call(this)&&r||this.baseURL,o=lo(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),c=Object.fromEntries(o.searchParams);return(!tn(i)||!tn(c))&&(t={...c,...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){(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 Ge(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:i,url:c,timeout:d}=await this.buildRequest(n,{retryCount:o-t});await this.prepareRequest(i,{url:c,options:n});let h="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=r===void 0?"":`, retryOf: ${r}`,m=Date.now();if(j(this).debug(`[${h}] sending request`,ye({retryOfRequestLogID:r,method:n.method,url:c,options:n,headers:i.headers})),n.signal?.aborted)throw new F;let _=n.__security??{bearerAuth:!0},f=new AbortController,y=await this.fetchWithAuth(c,i,d,f,_).catch(Ur),w=Date.now();if(y instanceof globalThis.Error){let b=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new F;let S=zr(y)||/timed? ?out/i.test(String(y)+("cause"in y?String(y.cause):""));if(t)return j(this).info(`[${h}] connection ${S?"timed out":"failed"} - ${b}`),j(this).debug(`[${h}] connection ${S?"timed out":"failed"} (${b})`,ye({retryOfRequestLogID:r,url:c,durationMs:w-m,message:y.message})),this.retryRequest(n,t,r??h);throw j(this).info(`[${h}] connection ${S?"timed out":"failed"} - error; no more retries left`),j(this).debug(`[${h}] connection ${S?"timed out":"failed"} (error; no more retries left)`,ye({retryOfRequestLogID:r,url:c,durationMs:w-m,message:y.message})),y instanceof We||y instanceof qr?y:S?new Re:new Se({message:Bc(y),cause:y})}let O=[...y.headers.entries()].filter(([b])=>b==="x-request-id").map(([b,S])=>", "+b+": "+JSON.stringify(S)).join(""),E=`[${h}${g}${O}] ${i.method} ${c} ${y.ok?"succeeded":"failed"} with status ${y.status} in ${w-m}ms`;if(!y.ok){if(y.status===401&&this._workloadIdentityAuth&&_.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await nn(y.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},t,r??h);let b=await this.shouldRetry(y);if(t&&b){let C=`retrying, ${t} attempts remaining`;return await nn(y.body),j(this).info(`${E} - ${C}`),j(this).debug(`[${h}] response error (${C})`,ye({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,durationMs:w-m})),this.retryRequest(n,t,r??h,y.headers)}let S=b?"error; no more retries left":"error; not retryable";j(this).info(`${E} - ${S}`);let k=await y.text().catch(C=>Ur(C).message),H=mo(k),L=H?void 0:k;throw j(this).debug(`[${h}] response error (${S})`,ye({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,message:L,durationMs:Date.now()-m})),this.makeStatusError(y.status,H,L,y.headers)}return j(this).info(E),j(this).debug(`[${h}] response start`,ye({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,durationMs:w-m})),{response:y,options:n,controller:f,requestLogID:h,retryOfRequestLogID:r,startTime:m}}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 Gr(this,r,e)}async fetchWithAuth(e,t,r,n,o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&o.bearerAuth){let c=t.headers,d=c.get("Authorization");if(!d||d===`Bearer ${Kc}`){let h=await this._workloadIdentityAuth.getToken();c.set("Authorization",`Bearer ${h}`)}}return await this.fetchWithTimeout(e,t,r,n)}async fetchWithTimeout(e,t,r,n){let{signal:o,method:i,...c}=t||{},d=this._makeAbort(n);o&&o.addEventListener("abort",d,{once:!0});let h=setTimeout(d,r),g=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,m={signal:n.signal,...g?{duplex:"half"}:{},method:"GET",...c};i&&(m.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(h)}}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,i=n?.get("retry-after-ms");if(i){let d=parseFloat(i);Number.isNaN(d)||(o=d)}let c=n?.get("retry-after");if(c&&!o){let d=parseFloat(c);Number.isNaN(d)?o=Date.parse(c)-Date.now():o=d*1e3}if(o===void 0){let d=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,d)}return await ue(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,i=Math.min(.5*Math.pow(2,o),8),c=1-Math.random()*.25;return i*c*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:n,path:o,query:i,defaultBaseURL:c}=r,d=this.buildURL(o,i,c);"timeout"in r&&ho("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:h,body:g,isStreamingBody:m}=this.buildBody({options:r});m&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let _=await this.buildHeaders({options:e,method:n,bodyHeaders:h,retryCount:t});return{req:{method:n,headers:_,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&g instanceof globalThis.ReadableStream&&{duplex:"half"},...g&&{body:g},...this.fetchOptions??{},...r.fetchOptions??{}},url:d,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 i=p([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))}:{},...yo(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i,e.__security??{bearerAuth:!0}),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let r=p([t]),n=typeof globalThis.ReadableStream<"u"&&e instanceof globalThis.ReadableStream,o=!n&&(typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof globalThis.Blob<"u"&&e instanceof globalThis.Blob||e instanceof URLSearchParams||e instanceof FormData);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||n?{bodyHeaders:void 0,body:e,isStreamingBody:!o}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:_s(e),isStreamingBody:!0}:typeof e=="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e),isStreamingBody:!1}:{...u(this,qs,"f").call(this,{body:e,headers:r}),isStreamingBody:!1}}};Fn=I,qs=new WeakMap,Ln=new WeakSet,fi=function(){return this.baseURL!=="https://api.openai.com/v1"};I.OpenAI=Fn;I.DEFAULT_TIMEOUT=6e5;I.OpenAIError=A;I.APIError=N;I.APIConnectionError=Se;I.APIConnectionTimeoutError=Re;I.APIUserAbortError=F;I.NotFoundError=xt;I.ConflictError=vt;I.RateLimitError=Rt;I.BadRequestError=wt;I.AuthenticationError=Pt;I.InternalServerError=kt;I.PermissionDeniedError=It;I.UnprocessableEntityError=St;I.InvalidWebhookSignatureError=le;I.toFile=vs;I.Completions=it;I.Chat=$e;I.Embeddings=ct;I.Files=ut;I.Images=ft;I.Audio=me;I.Moderations=gt;I.Models=pt;I.FineTuning=ae;I.Graders=ze;I.VectorStores=ve;I.Webhooks=At;I.Beta=ie;I.Batches=tt;I.Uploads=qe;I.Admin=Ne;I.Responses=pe;I.Realtime=Ie;I.Conversations=Ke;I.Evals=Be;I.Containers=Fe;I.Skills=xe;I.Videos=yt;function Bc(s){if(zc(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 zc(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 hs="2024-11-05",Ys="ccr-toolhub",jr="tool_hub.resolve",Js="tool_hub.invoke",He=6e4,Qn=10,Uc=1e4,qc=5*6e4,Zn,B=Buffer.alloc(0),$i="content-length";process.stdin.on("data",s=>{B=Buffer.concat([B,Buffer.isBuffer(s)?s:Buffer.from(s)]),Dc().catch(e=>{Vs(bt(null,-32603,Lr(e)),$i)})});process.stdin.resume();process.on("exit",()=>{Zn.close()});async function Dc(){for(;;){if(Hc(),B.length===0)return;if(!Wc(B)){let c=B.indexOf(`
26
- `);if(c<0)return;let d=B.subarray(0,c).toString("utf8").trim();if(B=B.subarray(c+1),!d)continue;await pi(d,"newline-json");continue}let s=B.indexOf(`\r
24
+ `);this.baseURL=h.baseURL,this.timeout=h.timeout??zn.DEFAULT_TIMEOUT,this.logger=h.logger??console;let g="warn";this.logLevel=g,this.logLevel=gn(h.logLevel,"ClientOptions.logLevel",this)??gn(ne("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??g,this.fetchOptions=h.fetchOptions,this.maxRetries=h.maxRetries??2,this.fetch=h.fetch??ys(),P(this,Hs,xo,"f");let m=ne("OPENAI_CUSTOM_HEADERS");if(m){let _={};for(let f of m.split(`
25
+ `)){let y=f.indexOf(":");y>=0&&(_[f.substring(0,y).trim()]=f.substring(y+1).trim())}h.defaultHeaders=p([_,h.defaultHeaders])}this._options=h,c&&(this._workloadIdentityAuth=new xs(c,this.fetch)),this.apiKey=typeof t=="string"?t:null,this.adminAPIKey=r,this.organization=n,this.project=o,this.webhookSecret=i}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},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 p([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return p([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return p([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return p([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return No(e)}getUserAgent(){return`${this.constructor.name}/JS ${ke}`}defaultIdempotencyKey(){return`stainless-node-retry-${rn()}`}makeStatusError(e,t,r,n){return N.generate(e,t,r,n)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(r){throw r instanceof A?r:new A(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!="string"||!t)throw new A(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let n=!u(this,Kn,"m",Ai).call(this)&&r||this.baseURL,o=po(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),c=Object.fromEntries(o.searchParams);return(!nn(i)||!nn(c))&&(t={...c,...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new Ve(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let n=await e,o=n.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(n);let{req:i,url:c,timeout:d}=await this.buildRequest(n,{retryCount:o-t});await this.prepareRequest(i,{url:c,options:n});let h="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=r===void 0?"":`, retryOf: ${r}`,m=Date.now();if(j(this).debug(`[${h}] sending request`,ye({retryOfRequestLogID:r,method:n.method,url:c,options:n,headers:i.headers})),n.signal?.aborted)throw new F;let _=n.__security??{bearerAuth:!0},f=new AbortController,y=await this.fetchWithAuth(c,i,d,f,_).catch(Hr),w=Date.now();if(y instanceof globalThis.Error){let b=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new F;let S=Dr(y)||/timed? ?out/i.test(String(y)+("cause"in y?String(y.cause):""));if(t)return j(this).info(`[${h}] connection ${S?"timed out":"failed"} - ${b}`),j(this).debug(`[${h}] connection ${S?"timed out":"failed"} (${b})`,ye({retryOfRequestLogID:r,url:c,durationMs:w-m,message:y.message})),this.retryRequest(n,t,r??h);throw j(this).info(`[${h}] connection ${S?"timed out":"failed"} - error; no more retries left`),j(this).debug(`[${h}] connection ${S?"timed out":"failed"} (error; no more retries left)`,ye({retryOfRequestLogID:r,url:c,durationMs:w-m,message:y.message})),y instanceof Je||y instanceof Wr?y:S?new Re:new Se({message:Jc(y),cause:y})}let O=[...y.headers.entries()].filter(([b])=>b==="x-request-id").map(([b,S])=>", "+b+": "+JSON.stringify(S)).join(""),E=`[${h}${g}${O}] ${i.method} ${c} ${y.ok?"succeeded":"failed"} with status ${y.status} in ${w-m}ms`;if(!y.ok){if(y.status===401&&this._workloadIdentityAuth&&_.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await cn(y.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},t,r??h);let b=await this.shouldRetry(y);if(t&&b){let C=`retrying, ${t} attempts remaining`;return await cn(y.body),j(this).info(`${E} - ${C}`),j(this).debug(`[${h}] response error (${C})`,ye({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,durationMs:w-m})),this.retryRequest(n,t,r??h,y.headers)}let S=b?"error; no more retries left":"error; not retryable";j(this).info(`${E} - ${S}`);let k=await y.text().catch(C=>Hr(C).message),H=yo(k),L=H?void 0:k;throw j(this).debug(`[${h}] response error (${S})`,ye({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,message:L,durationMs:Date.now()-m})),this.makeStatusError(y.status,H,L,y.headers)}return j(this).info(E),j(this).debug(`[${h}] response start`,ye({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,durationMs:w-m})),{response:y,options:n,controller:f,requestLogID:h,retryOfRequestLogID:r,startTime:m}}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 Yr(this,r,e)}async fetchWithAuth(e,t,r,n,o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&o.bearerAuth){let c=t.headers,d=c.get("Authorization");if(!d||d===`Bearer ${Wc}`){let h=await this._workloadIdentityAuth.getToken();c.set("Authorization",`Bearer ${h}`)}}return await this.fetchWithTimeout(e,t,r,n)}async fetchWithTimeout(e,t,r,n){let{signal:o,method:i,...c}=t||{},d=this._makeAbort(n);o&&o.addEventListener("abort",d,{once:!0});let h=setTimeout(d,r),g=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,m={signal:n.signal,...g?{duplex:"half"}:{},method:"GET",...c};i&&(m.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(h)}}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,i=n?.get("retry-after-ms");if(i){let d=parseFloat(i);Number.isNaN(d)||(o=d)}let c=n?.get("retry-after");if(c&&!o){let d=parseFloat(c);Number.isNaN(d)?o=Date.parse(c)-Date.now():o=d*1e3}if(o===void 0){let d=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,d)}return await de(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,i=Math.min(.5*Math.pow(2,o),8),c=1-Math.random()*.25;return i*c*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:n,path:o,query:i,defaultBaseURL:c}=r,d=this.buildURL(o,i,c);"timeout"in r&&_o("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:h,body:g,isStreamingBody:m}=this.buildBody({options:r});m&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let _=await this.buildHeaders({options:e,method:n,bodyHeaders:h,retryCount:t});return{req:{method:n,headers:_,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&g instanceof globalThis.ReadableStream&&{duplex:"half"},...g&&{body:g},...this.fetchOptions??{},...r.fetchOptions??{}},url:d,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 i=p([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))}:{},...Io(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i,e.__security??{bearerAuth:!0}),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let r=p([t]),n=typeof globalThis.ReadableStream<"u"&&e instanceof globalThis.ReadableStream,o=!n&&(typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof globalThis.Blob<"u"&&e instanceof globalThis.Blob||e instanceof URLSearchParams||e instanceof FormData);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||n?{bodyHeaders:void 0,body:e,isStreamingBody:!o}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:As(e),isStreamingBody:!0}:typeof e=="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e),isStreamingBody:!1}:{...u(this,Hs,"f").call(this,{body:e,headers:r}),isStreamingBody:!1}}};zn=I,Hs=new WeakMap,Kn=new WeakSet,Ai=function(){return this.baseURL!=="https://api.openai.com/v1"};I.OpenAI=zn;I.DEFAULT_TIMEOUT=6e5;I.OpenAIError=A;I.APIError=N;I.APIConnectionError=Se;I.APIConnectionTimeoutError=Re;I.APIUserAbortError=F;I.NotFoundError=St;I.ConflictError=Rt;I.RateLimitError=Ct;I.BadRequestError=It;I.AuthenticationError=vt;I.InternalServerError=Tt;I.PermissionDeniedError=xt;I.UnprocessableEntityError=kt;I.InvalidWebhookSignatureError=ue;I.toFile=Rs;I.Completions=at;I.Chat=$e;I.Embeddings=lt;I.Files=dt;I.Images=pt;I.Audio=fe;I.Moderations=_t;I.Models=gt;I.FineTuning=ae;I.Graders=ze;I.VectorStores=xe;I.Webhooks=bt;I.Beta=ie;I.Batches=rt;I.Uploads=qe;I.Admin=Ne;I.Responses=ge;I.Realtime=Ie;I.Conversations=Be;I.Evals=Ke;I.Containers=Fe;I.Skills=ve;I.Videos=At;function Jc(s){if(Gc(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 Gc(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 fs="2024-11-05",en="ccr-toolhub",wt="tool_hub.resolve",Vs="tool_hub.invoke",We=6e4,so=10,Vc=1e4,Xc=5*6e4,bi=["Treat executionPlanJs as the dependency plan for ToolHub invocations.","Each callTool(toolName, args) call maps to one tool_hub.invoke call with tool=toolName and args=args.","await means the next ToolHub invocation depends on the previous result and must not be started early.","Only callTool calls inside the same Promise.all([...]) expression may be issued as parallel tool calls.","If a later call needs values from an earlier result, wait for that earlier result and fill the arguments after it returns."].join(" "),Yc=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield".split(" ")),no,K=Buffer.alloc(0),Fi="content-length";process.stdin.on("data",s=>{K=Buffer.concat([K,Buffer.isBuffer(s)?s:Buffer.from(s)]),Qc().catch(e=>{Qs(Pt(null,-32603,Kr(e)),Fi)})});process.stdin.resume();process.on("exit",()=>{no.close()});async function Qc(){for(;;){if(Zc(),K.length===0)return;if(!el(K)){let c=K.indexOf(`
26
+ `);if(c<0)return;let d=K.subarray(0,c).toString("utf8").trim();if(K=K.subarray(c+1),!d)continue;await wi(d,"newline-json");continue}let s=K.indexOf(`\r
27
27
  \r
28
- `);if(s<0)return;let t=B.subarray(0,s).toString("utf8").match(/content-length:\s*(\d+)/i);if(!t){B=B.subarray(s+4),Vs(bt(null,-32600,"Missing Content-Length header."),"content-length");continue}let r=Number(t[1]),n=s+4,o=n+r;if(B.length<o)return;let i=B.subarray(n,o).toString("utf8");B=B.subarray(o),await pi(i,"content-length")}}function Hc(){for(;B[0]===10||B[0]===13;)B=B.subarray(1)}function Wc(s){return/^content-length\s*:/i.test(s.subarray(0,Math.min(s.length,64)).toString("utf8"))}async function pi(s,e){$i=e;let t;try{t=JSON.parse(s)}catch(n){Vs(bt(null,-32700,`Invalid JSON-RPC request: ${Lr(n)}`),e);return}let r=await Jc(t);r&&Vs(r,e)}async function Jc(s){if(!R(s))return bt(null,-32600,"JSON-RPC request must be an object.");let e=s,t=e.id??null;if(!(e.id===void 0&&e.method?.startsWith("notifications/"))){if(e.jsonrpc!=="2.0"||!e.method)return bt(t,-32600,"Invalid JSON-RPC 2.0 request.");try{switch(e.method){case"initialize":return Ds(t,{capabilities:{tools:{}},protocolVersion:hs,serverInfo:{name:Ys,title:"CCR ToolHub",version:"1.0.0"}});case"ping":return Ds(t,{});case"tools/list":return Ds(t,{tools:il()});case"tools/call":return Ds(t,await Zn.callTool(e.params));default:return bt(t,-32601,`Unsupported MCP method: ${e.method}`)}}catch(r){return bt(t,-32603,Lr(r))}}}var zn=class{clients=new Map;registry=new Un((e,t)=>this.clientForServer(e,t));sessions=new Map;async callTool(e){let t=R(e)&&typeof e.name=="string"?e.name.trim():"",r=R(e)&&R(e.arguments)?e.arguments:{};if(t===jr||t==="tool_hub_resolve"||t==="code_tool.resolve"||t==="code_tool_resolve")return this.resolveTools(r);if(t===Js||t==="tool_hub_invoke"||t==="code_tool.invoke"||t==="code_tool_invoke")return this.invokeTool(r);throw new Error(`Unknown ToolHub meta tool: ${t}`)}close(){for(let e of this.clients.values())e.client.close();this.clients.clear(),this.sessions.clear()}async resolveTools(e){let t=typeof e.task=="string"?e.task.trim():"";if(!t)throw new Error(`${jr} requires task.`);let r=zl(e.constraints?.maxTools??Si("TOOLHUB_MAX_TOOLS",Qn)),n=this.scopeKey(e),o=this.session(n),i=Kl(t);this.registry.updateServers(Kn());let c=await this.registry.listTools();if(c.length===0&&(await this.registry.refreshServers(void 0,!0),c=await this.registry.listTools()),c.length===0)throw new Error("No MCP tools are available to resolve.");let d=this.findRecentlyResolvedTask(n,i);if(d){let m=d.toolNames.map(_=>this.resolveCatalogEntry(_,c)).filter(_=>!!_);if(m.length>0)return this.markToolsLoaded(n,m),Hs(this.buildRepeatedResolveOutput(m))}let h=o.inFlightResolves.get(i);if(h){let m=await h,_=m.selectedTools.map(f=>this.resolveCatalogEntry(f.toolName,c)??f).filter(f=>!!f);return _.length>0?(this.markToolsLoaded(n,_),Hs(this.buildRepeatedResolveOutput(_))):Hs(m)}let g=this.executeFreshResolve({catalog:c,context:e.context,maxTools:r,observations:o.recentObservations.slice(-5),scopeKey:n,task:t,taskHash:i,timeoutMs:e.constraints?.latencyBudgetMs,withoutSideEffects:e.constraints?.allowSideEffects===!1});o.inFlightResolves.set(i,g);try{return Hs(await g)}finally{o.inFlightResolves.get(i)===g&&o.inFlightResolves.delete(i)}}async invokeTool(e){let t=typeof e.tool=="string"?e.tool.trim():"";if(!t)throw new Error(`${Js} requires tool.`);let r=this.scopeKey(e);this.registry.updateServers(Kn());let n=await this.registry.listTools(),o=this.resolveCatalogEntry(t,n);if(!o)return vi("UNKNOWN_TOOL",`Unknown ToolHub tool: ${t}`);if(!this.session(r).loadedTools.has(o.toolName))return vi("TOOL_NOT_RESOLVED",`Tool ${o.toolName} is not loaded in this session. Call ${jr} for the task first.`);let i=R(e.args)?e.args:{},d=await this.clientForServer(o.serverName).callTool(o.remoteToolName,i);return this.rememberObservation(r,o.toolName,d),d}async executeFreshResolve(e){let t,r="llm",n=!0;try{t=await this.resolveCatalogWithLlm(e)}catch(i){if(t=this.resolveCatalogLocally({...e,error:i}),t.selectedTools.length===0)throw i;r="local",n=!1}let o=t.selectedTools;if(e.withoutSideEffects&&(o=o.filter(i=>!i.invocation.sideEffect)),o.length===0)throw new Error("ToolHub could not resolve any matching MCP tools for this task.");return this.markToolsLoaded(e.scopeKey,o),this.rememberResolvedTask(e.scopeKey,e.taskHash,o),{...this.buildResolveOutput(t.summary,o),plannedSteps:t.plannedSteps,referencedTokens:t.referencedTokens,retriever:r,usedLlm:n,workflowSketch:t.workflowSketch}}async resolveCatalogWithLlm(e){let r=await new Wn({openAiApiKey:De("TOOLHUB_OPENAI_API_KEY"),openAiBaseUrl:De("TOOLHUB_OPENAI_BASE_URL")||"https://api.openai.com/v1",openAiModel:De("TOOLHUB_OPENAI_MODEL")}).search({catalog:e.catalog.map(ml),code:JSON.stringify({context:e.context??{},observations:e.observations??[]}),query:e.task,timeoutMs:e.timeoutMs??Si("TOOLHUB_REQUEST_TIMEOUT_MS",He),topK:e.maxTools}),n=r.selectedToolNames.map(o=>this.resolveCatalogEntry(o,e.catalog)).filter(o=>!!o).slice(0,e.maxTools);return{plannedSteps:r.plannedSteps,referencedTokens:r.referencedTokens,selectedTools:n,summary:r.summary,workflowSketch:r.workflowSketch}}resolveCatalogLocally(e){let t=[e.task,e.context?JSON.stringify(e.context):"",...e.observations.map(i=>`${i.toolName} ${i.resultSummary}`)].join(" "),r=Rl(t),n=e.catalog.map((i,c)=>({index:c,score:Sl(t,i,r),tool:i})).filter(i=>i.score>0).sort((i,c)=>c.score-i.score||i.index-c.index),o=Cl(n.map(i=>i.tool)).slice(0,e.maxTools);return{plannedSteps:o.length>0?["Resolve retrieval LLM did not finish within the latency budget.","Selected candidate tools with local catalog matching."]:void 0,referencedTokens:Gs(t),selectedTools:o,summary:`Resolve retrieval fell back to local catalog matching after LLM retrieval failed: ${Lr(e.error)}.`,workflowSketch:Tl(o)}}clientForServer(e,t){let r=t??Kn().find(c=>c.name===e);if(!r)throw new Error(`ToolHub backend MCP server not found: ${e}`);let n=this.clients.get(e),o=Mi(r);if(n&&n.configHash===o)return n.client;n?.client.close();let i=r.transport==="stdio"?new Hn(r):r.transport==="sse"?new qn(r):new Dn(r);return this.clients.set(e,{client:i,configHash:o}),i}resolveCatalogEntry(e,t){let r=Ws(t.map(n=>({alias:n.alias,canonicalName:n.canonicalName,name:n.toolName,remoteToolName:n.remoteToolName})),e);if(r)return t.find(n=>n.toolName===r)}buildResolveOutput(e,t){return{nextAction:this.buildResolveNextAction(t),reasoningSummary:e,runtimeContext:{availableContextKeys:["selectedTools"],summary:t.map(r=>`${r.toolName}: ${r.description||r.title}`)},selectedToolNames:t.map(r=>r.toolName),selectedTools:t,tsDefinitions:Pl(t)}}buildRepeatedResolveOutput(e){let t=this.buildResolveNextAction(e);return{alreadyResolved:!0,nextAction:t,reasoningSummary:["This task has already been resolved in the current ToolHub session.",t.instruction].join(" "),runtimeContext:{availableContextKeys:["selectedTools","nextAction"],summary:["The selected tools are already loaded for tool_hub.invoke.","Do not repeat discovery for this task.",t.instruction]},selectedToolNames:e.map(r=>r.toolName),selectedTools:e}}buildResolveNextAction(e){let t=e.map(d=>({requiredArguments:ds(d.inputSchema),sideEffect:d.invocation.sideEffect,toolName:d.toolName})).filter(d=>d.requiredArguments.length>0),r=e.filter(d=>d.invocation.sideEffect).map(d=>d.toolName),n=Ol(e),o=n?ds(n.inputSchema):[],i=o.length>0?{missingArguments:o,toolName:n?.toolName,type:"ask_user"}:{toolName:n?.toolName,type:"invoke_tool"},c=["Do not call tool_hub.resolve again for this task."];return n&&o.length>0?c.push(`Ask the user for missing required arguments for ${n.toolName}: ${o.join(", ")}.`):n?c.push(`Call tool_hub.invoke for ${n.toolName}.`):c.push("Ask the user for the missing task details before invoking tools."),r.length>0&&c.push(`Before calling side-effecting tools, ask for explicit confirmation: ${r.join(", ")}.`),{confirmationRequiredFor:r,firstAction:i,instruction:c.join(" "),requiredArgumentsByTool:t}}scopeKey(e){return xi(e.__toolHubScopeKey)||xi(e.__codeToolScopeKey)||"default"}session(e){let t=this.sessions.get(e);if(t)return t;let r={inFlightResolves:new Map,loadedTools:new Set,recentObservations:[],recentlyResolvedTasks:[]};return this.sessions.set(e,r),r}markToolsLoaded(e,t){let r=this.session(e);for(let n of t)r.loadedTools.add(n.toolName)}rememberResolvedTask(e,t,r){let n=this.session(e);n.recentlyResolvedTasks=n.recentlyResolvedTasks.filter(o=>o.taskHash!==t),n.recentlyResolvedTasks.unshift({observationCount:n.recentObservations.length,resolvedAt:Date.now(),taskHash:t,toolNames:r.map(o=>o.toolName)}),n.recentlyResolvedTasks=n.recentlyResolvedTasks.slice(0,10)}findRecentlyResolvedTask(e,t){let r=this.session(e),n=Date.now();return r.recentlyResolvedTasks=r.recentlyResolvedTasks.filter(o=>n-o.resolvedAt<=qc),r.recentlyResolvedTasks.find(o=>o.taskHash===t)}rememberObservation(e,t,r){let n=this.session(e);n.recentObservations.push({resultSummary:Bl(r),toolName:t}),n.recentObservations=n.recentObservations.slice(-20)}},Un=class{constructor(e){this.clientFactory=e}clientFactory;discoveryPromise;entries=new Map;updateServers(e){let t=new Set;for(let r of e){t.add(r.name);let n=Mi(r),o=this.entries.get(r.name);if(o&&o.configHash===n){o.config=bi(r);continue}let i=wi.readDiscovery(r.name,n);this.entries.set(r.name,{config:bi(r),configHash:n,lastCheckedAt:i?.cachedAt,lastSeenOnlineAt:i?.lastSeenOnlineAt,loadedFromCache:!!i,status:"unknown",tools:i?.tools.map(c=>({...c}))??[]})}for(let r of this.entries.keys())t.has(r)||this.entries.delete(r)}async listTools(){return await this.ensureDiscoveryFresh(),this.listCatalogEntriesSync()}async refreshServers(e,t=!0){let r=jl(e,this.entries);if(r.length!==0&&!(this.discoveryPromise&&(await this.discoveryPromise,!t))){this.discoveryPromise=this.performDiscovery(r,t);try{await this.discoveryPromise}finally{this.discoveryPromise=void 0}}}async ensureDiscoveryFresh(e=Uc){let t=[...this.entries.values()].filter(r=>!r.loadedFromCache&&(!r.lastCheckedAt||Date.now()-r.lastCheckedAt>e)).map(r=>r.config.name);t.length!==0&&await this.refreshServers(t,!1)}listCatalogEntriesSync(){let e=hl([...this.entries.values()].map(r=>r.config.name)),t=[];for(let r of this.entries.values()){let n=e.get(r.config.name)??ge(r.config.name);for(let o of r.tools){let i=o.name.trim();if(!i)continue;let c=`mcp.${n}.${i}`;t.push({alias:ge(c),canonicalName:`${r.config.name}.${i}`,description:o.description??"",inputSchema:o.inputSchema,invocation:El(o),outputSchema:o.outputSchema,remoteToolName:i,serverId:r.config.name,serverLabel:r.config.label,serverName:r.config.name,serverNamespace:n,status:r.status,tags:o.tags??[],title:o.title||o.name,toolName:c})}}return t.sort((r,n)=>r.toolName.localeCompare(n.toolName))}async performDiscovery(e,t){for(let r of e){let n=this.entries.get(r);n&&(!t&&n.lastCheckedAt&&Date.now()-n.lastCheckedAt<3e3||await this.probeServer(n.config))}}async probeServer(e){let t=Date.now();try{let r=await this.clientFactory(e.name,e).listTools(),n=this.entries.get(e.name);if(!n)return;n.status="online",n.tools=r.map(o=>({...o})),n.lastCheckedAt=t,n.lastSeenOnlineAt=t,n.loadedFromCache=!0,n.error=void 0,wi.writeDiscovery(e.name,n.configHash,n.tools,t)}catch(r){let n=this.entries.get(e.name);if(!n)return;n.status="offline",n.lastCheckedAt=t,n.loadedFromCache=!1,n.error=Lr(r)}}};Zn=new zn;var qn=class{constructor(e){this.server=e}server;endpointUrl="";initialized=!1;nextId=1;openPromise;pending=new Map;streamAbort;streamBuffer="";async listTools(){await this.ensureInitialized();let e=await this.request("tools/list",{});return eo(e)}async callTool(e,t){return await this.ensureInitialized(),this.request("tools/call",{name:e,arguments:t})}async close(){this.initialized=!1,this.endpointUrl="",this.streamAbort?.abort(),this.streamAbort=void 0,this.rejectAll(new Error(`MCP SSE client closed: ${this.server.name}`))}async ensureInitialized(){this.initialized||(await this.ensureStream(),await this.request("initialize",{capabilities:{},clientInfo:{name:Ys,version:"1.0.0"},protocolVersion:this.server.protocolVersion||hs},this.server.startupTimeoutMs),await this.notification("notifications/initialized",{}).catch(()=>{}),this.initialized=!0)}async ensureStream(){this.endpointUrl||(this.openPromise||(this.openPromise=this.openStream().finally(()=>{this.openPromise=void 0})),await this.openPromise)}async openStream(){let e=new AbortController;this.streamAbort=e;let t=await fetch(this.server.url,{headers:this.headers(!1),method:"GET",signal:e.signal});if(!t.ok||!t.body)throw new Error(`MCP SSE stream failed (${this.server.name}): ${t.status}`);let r=()=>{},n=()=>{},o=new Promise((h,g)=>{r=h,n=g}),i=setTimeout(()=>{n(new Error(`MCP SSE endpoint timed out (${this.server.name}).`)),e.abort()},this.server.startupTimeoutMs??He),c=t.body.getReader(),d=new TextDecoder;(async()=>{try{for(;;){let{done:h,value:g}=await c.read();if(h)break;this.streamBuffer+=d.decode(g,{stream:!0}),this.streamBuffer=ul(this.streamBuffer,m=>{if(m.event==="endpoint"){this.endpointUrl=new URL(m.data.trim(),this.server.url).toString(),clearTimeout(i),r();return}this.routeSseMessage(m.data)})}this.rejectAll(new Error(`MCP SSE stream closed (${this.server.name}).`))}catch(h){clearTimeout(i),n(Ci(h)),this.rejectAll(Ci(h))}})(),await o}request(e,t,r=this.server.requestTimeoutMs){return this.ensureStream().then(()=>{let n=this.nextId++,o={id:n,jsonrpc:"2.0",method:e,params:t},i=new Promise((c,d)=>{let h=setTimeout(()=>{this.pending.delete(String(n)),d(new Error(`MCP SSE request timed out (${this.server.name}): ${e}`))},r??He);this.pending.set(String(n),{reject:d,resolve:g=>{if(R(g.error)){d(new Error(String(g.error.message??"MCP request failed.")));return}c(g.result)},timer:h})});return this.post(o).then(()=>i)})}async notification(e,t){await this.ensureStream(),await this.post({jsonrpc:"2.0",method:e,params:t})}async post(e){let t=await fetch(this.endpointUrl,{body:JSON.stringify(e),headers:this.headers(!0),method:"POST"});if(!t.ok)throw new Error(`MCP SSE post failed (${this.server.name}): ${t.status}`)}headers(e){let t=new Headers({...e?{"content-type":"application/json"}:{},...this.server.headers??{}}),r=this.server.apiKey||(this.server.apiKeyEnv?process.env[this.server.apiKeyEnv]:"");return r&&!t.has("authorization")&&t.set("authorization",`Bearer ${r}`),t}routeSseMessage(e){let t;try{t=JSON.parse(e)}catch{return}let r=t.id===void 0||t.id===null?"":String(t.id),n=r?this.pending.get(r):void 0;n&&(this.pending.delete(r),clearTimeout(n.timer),n.resolve(t))}rejectAll(e){for(let t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear()}},Dn=class{constructor(e){this.server=e}server;initialized=!1;sessionId="";async listTools(){await this.ensureInitialized();let e=await this.request("tools/list",{});return eo(e)}async callTool(e,t){return await this.ensureInitialized(),this.request("tools/call",{name:e,arguments:t})}async close(){this.initialized=!1,this.sessionId=""}async ensureInitialized(){this.initialized||(await this.request("initialize",{capabilities:{},clientInfo:{name:Ys,version:"1.0.0"},protocolVersion:this.server.protocolVersion||hs},this.server.startupTimeoutMs),await this.notification("notifications/initialized",{}).catch(()=>{}),this.initialized=!0)}async notification(e,t){await this.frame({jsonrpc:"2.0",method:e,params:t},this.server.requestTimeoutMs,!0)}async request(e,t,r=this.server.requestTimeoutMs){let n=await this.frame({id:(0,Xs.randomUUID)(),jsonrpc:"2.0",method:e,params:t},r,!1);if(!R(n))throw new Error(`Invalid MCP response from ${this.server.name}.`);if(R(n.error))throw new Error(`MCP request failed (${this.server.name}): ${String(n.error.message??"Unknown error")}`);return n.result}async frame(e,t=He,r){let n=new AbortController,o=setTimeout(()=>n.abort(),t);try{let i=new Headers({accept:"application/json, text/event-stream","content-type":"application/json",...this.server.headers??{}}),c=this.server.apiKey||(this.server.apiKeyEnv?process.env[this.server.apiKeyEnv]:"");c&&!i.has("authorization")&&i.set("authorization",`Bearer ${c}`),this.sessionId&&i.set("mcp-session-id",this.sessionId);let d=await fetch(this.server.url,{body:JSON.stringify(e),headers:i,method:"POST",signal:n.signal});if(this.sessionId=d.headers.get("mcp-session-id")||d.headers.get("x-mcp-session-id")||this.sessionId,r&&d.status===204)return;let h=await d.text();if(!d.ok)throw new Error(`MCP HTTP request failed (${this.server.name}): ${d.status} ${h.slice(0,300)}`);return h.trim()?ll(h):void 0}finally{clearTimeout(o)}}},Hn=class{constructor(e){this.server=e}server;child;initialized=!1;nextId=1;pending=new Map;stdoutBuffer=Buffer.alloc(0);async listTools(){await this.ensureInitialized();let e=await this.request("tools/list",{},this.server.requestTimeoutMs);return eo(e)}async callTool(e,t){return await this.ensureInitialized(),this.request("tools/call",{name:e,arguments:t},this.server.requestTimeoutMs)}async close(){this.initialized=!1;for(let e of this.pending.values())clearTimeout(e.timer),e.reject(new Error(`MCP stdio client closed: ${this.server.name}`));this.pending.clear(),this.child&&!this.child.killed&&this.child.kill(),this.child=void 0}async ensureInitialized(){this.initialized||(this.ensureChild(),await this.request("initialize",{capabilities:{},clientInfo:{name:Ys,version:"1.0.0"},protocolVersion:this.server.protocolVersion||hs},this.server.startupTimeoutMs),this.notify("notifications/initialized",{}),this.initialized=!0)}ensureChild(){if(this.child)return this.child;let e=(0,Ti.spawn)(this.server.command,this.server.args??[],{cwd:this.server.cwd||void 0,env:{...process.env,...this.server.env??{}},stdio:["pipe","pipe","pipe"]});return e.stdout.on("data",t=>this.readStdout(t)),e.stderr.on("data",t=>{let r=t.toString("utf8").trim();r&&console.error(`[ToolHub backend ${this.server.name}] ${r}`)}),e.on("error",t=>this.rejectAll(t)),e.on("exit",(t,r)=>{this.initialized=!1,this.child=void 0,this.rejectAll(new Error(`MCP server exited (${this.server.name}): ${r??t??"unknown"}`))}),this.child=e,e}request(e,t,r=He){let n=this.nextId++,o={id:n,jsonrpc:"2.0",method:e,params:t};return new Promise((i,c)=>{let d=setTimeout(()=>{this.pending.delete(String(n)),c(new Error(`MCP stdio request timed out (${this.server.name}): ${e}`))},r);this.pending.set(String(n),{reject:c,resolve:h=>{if(R(h.error)){c(new Error(String(h.error.message??"MCP request failed.")));return}i(h.result)},timer:d}),this.write(o)})}notify(e,t){this.write({jsonrpc:"2.0",method:e,params:t})}write(e){let t=this.ensureChild(),r=JSON.stringify(e);if(this.server.stdioMessageMode==="newline-json"){t.stdin.write(`${r}
28
+ `);if(s<0)return;let t=K.subarray(0,s).toString("utf8").match(/content-length:\s*(\d+)/i);if(!t){K=K.subarray(s+4),Qs(Pt(null,-32600,"Missing Content-Length header."),"content-length");continue}let r=Number(t[1]),n=s+4,o=n+r;if(K.length<o)return;let i=K.subarray(n,o).toString("utf8");K=K.subarray(o),await wi(i,"content-length")}}function Zc(){for(;K[0]===10||K[0]===13;)K=K.subarray(1)}function el(s){return/^content-length\s*:/i.test(s.subarray(0,Math.min(s.length,64)).toString("utf8"))}async function wi(s,e){Fi=e;let t;try{t=JSON.parse(s)}catch(n){Qs(Pt(null,-32700,`Invalid JSON-RPC request: ${Kr(n)}`),e);return}let r=await tl(t);r&&Qs(r,e)}async function tl(s){if(!R(s))return Pt(null,-32600,"JSON-RPC request must be an object.");let e=s,t=e.id??null;if(!(e.id===void 0&&e.method?.startsWith("notifications/"))){if(e.jsonrpc!=="2.0"||!e.method)return Pt(t,-32600,"Invalid JSON-RPC 2.0 request.");try{switch(e.method){case"initialize":return Ws(t,{capabilities:{tools:{}},protocolVersion:fs,serverInfo:{name:en,title:"CCR ToolHub",version:"1.0.0"}});case"ping":return Ws(t,{});case"tools/list":return Ws(t,{tools:fl()});case"tools/call":return Ws(t,await no.callTool(e.params));default:return Pt(t,-32601,`Unsupported MCP method: ${e.method}`)}}catch(r){return Pt(t,-32603,Kr(r))}}}var Wn=class{clients=new Map;registry=new Jn((e,t)=>this.clientForServer(e,t));sessions=new Map;async callTool(e){let t=R(e)&&typeof e.name=="string"?e.name.trim():"",r=R(e)&&R(e.arguments)?e.arguments:{};if(t===wt||t==="tool_hub_resolve"||t==="code_tool.resolve"||t==="code_tool_resolve")return this.resolveTools(r);if(t===Vs||t==="tool_hub_invoke"||t==="code_tool.invoke"||t==="code_tool_invoke")return this.invokeTool(r);throw new Error(`Unknown ToolHub meta tool: ${t}`)}close(){for(let e of this.clients.values())e.client.close();this.clients.clear(),this.sessions.clear()}async resolveTools(e){let t=typeof e.task=="string"?e.task.trim():"";if(!t)throw new Error(`${wt} requires task.`);let r=Zl(e.constraints?.maxTools??$i("TOOLHUB_MAX_TOOLS",so)),n=this.scopeKey(e),o=this.session(n),i=Yl(t);this.registry.updateServers(Un());let c=await this.registry.listTools();if(c.length===0&&(await this.registry.refreshServers(void 0,!0),c=await this.registry.listTools()),Bi(t)&&!jl(c)&&(await this.registry.refreshServers(["ccr-browser-automation"],!0),c=await this.registry.listTools()),c.length===0)throw new Error("No MCP tools are available to resolve.");let d=this.findRecentlyResolvedTask(n,i);if(d){let m=Dn(hs([...d.toolNames.map(_=>this.resolveCatalogEntry(_,c)).filter(_=>!!_),...qn(t,c)]),c);if(m.length>0)return this.markToolsLoaded(n,m),Js(this.buildRepeatedResolveOutput(m))}let h=o.inFlightResolves.get(i);if(h){let m=await h,_=Dn(hs([...m.selectedTools.map(f=>this.resolveCatalogEntry(f.toolName,c)??f).filter(f=>!!f),...qn(t,c)]),c);return _.length>0?(this.markToolsLoaded(n,_),Js(this.buildRepeatedResolveOutput(_))):Js(m)}let g=this.executeFreshResolve({catalog:c,context:e.context,maxTools:r,observations:o.recentObservations.slice(-5),scopeKey:n,task:t,taskHash:i,timeoutMs:e.constraints?.latencyBudgetMs,withoutSideEffects:e.constraints?.allowSideEffects===!1});o.inFlightResolves.set(i,g);try{return Js(await g)}finally{o.inFlightResolves.get(i)===g&&o.inFlightResolves.delete(i)}}async invokeTool(e){let t=typeof e.tool=="string"?e.tool.trim():"";if(!t)throw new Error(`${Vs} requires tool.`);let r=this.scopeKey(e);this.registry.updateServers(Un());let n=await this.registry.listTools(),o=this.resolveCatalogEntry(t,n);if(!o)return Ei("UNKNOWN_TOOL",`Unknown ToolHub tool: ${t}`);if(!this.session(r).loadedTools.has(o.toolName))return Ei("TOOL_NOT_RESOLVED",`Tool ${o.toolName} is not loaded in this session. Call ${wt} for the task first.`);let i=R(e.args)?e.args:{},d=await this.clientForServer(o.serverName).callTool(o.remoteToolName,i);return this.rememberObservation(r,o.toolName,d),d}async executeFreshResolve(e){let t,r="llm",n=!0;try{t=await this.resolveCatalogWithLlm(e)}catch(c){if(t=this.resolveCatalogLocally({...e,error:c}),t.selectedTools.length===0)throw c;r="local",n=!1}let o=Dn(hs([...t.selectedTools,...qn(e.task,e.catalog)]),e.catalog);if(e.withoutSideEffects&&(o=o.filter(c=>!c.invocation.sideEffect)),o.length===0)throw new Error("ToolHub could not resolve any matching MCP tools for this task.");this.markToolsLoaded(e.scopeKey,o),this.rememberResolvedTask(e.scopeKey,e.taskHash,o);let i=Kl(t.workflowSketch,o);return{...this.buildResolveOutput(t.summary,o,i),plannedSteps:t.plannedSteps,referencedTokens:t.referencedTokens,retriever:r,usedLlm:n,workflowSketch:i}}async resolveCatalogWithLlm(e){let r=await new Yn({openAiApiKey:He("TOOLHUB_OPENAI_API_KEY"),openAiBaseUrl:He("TOOLHUB_OPENAI_BASE_URL")||"https://api.openai.com/v1",openAiModel:He("TOOLHUB_OPENAI_MODEL")}).search({catalog:e.catalog.map(wl),code:JSON.stringify({context:e.context??{},observations:e.observations??[]}),query:e.task,timeoutMs:e.timeoutMs??$i("TOOLHUB_REQUEST_TIMEOUT_MS",We),topK:e.maxTools}),n=r.selectedToolNames.map(o=>this.resolveCatalogEntry(o,e.catalog)).filter(o=>!!o).slice(0,e.maxTools);return{plannedSteps:r.plannedSteps,referencedTokens:r.referencedTokens,selectedTools:n,summary:r.summary,workflowSketch:r.workflowSketch}}resolveCatalogLocally(e){let t=[e.task,e.context?JSON.stringify(e.context):"",...e.observations.map(i=>`${i.toolName} ${i.resultSummary}`)].join(" "),r=Ml(t),n=e.catalog.map((i,c)=>({index:c,score:Nl(t,i,r),tool:i})).filter(i=>i.score>0).sort((i,c)=>c.score-i.score||i.index-c.index),o=hs(n.map(i=>i.tool)).slice(0,e.maxTools);return{plannedSteps:o.length>0?["Resolve retrieval LLM did not finish within the latency budget.","Selected candidate tools with local catalog matching."]:void 0,referencedTokens:Xs(t),selectedTools:o,summary:`Resolve retrieval fell back to local catalog matching after LLM retrieval failed: ${Kr(e.error)}.`,workflowSketch:Fl(o)}}clientForServer(e,t){let r=t??Un().find(c=>c.name===e);if(!r)throw new Error(`ToolHub backend MCP server not found: ${e}`);let n=this.clients.get(e),o=Ui(r);if(n&&n.configHash===o)return n.client;n?.client.close();let i=r.transport==="stdio"?new Xn(r):r.transport==="sse"?new Gn(r):new Vn(r);return this.clients.set(e,{client:i,configHash:o}),i}resolveCatalogEntry(e,t){let r=Gs(t.map(n=>({alias:n.alias,canonicalName:n.canonicalName,name:n.toolName,remoteToolName:n.remoteToolName})),e);if(r)return t.find(n=>n.toolName===r)}buildResolveOutput(e,t,r=Ys(t)){return{executionPlanInstructions:bi,executionPlanJs:r,nextAction:this.buildResolveNextAction(t),reasoningSummary:e,runtimeContext:{availableContextKeys:["selectedTools","executionPlanJs","executionPlanInstructions"],summary:[...t.map(n=>`${n.toolName}: ${n.description||n.title}`),"Follow executionPlanJs for dependency ordering before invoking selected tools."]},selectedToolNames:t.map(n=>n.toolName),selectedTools:t,tsDefinitions:Tl(t),workflowSketch:r}}buildRepeatedResolveOutput(e){let t=this.buildResolveNextAction(e),r=Ys(e);return{alreadyResolved:!0,executionPlanInstructions:bi,executionPlanJs:r,nextAction:t,reasoningSummary:["This task has already been resolved in the current ToolHub session.",t.instruction].join(" "),runtimeContext:{availableContextKeys:["selectedTools","nextAction","executionPlanJs","executionPlanInstructions"],summary:["The selected tools are already loaded for tool_hub.invoke.","Do not repeat discovery for this task.",t.instruction,"Follow executionPlanJs for dependency ordering before invoking selected tools."]},selectedToolNames:e.map(n=>n.toolName),selectedTools:e,workflowSketch:r}}buildResolveNextAction(e){let t=e.map(d=>({requiredArguments:Br(d.inputSchema),sideEffect:d.invocation.sideEffect,toolName:d.toolName})).filter(d=>d.requiredArguments.length>0),r=e.filter(d=>d.invocation.sideEffect).map(d=>d.toolName),n=Hl(e),o=n?Br(n.inputSchema):[],i=o.length>0?{missingArguments:o,toolName:n?.toolName,type:"ask_user"}:{toolName:n?.toolName,type:"invoke_tool"},c=["Do not call tool_hub.resolve again for this task.","Follow executionPlanJs: await is serial dependency; only Promise.all groups may run in parallel."];return n&&o.length>0?c.push(`Ask the user for missing required arguments for ${n.toolName}: ${o.join(", ")}.`):n?c.push(`Call tool_hub.invoke for ${n.toolName}.`):c.push("Ask the user for the missing task details before invoking tools."),r.length>0&&c.push(`Before calling side-effecting tools, ask for explicit confirmation: ${r.join(", ")}.`),{confirmationRequiredFor:r,firstAction:i,instruction:c.join(" "),requiredArgumentsByTool:t}}scopeKey(e){return Ti(e.__toolHubScopeKey)||Ti(e.__codeToolScopeKey)||"default"}session(e){let t=this.sessions.get(e);if(t)return t;let r={inFlightResolves:new Map,loadedTools:new Set,recentObservations:[],recentlyResolvedTasks:[]};return this.sessions.set(e,r),r}markToolsLoaded(e,t){let r=this.session(e);for(let n of t)r.loadedTools.add(n.toolName)}rememberResolvedTask(e,t,r){let n=this.session(e);n.recentlyResolvedTasks=n.recentlyResolvedTasks.filter(o=>o.taskHash!==t),n.recentlyResolvedTasks.unshift({observationCount:n.recentObservations.length,resolvedAt:Date.now(),taskHash:t,toolNames:r.map(o=>o.toolName)}),n.recentlyResolvedTasks=n.recentlyResolvedTasks.slice(0,10)}findRecentlyResolvedTask(e,t){let r=this.session(e),n=Date.now();return r.recentlyResolvedTasks=r.recentlyResolvedTasks.filter(o=>n-o.resolvedAt<=Xc),r.recentlyResolvedTasks.find(o=>o.taskHash===t)}rememberObservation(e,t,r){let n=this.session(e);n.recentObservations.push({resultSummary:Ql(r),toolName:t}),n.recentObservations=n.recentObservations.slice(-20)}},Jn=class{constructor(e){this.clientFactory=e}clientFactory;discoveryPromise;entries=new Map;updateServers(e){let t=new Set;for(let r of e){t.add(r.name);let n=Ui(r),o=this.entries.get(r.name);if(o&&o.configHash===n){o.config=Si(r);continue}let i=Ri.readDiscovery(r.name,n);this.entries.set(r.name,{config:Si(r),configHash:n,lastCheckedAt:i?.cachedAt,lastSeenOnlineAt:i?.lastSeenOnlineAt,loadedFromCache:!!i,status:"unknown",tools:i?.tools.map(c=>({...c}))??[]})}for(let r of this.entries.keys())t.has(r)||this.entries.delete(r)}async listTools(){return await this.ensureDiscoveryFresh(),this.listCatalogEntriesSync()}async refreshServers(e,t=!0){let r=Gl(e,this.entries);if(r.length!==0&&!(this.discoveryPromise&&(await this.discoveryPromise,!t))){this.discoveryPromise=this.performDiscovery(r,t);try{await this.discoveryPromise}finally{this.discoveryPromise=void 0}}}async ensureDiscoveryFresh(e=Vc){let t=[...this.entries.values()].filter(r=>!r.lastCheckedAt||Date.now()-r.lastCheckedAt>e).map(r=>r.config.name);t.length!==0&&await this.refreshServers(t,!1)}listCatalogEntriesSync(){let e=bl([...this.entries.values()].map(r=>r.config.name)),t=[];for(let r of this.entries.values()){let n=e.get(r.config.name)??ce(r.config.name);for(let o of r.tools){let i=o.name.trim();if(!i)continue;let c=`mcp.${n}.${i}`;t.push({alias:ce(c),canonicalName:`${r.config.name}.${i}`,description:o.description??"",inputSchema:o.inputSchema,invocation:ql(o),outputSchema:o.outputSchema,remoteToolName:i,serverId:r.config.name,serverLabel:r.config.label,serverName:r.config.name,serverNamespace:n,status:r.status,tags:o.tags??[],title:o.title||o.name,toolName:c})}}return t.sort((r,n)=>r.toolName.localeCompare(n.toolName))}async performDiscovery(e,t){for(let r of e){let n=this.entries.get(r);n&&(!t&&n.lastCheckedAt&&Date.now()-n.lastCheckedAt<3e3||await this.probeServer(n.config))}}async probeServer(e){let t=Date.now();try{let r=await this.clientFactory(e.name,e).listTools(),n=this.entries.get(e.name);if(!n)return;n.status="online",n.tools=r.map(o=>({...o})),n.lastCheckedAt=t,n.lastSeenOnlineAt=t,n.loadedFromCache=!0,n.error=void 0,Ri.writeDiscovery(e.name,n.configHash,n.tools,t)}catch(r){let n=this.entries.get(e.name);if(!n)return;n.status="offline",n.lastCheckedAt=t,n.loadedFromCache=!1,n.error=Kr(r)}}};no=new Wn;var Gn=class{constructor(e){this.server=e}server;endpointUrl="";initialized=!1;nextId=1;openPromise;pending=new Map;streamAbort;streamBuffer="";async listTools(){await this.ensureInitialized();let e=await this.request("tools/list",{});return oo(e)}async callTool(e,t){return await this.ensureInitialized(),this.request("tools/call",{name:e,arguments:t})}async close(){this.initialized=!1,this.endpointUrl="",this.streamAbort?.abort(),this.streamAbort=void 0,this.rejectAll(new Error(`MCP SSE client closed: ${this.server.name}`))}async ensureInitialized(){this.initialized||(await this.ensureStream(),await this.request("initialize",{capabilities:{},clientInfo:{name:en,version:"1.0.0"},protocolVersion:this.server.protocolVersion||fs},this.server.startupTimeoutMs),await this.notification("notifications/initialized",{}).catch(()=>{}),this.initialized=!0)}async ensureStream(){this.endpointUrl||(this.openPromise||(this.openPromise=this.openStream().finally(()=>{this.openPromise=void 0})),await this.openPromise)}async openStream(){let e=new AbortController;this.streamAbort=e;let t=await fetch(this.server.url,{headers:this.headers(!1),method:"GET",signal:e.signal});if(!t.ok||!t.body)throw new Error(`MCP SSE stream failed (${this.server.name}): ${t.status}`);let r=()=>{},n=()=>{},o=new Promise((h,g)=>{r=h,n=g}),i=setTimeout(()=>{n(new Error(`MCP SSE endpoint timed out (${this.server.name}).`)),e.abort()},this.server.startupTimeoutMs??We),c=t.body.getReader(),d=new TextDecoder;(async()=>{try{for(;;){let{done:h,value:g}=await c.read();if(h)break;this.streamBuffer+=d.decode(g,{stream:!0}),this.streamBuffer=yl(this.streamBuffer,m=>{if(m.event==="endpoint"){this.endpointUrl=new URL(m.data.trim(),this.server.url).toString(),clearTimeout(i),r();return}this.routeSseMessage(m.data)})}this.rejectAll(new Error(`MCP SSE stream closed (${this.server.name}).`))}catch(h){clearTimeout(i),n(Mi(h)),this.rejectAll(Mi(h))}})(),await o}request(e,t,r=this.server.requestTimeoutMs){return this.ensureStream().then(()=>{let n=this.nextId++,o={id:n,jsonrpc:"2.0",method:e,params:t},i=new Promise((c,d)=>{let h=setTimeout(()=>{this.pending.delete(String(n)),d(new Error(`MCP SSE request timed out (${this.server.name}): ${e}`))},r??We);this.pending.set(String(n),{reject:d,resolve:g=>{if(R(g.error)){d(new Error(String(g.error.message??"MCP request failed.")));return}c(g.result)},timer:h})});return this.post(o).then(()=>i)})}async notification(e,t){await this.ensureStream(),await this.post({jsonrpc:"2.0",method:e,params:t})}async post(e){let t=await fetch(this.endpointUrl,{body:JSON.stringify(e),headers:this.headers(!0),method:"POST"});if(!t.ok)throw new Error(`MCP SSE post failed (${this.server.name}): ${t.status}`)}headers(e){let t=new Headers({...e?{"content-type":"application/json"}:{},...this.server.headers??{}}),r=this.server.apiKey||(this.server.apiKeyEnv?process.env[this.server.apiKeyEnv]:"");return r&&!t.has("authorization")&&t.set("authorization",`Bearer ${r}`),t}routeSseMessage(e){let t;try{t=JSON.parse(e)}catch{return}let r=t.id===void 0||t.id===null?"":String(t.id),n=r?this.pending.get(r):void 0;n&&(this.pending.delete(r),clearTimeout(n.timer),n.resolve(t))}rejectAll(e){for(let t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear()}},Vn=class{constructor(e){this.server=e}server;initialized=!1;sessionId="";async listTools(){await this.ensureInitialized();let e=await this.request("tools/list",{});return oo(e)}async callTool(e,t){return await this.ensureInitialized(),this.request("tools/call",{name:e,arguments:t})}async close(){this.initialized=!1,this.sessionId=""}async ensureInitialized(){this.initialized||(await this.request("initialize",{capabilities:{},clientInfo:{name:en,version:"1.0.0"},protocolVersion:this.server.protocolVersion||fs},this.server.startupTimeoutMs),await this.notification("notifications/initialized",{}).catch(()=>{}),this.initialized=!0)}async notification(e,t){await this.frame({jsonrpc:"2.0",method:e,params:t},this.server.requestTimeoutMs,!0)}async request(e,t,r=this.server.requestTimeoutMs){let n=await this.frame({id:(0,Zs.randomUUID)(),jsonrpc:"2.0",method:e,params:t},r,!1);if(!R(n))throw new Error(`Invalid MCP response from ${this.server.name}.`);if(R(n.error))throw new Error(`MCP request failed (${this.server.name}): ${String(n.error.message??"Unknown error")}`);return n.result}async frame(e,t=We,r){let n=new AbortController,o=setTimeout(()=>n.abort(),t);try{let i=new Headers({accept:"application/json, text/event-stream","content-type":"application/json",...this.server.headers??{}}),c=this.server.apiKey||(this.server.apiKeyEnv?process.env[this.server.apiKeyEnv]:"");c&&!i.has("authorization")&&i.set("authorization",`Bearer ${c}`),this.sessionId&&i.set("mcp-session-id",this.sessionId);let d=await fetch(this.server.url,{body:JSON.stringify(e),headers:i,method:"POST",signal:n.signal});if(this.sessionId=d.headers.get("mcp-session-id")||d.headers.get("x-mcp-session-id")||this.sessionId,r&&d.status===204)return;let h=await d.text();if(!d.ok)throw new Error(`MCP HTTP request failed (${this.server.name}): ${d.status} ${h.slice(0,300)}`);return h.trim()?_l(h):void 0}finally{clearTimeout(o)}}},Xn=class{constructor(e){this.server=e}server;child;initialized=!1;nextId=1;pending=new Map;stdoutBuffer=Buffer.alloc(0);async listTools(){await this.ensureInitialized();let e=await this.request("tools/list",{},this.server.requestTimeoutMs);return oo(e)}async callTool(e,t){return await this.ensureInitialized(),this.request("tools/call",{name:e,arguments:t},this.server.requestTimeoutMs)}async close(){this.initialized=!1;for(let e of this.pending.values())clearTimeout(e.timer),e.reject(new Error(`MCP stdio client closed: ${this.server.name}`));this.pending.clear(),this.child&&!this.child.killed&&this.child.kill(),this.child=void 0}async ensureInitialized(){this.initialized||(this.ensureChild(),await this.request("initialize",{capabilities:{},clientInfo:{name:en,version:"1.0.0"},protocolVersion:this.server.protocolVersion||fs},this.server.startupTimeoutMs),this.notify("notifications/initialized",{}),this.initialized=!0)}ensureChild(){if(this.child)return this.child;let e=(0,ji.spawn)(this.server.command,this.server.args??[],{cwd:this.server.cwd||void 0,env:{...process.env,...this.server.env??{}},stdio:["pipe","pipe","pipe"]});return e.stdout.on("data",t=>this.readStdout(t)),e.stderr.on("data",t=>{let r=t.toString("utf8").trim();r&&console.error(`[ToolHub backend ${this.server.name}] ${r}`)}),e.on("error",t=>this.rejectAll(t)),e.on("exit",(t,r)=>{this.initialized=!1,this.child=void 0,this.rejectAll(new Error(`MCP server exited (${this.server.name}): ${r??t??"unknown"}`))}),this.child=e,e}request(e,t,r=We){let n=this.nextId++,o={id:n,jsonrpc:"2.0",method:e,params:t};return new Promise((i,c)=>{let d=setTimeout(()=>{this.pending.delete(String(n)),c(new Error(`MCP stdio request timed out (${this.server.name}): ${e}`))},r);this.pending.set(String(n),{reject:c,resolve:h=>{if(R(h.error)){c(new Error(String(h.error.message??"MCP request failed.")));return}i(h.result)},timer:d}),this.write(o)})}notify(e,t){this.write({jsonrpc:"2.0",method:e,params:t})}write(e){let t=this.ensureChild(),r=JSON.stringify(e);if(this.server.stdioMessageMode==="newline-json"){t.stdin.write(`${r}
29
29
  `);return}t.stdin.write(`Content-Length: ${Buffer.byteLength(r,"utf8")}\r
30
30
  \r
31
31
  ${r}`)}readStdout(e){this.stdoutBuffer=Buffer.concat([this.stdoutBuffer,e]),this.server.stdioMessageMode==="newline-json"?this.drainNewlineJsonStdout():this.drainContentLengthStdout()}drainContentLengthStdout(){for(;;){let e=this.stdoutBuffer.indexOf(`\r
32
32
  \r
33
33
  `);if(e<0)return;let r=this.stdoutBuffer.subarray(0,e).toString("utf8").match(/content-length:\s*(\d+)/i);if(!r){this.stdoutBuffer=this.stdoutBuffer.subarray(e+4);continue}let n=Number(r[1]),o=e+4,i=o+n;if(this.stdoutBuffer.length<i)return;let c=this.stdoutBuffer.subarray(o,i).toString("utf8");this.stdoutBuffer=this.stdoutBuffer.subarray(i),this.routeMessage(c)}}drainNewlineJsonStdout(){for(;;){let e=this.stdoutBuffer.indexOf(`
34
- `);if(e<0)return;let t=this.stdoutBuffer.subarray(0,e).toString("utf8").trim();this.stdoutBuffer=this.stdoutBuffer.subarray(e+1),t&&this.routeMessage(t)}}routeMessage(e){let t;try{t=JSON.parse(e)}catch{return}let r=t.id===void 0||t.id===null?"":String(t.id),n=r?this.pending.get(r):void 0;n&&(this.pending.delete(r),clearTimeout(n.timer),n.resolve(t))}rejectAll(e){for(let t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear()}},ls="tree_sitter_collect_tool_references",Gc=3,Vc=6,Xc=8e3,Yc=6e4,Qc=3500,Zc=8e3,gi=1500,Wn=class{constructor(e){this.config=e}config;analyzer=new Gn;async search(e){let t=e.query.trim();if(!t)throw new Error("ToolHub resolve query must be non-empty.");let r=this.config.openAiApiKey||De("TOOLHUB_OPENAI_API_KEY"),n=this.config.openAiBaseUrl||De("TOOLHUB_OPENAI_BASE_URL")||"https://api.openai.com/v1",o=this.config.openAiModel||De("TOOLHUB_OPENAI_MODEL");if(!r||!o)throw new Error("ToolHub resolver requires TOOLHUB_OPENAI_API_KEY and TOOLHUB_OPENAI_MODEL.");let i=yl(e.topK),c=Al(e.maxTurns),d=bl(e.timeoutMs),h=Date.now()+d;await el(n,r,d);let g=new I({apiKey:r,baseURL:n}),m=[{role:"user",content:JSON.stringify({context:e.code??"",query:t},null,2)}],_=!1,f=0,y="",w="",O=[],E=[],b=[],S=[];for(let H=0;H<c;H+=1){let L=h-Date.now();if(L<=(_?Zc:Qc)+gi)break;let C=Math.min(L-gi,Yc),T=await this.callOpenAiWithTools(g,o,fl(e.catalog,i),m,C),$=T.tool_calls??[];if($.length>0){m.push(T);let se=[];for(let Kr of $){if(Kr.function.name!==ls){m.push({role:"tool",tool_call_id:Kr.id,content:JSON.stringify({error:`Unknown tool: ${Kr.function.name}`})});continue}_=!0,f+=1;let no=_l(Kr.function.arguments),ji=typeof no.code=="string"?no.code:"",oo=this.analyzer.collectReferences(ji),Qs=Q(oo.map(Br=>Br.rawName)),io=Q(Qs.map(Br=>Ws(e.catalog,Br)).filter(Br=>typeof Br=="string"));b=Q([...b,...Qs]),se.push(...io),m.push({role:"tool",tool_call_id:Kr.id,content:JSON.stringify({references:oo,resolvedToolNames:io,tokens:Qs})})}S=Q(se);continue}let M=typeof T.content=="string"?T.content.trim():"",ce=dl(M);if(!ce){m.push(T),m.push({role:"user",content:_?'Return only a valid JSON object with keys "summary", "steps", "workflowSketch", and "toolNames".':`You must call ${ls} on a TypeScript workflow sketch before your final answer.`});continue}y=typeof ce.summary=="string"?ce.summary.trim():"",w=typeof ce.workflowSketch=="string"?ce.workflowSketch:"",O=yi(ce.steps);let Fr=this.analyzer.collectReferences(w),ms=Q(Fr.map(se=>se.rawName)),fs=Q(ms.map(se=>Ws(e.catalog,se)).filter(se=>typeof se=="string"));b=Q([...b,...ms]),E=Q([...fs,...yi(ce.toolNames)].map(se=>Ws(e.catalog,se)).filter(se=>typeof se=="string"));let ro=Q([...S,...E]).slice(0,i),so=_?pl({selectedToolNames:ro,summary:y,workflowSketch:w}):ro.length===0?"Your current answer resolved to zero valid catalog tools. Call the tree-sitter tool on a revised TypeScript workflow sketch before answering.":void 0;if(so&&H+1<c){m.push(T),m.push({role:"user",content:so});continue}break}let k=Q([...S,...E]).slice(0,i);if(k.length===0)throw new Error(_||f>0?"Resolve retrieval did not converge on any valid catalog tools after AST refinement.":"Resolve retrieval did not converge on any valid catalog tools.");if((!_||f===0)&&(b=Q([...b,...k])),_&&f===0)throw new Error("Resolve retrieval LLM did not complete an AST planning round.");return y?y.toLowerCase().includes("no strong tool bundle match was found")&&(y="Resolved a candidate tool bundle after iterative AST refinement."):y=_?"Resolved a planned end-to-end tool bundle with AST-assisted retrieval.":"Resolved a planned end-to-end tool bundle from the resolver model response.",{plannedSteps:O.length>0?O:void 0,referencedTokens:b,selectedToolNames:k,summary:y,workflowSketch:w||void 0}}async callOpenAiWithTools(e,t,r,n,o){let c=(await e.chat.completions.create({model:t,temperature:0,messages:[{role:"system",content:r},...n],stream:!1,tools:[{type:"function",function:{name:ls,description:"Analyze a short TypeScript workflow sketch and extract exact ToolHub tool references.",parameters:{type:"object",properties:{code:{type:"string",description:"TypeScript workflow sketch that references ToolHub tools."}},required:["code"],additionalProperties:!1}}}],tool_choice:"auto"},{timeout:o})).choices[0]?.message;if(!c)throw new Error("OpenAI resolve retrieval returned no assistant message.");let d=typeof c.content=="string"?c.content:"",h=(c.tool_calls??[]).map((g,m)=>{let _=g,f=R(_.function)?_.function:{};return{id:g.id||`tool_call_${m}`,type:"function",function:{arguments:typeof f.arguments=="string"?f.arguments:"",name:typeof f.name=="string"?f.name:""}}}).filter(g=>g.function.name.length>0);if(!d&&h.length===0)throw new Error("OpenAI resolve retrieval returned no assistant content or tool calls.");return{role:"assistant",content:d,tool_calls:h}}};async function el(s,e,t){let r=tl(s);if(!r)return;let n=Date.now()+Math.min(Math.max(t,1e3),3e4),o;for(;Date.now()<n;){let i=new AbortController,c=setTimeout(()=>i.abort(),1e3);try{await fetch(r,{headers:{authorization:`Bearer ${e}`},method:"GET",signal:i.signal});return}catch(d){if(o=d,!sl(d))return;await ol(300)}finally{clearTimeout(c)}}throw new Error(`ToolHub resolver could not connect to CCR Gateway at ${r}: ${Lr(o)}.`)}function tl(s){let e;try{e=new URL(s)}catch{return}return rl(e.hostname)?`${s.replace(/\/+$/g,"")}/models`:void 0}function rl(s){let e=s.trim().toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e==="::1"||e==="0:0:0:0:0:0:0:1"||e.startsWith("127.")}function sl(s){if(s instanceof DOMException&&s.name==="AbortError")return!0;let e=nl(s);return e==="ECONNREFUSED"||e==="ECONNRESET"||e==="EHOSTUNREACH"||e==="ENETUNREACH"||e==="ETIMEDOUT"}function nl(s){if(!R(s))return"";let e=typeof s.code=="string"?s.code:"";if(e)return e;let t=R(s.cause)?s.cause:void 0;return typeof t?.code=="string"?t.code:""}function ol(s){return new Promise(e=>setTimeout(e,s))}function il(){return[{name:jr,description:["Search ToolHub with the configured model and resolve installed MCP tools needed for a task.","MUST be called before answering any request about external services, installed MCP capabilities, business APIs, orders, coupons, stores, accounts, available tools, or capabilities that are not already obvious from the eager tools.",`Call this even if the user did not mention ToolHub or ${jr}.`,`Use ${Js} after this tool returns selected tools.`,"Use the user's request as task and include concise context so the resolver can select the right tools."].join(" "),inputSchema:{type:"object",properties:{task:{type:"string"},context:{type:"object",additionalProperties:!0},constraints:{type:"object",properties:{maxTools:{type:"number"}},additionalProperties:!1}},required:["task"],additionalProperties:!1}},{name:Js,description:`Invoke one MCP tool selected by ${jr}.`,inputSchema:{type:"object",properties:{tool:{type:"string"},args:{type:"object",additionalProperties:!0}},required:["tool"],additionalProperties:!1}}]}function Kn(){let s=De("TOOLHUB_MCP_SERVERS_JSON");if(!s)return[];try{let e=JSON.parse(s);return Array.isArray(e)?e.map(al).filter(t=>!!t):[]}catch{return[]}}function al(s){if(!R(s))return;let t=(typeof s.transport=="string"?s.transport:typeof s.type=="string"?s.type:"").toLowerCase().replace(/_/g,"-"),r=t==="streamable-http"||t==="streamablehttp"||t==="http"?"streamable-http":t==="sse"?"sse":"stdio",n=typeof s.name=="string"&&s.name.trim()?s.name.trim():"";if(!n)return;let o={label:typeof s.label=="string"&&s.label.trim()?s.label.trim():void 0,name:n,protocolVersion:typeof s.protocolVersion=="string"?s.protocolVersion:hs,requestTimeoutMs:Ri(s.requestTimeoutMs,He),startupTimeoutMs:Ri(s.startupTimeoutMs,He),transport:r};if(r!=="stdio"){let c=typeof s.url=="string"&&s.url.trim()?s.url.trim():"";return c?{...o,apiKey:typeof s.apiKey=="string"?s.apiKey:void 0,apiKeyEnv:typeof s.apiKeyEnv=="string"?s.apiKeyEnv:void 0,headers:ki(s.headers)?s.headers:{},transport:r,url:c}:void 0}let i=typeof s.command=="string"&&s.command.trim()?s.command.trim():"";if(i)return{...o,args:Array.isArray(s.args)?s.args.filter(c=>typeof c=="string"):[],command:i,cwd:typeof s.cwd=="string"&&s.cwd.trim()?s.cwd.trim():void 0,env:ki(s.env)?s.env:{},stdioMessageMode:s.stdioMessageMode==="newline-json"?"newline-json":"content-length",transport:r}}function eo(s){let e=R(s)&&Array.isArray(s.tools)?s.tools:[],t=[];for(let r of e)!R(r)||typeof r.name!="string"||!r.name.trim()||t.push({description:typeof r.description=="string"?r.description:"",inputSchema:cl(r.inputSchema??r.input_schema),name:r.name.trim(),outputSchema:Jn(r.outputSchema??r.output_schema),tags:Array.isArray(r.tags)?r.tags.filter(n=>typeof n=="string"):void 0,title:typeof r.title=="string"&&r.title.trim()?r.title.trim():void 0});return t}function cl(s){return R(s)?s:{type:"object",properties:{}}}function Jn(s){return R(s)?s:void 0}function ll(s){if(/^event:/m.test(s)||/^data:/m.test(s)){let e=s.split(/\n\n+/);for(let t of e){let r=t.split(/\n/).filter(n=>n.startsWith("data:")).map(n=>n.slice(5).trim()).join(`
35
- `);if(r)try{return JSON.parse(r)}catch{continue}}}return JSON.parse(s)}function ul(s,e){let t=0;for(;;){let r=/\r?\n\r?\n/.exec(s.slice(t));if(!r||r.index<0)return s.slice(t);let n=t+r.index,o=s.slice(t,n);t=n+r[0].length;let i="message",c=[];for(let d of o.split(/\r?\n/))d.startsWith("event:")?i=d.slice(6).trim()||"message":d.startsWith("data:")&&c.push(d.slice(5).trimStart());(c.length>0||i!=="message")&&e({data:c.join(`
36
- `),event:i})}}function dl(s){try{let e=JSON.parse(s);return R(e)?e:void 0}catch{let e=s.indexOf("{"),t=s.lastIndexOf("}");if(e<0||t<=e)return;try{let r=JSON.parse(s.slice(e,t+1));return R(r)?r:void 0}catch{return}}}function hl(s){let e=new Map,t=new Map;for(let r of s){let n=ge(r),o=(e.get(n)??0)+1;e.set(n,o),t.set(r,o===1?n:`${n}_${o}`)}return t}function ge(s){let e=s.replace(/[^a-zA-Z0-9_]/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"");return e?/^\d/.test(e)?`_${e}`:e:"tool"}function ml(s){return{alias:s.alias,canonicalName:s.canonicalName,description:s.description,invocationMode:s.invocation.mode,name:s.toolName,remoteToolName:s.remoteToolName,required:ds(s.inputSchema),serverId:s.serverId,serverLabel:s.serverLabel,sideEffect:s.invocation.sideEffect,title:s.title}}function fl(s,e){return["You are the ToolHub resolve planner and retrieval agent.","Your job is to return the complete anticipated tool bundle for the user task, not just the first tool.","You must think ahead about the next likely steps needed to finish the task end-to-end.",`You MUST call ${ls} before your final answer.`,"You may need multiple planning and search rounds.","If your first workflow sketch yields zero, partial, or weak tool matches, revise the sketch and call the tree-sitter tool again before answering.","Workflow you must follow:","1. Plan the likely execution steps.","2. Draft a short TypeScript workflow sketch that uses the exact catalog tool names or aliases you expect to need.",'2a. Prefer sketches that call tools through string literals such as callTool("<exact catalog tool name>", {...}) or tools.call("<exact catalog tool name>", {...}).',"3. Call the tree-sitter tool on that sketch.","4. Inspect the tree-sitter result and check whether the bundle is complete end-to-end.","5. If it is incomplete, revise the sketch and call the tree-sitter tool again.","6. Return the final JSON only after the bundle is complete.",`Return at most ${e} tool names.`,"Final answer MUST be a JSON object with this shape:",'{ "summary": string, "steps": string[], "workflowSketch": string, "toolNames": string[] }',"Rules:","- toolNames must be exact catalog names or aliases.","- In workflowSketch, prefer string-literal tool calls over reconstructed member chains whenever possible.","- Include prerequisite and downstream tools you will likely need after the first action.","- Never invent tool names.","- Generic browser automation tools are a strong match for web tasks such as ordering, buying, booking, delivery, or checkout when no domain-specific MCP tool exists.","- If using member-call syntax, prefer tools.<catalog alias>(...) or mcp.<server namespace>.<remote tool name>(...).","- For lookup tasks, do not stop at opening or navigating. Include the tools needed to read or extract the answer.","- If the catalog has no strong match, return an empty toolNames array.","","Tool catalog:",JSON.stringify(s,null,2)].join(`
37
- `)}function pl(s){let e=[];if(s.workflowSketch.trim()||e.push("workflowSketch is empty."),s.selectedToolNames.length===0&&e.push("Your current answer resolved to zero valid catalog tools."),s.summary.trim().toLowerCase().includes("no strong tool bundle match was found")&&e.push("Your summary says the bundle is weak; revise the workflow sketch and search again."),e.length!==0)return["Your last candidate tool bundle is incomplete.",...e.map((t,r)=>`${r+1}. ${t}`),`Revise the workflow sketch, call ${ls} again, and then return updated JSON only.`].join(`
38
- `)}var Gn=class{collectReferences(e){if(!e.trim())return[];let t=[];return this.collectStringCallReferences(e,t),this.collectMemberReferences(e,t),gl(t)}collectStringCallReferences(e,t){let r=[{regex:/\bcallTool\s*\(\s*(["'`])([^"'`]+)\1/g,source:"callTool"},{regex:/\btools\s*\.\s*call\s*\(\s*(["'`])([^"'`]+)\1/g,source:"tools.call"},{regex:/\b[\w$]+\s*\.\s*callTool\s*\(\s*(["'`])([^"'`]+)\1/g,source:"context.callTool"},{regex:/\btools\s*\[\s*(["'`])([^"'`]+)\1\s*\]\s*\(/g,source:"tools.subscript"}];for(let n of r)for(let o of e.matchAll(n.regex)){let i=o[2]?.trim();i&&t.push(_i(e,o.index??0,i,n.source))}}collectMemberReferences(e,t){let r=[{regex:/\btools\s*\.\s*([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*)\s*\(/g,source:"tools.member"},{regex:/\bmcp\s*\.\s*([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*){1,})\s*\(/g,source:"mcp.member"}];for(let n of r)for(let o of e.matchAll(n.regex)){let i=o[1]?.replace(/\s+/g,"");if(!i||i==="call")continue;let c=n.source==="mcp.member"?`mcp.${i}`:i;t.push(_i(e,o.index??0,c,n.source))}}};function _i(s,e,t,r){let o=s.slice(0,e).split(/\r?\n/);return{column:o[o.length-1].length+1,line:o.length,rawName:t,source:r}}function gl(s){let e=new Set,t=[];for(let r of s){let n=`${r.rawName}\0${r.source}\0${r.line}\0${r.column}`;e.has(n)||(e.add(n),t.push(r))}return t}function _l(s){try{let e=JSON.parse(s);return R(e)?e:{}}catch{return{}}}function yi(s){return Array.isArray(s)?s.filter(e=>typeof e=="string"):[]}function yl(s){return Math.min(Math.max(to(s,Qn),1),20)}function Al(s){return Math.min(Math.max(to(s,Gc),1),Vc)}function bl(s){return Math.max(to(s,He),Xc)}function to(s,e){if(typeof s!="number"||!Number.isFinite(s))return e;let t=Math.floor(s);return t>0?t:e}function Ws(s,e){let t=e.trim();if(!t)return;let r=Q([t,ge(t),t.startsWith("mcp.")?t:`mcp.${t}`,t.startsWith("mcp_")?t:`mcp_${ge(t)}`]);for(let o of s){let i=Q([o.name,o.alias,o.canonicalName??"",o.canonicalName?ge(o.canonicalName):""].filter(Boolean));for(let c of r)if(i.includes(c))return o.name}let n=s.filter(o=>wl(o,t));return n.length===1?n[0].name:void 0}function wl(s,e){let t=ge(e),r=s.name.split(".").slice(1).join("."),n=s.remoteToolName||s.name.split(".").at(-1)||"",o=Q([s.canonicalName??"",s.canonicalName?ge(s.canonicalName):"",r,ge(r),n,ge(n)].filter(Boolean));return o.includes(e)||o.includes(t)}function Pl(s){return s.map(e=>{let t=vl(e.toolName),r=`${t}Args`;return["/**",` * ${e.description||e.title}`,` * Exact tool name: "${e.toolName}".`,` * Callable references: "${e.toolName}", "${e.alias}".`," */",`type ${r} = ${Il(e.inputSchema)};`,`type ${t}Call = { tool: "${e.toolName}"; args: ${r}; };`].join(`
34
+ `);if(e<0)return;let t=this.stdoutBuffer.subarray(0,e).toString("utf8").trim();this.stdoutBuffer=this.stdoutBuffer.subarray(e+1),t&&this.routeMessage(t)}}routeMessage(e){let t;try{t=JSON.parse(e)}catch{return}let r=t.id===void 0||t.id===null?"":String(t.id),n=r?this.pending.get(r):void 0;n&&(this.pending.delete(r),clearTimeout(n.timer),n.resolve(t))}rejectAll(e){for(let t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear()}},ms="tree_sitter_collect_tool_references",rl=3,sl=6,nl=8e3,ol=6e4,il=3500,al=8e3,Pi=1500,Yn=class{constructor(e){this.config=e}config;analyzer=new Zn;async search(e){let t=e.query.trim();if(!t)throw new Error("ToolHub resolve query must be non-empty.");let r=this.config.openAiApiKey||He("TOOLHUB_OPENAI_API_KEY"),n=this.config.openAiBaseUrl||He("TOOLHUB_OPENAI_BASE_URL")||"https://api.openai.com/v1",o=this.config.openAiModel||He("TOOLHUB_OPENAI_MODEL");if(!r||!o)throw new Error("ToolHub resolver requires TOOLHUB_OPENAI_API_KEY and TOOLHUB_OPENAI_MODEL.");let i=Sl(e.topK),c=Rl(e.maxTurns),d=kl(e.timeoutMs),h=Date.now()+d;await cl(n,r,d);let g=new I({apiKey:r,baseURL:n}),m=[{role:"user",content:JSON.stringify({context:e.code??"",query:t},null,2)}],_=!1,f=0,y="",w="",O=[],E=[],b=[],S=[];for(let H=0;H<c;H+=1){let L=h-Date.now();if(L<=(_?al:il)+Pi)break;let C=Math.min(L-Pi,ol),T=await this.callOpenAiWithTools(g,o,Pl(e.catalog,i),m,C),$=T.tool_calls??[];if($.length>0){m.push(T);let se=[];for(let Ur of $){if(Ur.function.name!==ms){m.push({role:"tool",tool_call_id:Ur.id,content:JSON.stringify({error:`Unknown tool: ${Ur.function.name}`})});continue}_=!0,f+=1;let lo=xl(Ur.function.arguments),qi=typeof lo.code=="string"?lo.code:"",uo=this.analyzer.collectReferences(qi),tn=Q(uo.map(qr=>qr.rawName)),ho=Q(tn.map(qr=>Gs(e.catalog,qr)).filter(qr=>typeof qr=="string"));b=Q([...b,...tn]),se.push(...ho),m.push({role:"tool",tool_call_id:Ur.id,content:JSON.stringify({references:uo,resolvedToolNames:ho,tokens:tn})})}S=Q(se);continue}let M=typeof T.content=="string"?T.content.trim():"",le=Al(M);if(!le){m.push(T),m.push({role:"user",content:_?'Return only a valid JSON object with keys "summary", "steps", "workflowSketch", and "toolNames".':`You must call ${ms} on a TypeScript workflow sketch before your final answer.`});continue}y=typeof le.summary=="string"?le.summary.trim():"",w=typeof le.workflowSketch=="string"?le.workflowSketch:"",O=vi(le.steps);let zr=this.analyzer.collectReferences(w),ps=Q(zr.map(se=>se.rawName)),gs=Q(ps.map(se=>Gs(e.catalog,se)).filter(se=>typeof se=="string"));b=Q([...b,...ps]),E=Q([...gs,...vi(le.toolNames)].map(se=>Gs(e.catalog,se)).filter(se=>typeof se=="string"));let ao=Q([...S,...E]).slice(0,i),co=_?Il({selectedToolNames:ao,summary:y,workflowSketch:w}):ao.length===0?"Your current answer resolved to zero valid catalog tools. Call the tree-sitter tool on a revised TypeScript workflow sketch before answering.":void 0;if(co&&H+1<c){m.push(T),m.push({role:"user",content:co});continue}break}let k=Q([...S,...E]).slice(0,i);if(k.length===0)throw new Error(_||f>0?"Resolve retrieval did not converge on any valid catalog tools after AST refinement.":"Resolve retrieval did not converge on any valid catalog tools.");if((!_||f===0)&&(b=Q([...b,...k])),_&&f===0)throw new Error("Resolve retrieval LLM did not complete an AST planning round.");return y?y.toLowerCase().includes("no strong tool bundle match was found")&&(y="Resolved a candidate tool bundle after iterative AST refinement."):y=_?"Resolved a planned end-to-end tool bundle with AST-assisted retrieval.":"Resolved a planned end-to-end tool bundle from the resolver model response.",{plannedSteps:O.length>0?O:void 0,referencedTokens:b,selectedToolNames:k,summary:y,workflowSketch:w||void 0}}async callOpenAiWithTools(e,t,r,n,o){let c=(await e.chat.completions.create({model:t,temperature:0,messages:[{role:"system",content:r},...n],stream:!1,tools:[{type:"function",function:{name:ms,description:"Analyze a short TypeScript workflow sketch and extract exact ToolHub tool references.",parameters:{type:"object",properties:{code:{type:"string",description:"TypeScript workflow sketch that references ToolHub tools."}},required:["code"],additionalProperties:!1}}}],tool_choice:"auto"},{timeout:o})).choices[0]?.message;if(!c)throw new Error("OpenAI resolve retrieval returned no assistant message.");let d=typeof c.content=="string"?c.content:"",h=(c.tool_calls??[]).map((g,m)=>{let _=g,f=R(_.function)?_.function:{};return{id:g.id||`tool_call_${m}`,type:"function",function:{arguments:typeof f.arguments=="string"?f.arguments:"",name:typeof f.name=="string"?f.name:""}}}).filter(g=>g.function.name.length>0);if(!d&&h.length===0)throw new Error("OpenAI resolve retrieval returned no assistant content or tool calls.");return{role:"assistant",content:d,tool_calls:h}}};async function cl(s,e,t){let r=ll(s);if(!r)return;let n=Date.now()+Math.min(Math.max(t,1e3),3e4),o;for(;Date.now()<n;){let i=new AbortController,c=setTimeout(()=>i.abort(),1e3);try{await fetch(r,{headers:{authorization:`Bearer ${e}`},method:"GET",signal:i.signal});return}catch(d){if(o=d,!dl(d))return;await ml(300)}finally{clearTimeout(c)}}throw new Error(`ToolHub resolver could not connect to CCR Gateway at ${r}: ${Kr(o)}.`)}function ll(s){let e;try{e=new URL(s)}catch{return}return ul(e.hostname)?`${s.replace(/\/+$/g,"")}/models`:void 0}function ul(s){let e=s.trim().toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e==="::1"||e==="0:0:0:0:0:0:0:1"||e.startsWith("127.")}function dl(s){if(s instanceof DOMException&&s.name==="AbortError")return!0;let e=hl(s);return e==="ECONNREFUSED"||e==="ECONNRESET"||e==="EHOSTUNREACH"||e==="ENETUNREACH"||e==="ETIMEDOUT"}function hl(s){if(!R(s))return"";let e=typeof s.code=="string"?s.code:"";if(e)return e;let t=R(s.cause)?s.cause:void 0;return typeof t?.code=="string"?t.code:""}function ml(s){return new Promise(e=>setTimeout(e,s))}function fl(){return[{name:wt,description:["Search ToolHub with the configured model and resolve installed MCP tools needed for a task.","MUST be called before answering any request about external services, installed MCP capabilities, business APIs, orders, coupons, stores, accounts, available tools, or capabilities that are not already obvious from the eager tools.",`Call this even if the user did not mention ToolHub or ${wt}.`,`Use ${Vs} after this tool returns selected tools.`,"Follow the returned executionPlanJs: await means serial dependency, and only calls grouped by Promise.all may be invoked in parallel.","Use the user's request as task and include concise context so the resolver can select the right tools."].join(" "),inputSchema:{type:"object",properties:{task:{type:"string"},context:{type:"object",additionalProperties:!0},constraints:{type:"object",properties:{maxTools:{type:"number"}},additionalProperties:!1}},required:["task"],additionalProperties:!1}},{name:Vs,description:`Invoke one MCP tool selected by ${wt}. Follow executionPlanJs from ${wt}; do not parallelize invoke calls unless that plan groups them in Promise.all.`,inputSchema:{type:"object",properties:{tool:{type:"string"},args:{type:"object",additionalProperties:!0}},required:["tool"],additionalProperties:!1}}]}function Un(){let s=He("TOOLHUB_MCP_SERVERS_JSON");if(!s)return[];try{let e=JSON.parse(s);return Array.isArray(e)?e.map(pl).filter(t=>!!t):[]}catch{return[]}}function pl(s){if(!R(s))return;let t=(typeof s.transport=="string"?s.transport:typeof s.type=="string"?s.type:"").toLowerCase().replace(/_/g,"-"),r=t==="streamable-http"||t==="streamablehttp"||t==="http"?"streamable-http":t==="sse"?"sse":"stdio",n=typeof s.name=="string"&&s.name.trim()?s.name.trim():"";if(!n)return;let o={label:typeof s.label=="string"&&s.label.trim()?s.label.trim():void 0,name:n,protocolVersion:typeof s.protocolVersion=="string"?s.protocolVersion:fs,requestTimeoutMs:Oi(s.requestTimeoutMs,We),startupTimeoutMs:Oi(s.startupTimeoutMs,We),transport:r};if(r!=="stdio"){let c=typeof s.url=="string"&&s.url.trim()?s.url.trim():"";return c?{...o,apiKey:typeof s.apiKey=="string"?s.apiKey:void 0,apiKeyEnv:typeof s.apiKeyEnv=="string"?s.apiKeyEnv:void 0,headers:Ni(s.headers)?s.headers:{},transport:r,url:c}:void 0}let i=typeof s.command=="string"&&s.command.trim()?s.command.trim():"";if(i)return{...o,args:Array.isArray(s.args)?s.args.filter(c=>typeof c=="string"):[],command:i,cwd:typeof s.cwd=="string"&&s.cwd.trim()?s.cwd.trim():void 0,env:Ni(s.env)?s.env:{},stdioMessageMode:s.stdioMessageMode==="newline-json"?"newline-json":"content-length",transport:r}}function oo(s){let e=R(s)&&Array.isArray(s.tools)?s.tools:[],t=[];for(let r of e)!R(r)||typeof r.name!="string"||!r.name.trim()||t.push({description:typeof r.description=="string"?r.description:"",inputSchema:gl(r.inputSchema??r.input_schema),name:r.name.trim(),outputSchema:Qn(r.outputSchema??r.output_schema),tags:Array.isArray(r.tags)?r.tags.filter(n=>typeof n=="string"):void 0,title:typeof r.title=="string"&&r.title.trim()?r.title.trim():void 0});return t}function gl(s){return R(s)?s:{type:"object",properties:{}}}function Qn(s){return R(s)?s:void 0}function _l(s){if(/^event:/m.test(s)||/^data:/m.test(s)){let e=s.split(/\n\n+/);for(let t of e){let r=t.split(/\n/).filter(n=>n.startsWith("data:")).map(n=>n.slice(5).trim()).join(`
35
+ `);if(r)try{return JSON.parse(r)}catch{continue}}}return JSON.parse(s)}function yl(s,e){let t=0;for(;;){let r=/\r?\n\r?\n/.exec(s.slice(t));if(!r||r.index<0)return s.slice(t);let n=t+r.index,o=s.slice(t,n);t=n+r[0].length;let i="message",c=[];for(let d of o.split(/\r?\n/))d.startsWith("event:")?i=d.slice(6).trim()||"message":d.startsWith("data:")&&c.push(d.slice(5).trimStart());(c.length>0||i!=="message")&&e({data:c.join(`
36
+ `),event:i})}}function Al(s){try{let e=JSON.parse(s);return R(e)?e:void 0}catch{let e=s.indexOf("{"),t=s.lastIndexOf("}");if(e<0||t<=e)return;try{let r=JSON.parse(s.slice(e,t+1));return R(r)?r:void 0}catch{return}}}function bl(s){let e=new Map,t=new Map;for(let r of s){let n=ce(r),o=(e.get(n)??0)+1;e.set(n,o),t.set(r,o===1?n:`${n}_${o}`)}return t}function ce(s){let e=s.replace(/[^a-zA-Z0-9_]/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"");return e?/^\d/.test(e)?`_${e}`:e:"tool"}function wl(s){return{alias:s.alias,canonicalName:s.canonicalName,description:s.description,invocationMode:s.invocation.mode,name:s.toolName,remoteToolName:s.remoteToolName,required:Br(s.inputSchema),serverId:s.serverId,serverLabel:s.serverLabel,sideEffect:s.invocation.sideEffect,title:s.title}}function Pl(s,e){return["You are the ToolHub resolve planner and retrieval agent.","Your job is to return the complete anticipated tool bundle for the user task, not just the first tool.","You must think ahead about the next likely steps needed to finish the task end-to-end.",`You MUST call ${ms} before your final answer.`,"You may need multiple planning and search rounds.","If your first workflow sketch yields zero, partial, or weak tool matches, revise the sketch and call the tree-sitter tool again before answering.","Workflow you must follow:","1. Plan the likely execution steps.","2. Draft a short JavaScript/TypeScript workflow sketch that uses the exact catalog tool names or aliases you expect to need.",'2a. Prefer sketches that call tools through string literals such as callTool("<exact catalog tool name>", {...}) or tools.call("<exact catalog tool name>", {...}).',"3. Call the tree-sitter tool on that sketch.","4. Inspect the tree-sitter result and check whether the bundle is complete end-to-end.","5. If it is incomplete, revise the sketch and call the tree-sitter tool again.","6. Return the final JSON only after the bundle is complete.",`Return at most ${e} tool names.`,"Final answer MUST be a JSON object with this shape:",'{ "summary": string, "steps": string[], "workflowSketch": string, "toolNames": string[] }',"Rules:","- toolNames must be exact catalog names or aliases.","- workflowSketch is the dependency plan that will be returned to the caller as executionPlanJs.","- In workflowSketch, use await to show serial dependencies and Promise.all([...]) only for tool calls that are independent and safe to invoke in parallel.","- Do not put side-effecting calls in Promise.all unless they are truly independent and safe to run concurrently.","- In workflowSketch, prefer string-literal tool calls over reconstructed member chains whenever possible.","- Include prerequisite and downstream tools you will likely need after the first action.","- Never invent tool names.","- Generic browser automation tools are a strong match for web tasks such as ordering, buying, booking, delivery, or checkout when no domain-specific MCP tool exists.",'- For browser navigation/open calls, prefer omitting waitUntil or using waitUntil: "interactive" so the agent can inspect and act as soon as the page is usable.','- Do not use waitUntil: "network_idle" for Gmail, Google sign-in, SPAs, mail, chat, auth, checkout, verification, or pages with long-lived requests. Use network_idle only when the user explicitly asks for network quiescence.',"- When selecting CCR browser automation tools, include the human-handoff follow-up tools needed if login, CAPTCHA, verification, blocked navigation, or manual confirmation appears.","- For CCR browser automation bundles, include browser_handoff_request and browser_handoff_wait when the workflow may need user help. Do not assume all browser tools are preloaded.","- For importing existing Chrome login state into CCR's in-app browser, select browser_chrome_login_import and include browser_chrome_login_import_status to check completion.","- If using member-call syntax, prefer tools.<catalog alias>(...) or mcp.<server namespace>.<remote tool name>(...).","- For lookup tasks, do not stop at opening or navigating. Include the tools needed to read or extract the answer.","- If the catalog has no strong match, return an empty toolNames array.","","Tool catalog:",JSON.stringify(s,null,2)].join(`
37
+ `)}function Il(s){let e=[];if(s.workflowSketch.trim()||e.push("workflowSketch is empty."),s.selectedToolNames.length===0&&e.push("Your current answer resolved to zero valid catalog tools."),s.summary.trim().toLowerCase().includes("no strong tool bundle match was found")&&e.push("Your summary says the bundle is weak; revise the workflow sketch and search again."),e.length!==0)return["Your last candidate tool bundle is incomplete.",...e.map((t,r)=>`${r+1}. ${t}`),`Revise the workflow sketch, call ${ms} again, and then return updated JSON only.`].join(`
38
+ `)}var Zn=class{collectReferences(e){if(!e.trim())return[];let t=[];return this.collectStringCallReferences(e,t),this.collectMemberReferences(e,t),vl(t)}collectStringCallReferences(e,t){let r=[{regex:/\bcallTool\s*\(\s*(["'`])([^"'`]+)\1/g,source:"callTool"},{regex:/\btools\s*\.\s*call\s*\(\s*(["'`])([^"'`]+)\1/g,source:"tools.call"},{regex:/\b[\w$]+\s*\.\s*callTool\s*\(\s*(["'`])([^"'`]+)\1/g,source:"context.callTool"},{regex:/\btools\s*\[\s*(["'`])([^"'`]+)\1\s*\]\s*\(/g,source:"tools.subscript"}];for(let n of r)for(let o of e.matchAll(n.regex)){let i=o[2]?.trim();i&&t.push(Ii(e,o.index??0,i,n.source))}}collectMemberReferences(e,t){let r=[{regex:/\btools\s*\.\s*([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*)\s*\(/g,source:"tools.member"},{regex:/\bmcp\s*\.\s*([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*){1,})\s*\(/g,source:"mcp.member"}];for(let n of r)for(let o of e.matchAll(n.regex)){let i=o[1]?.replace(/\s+/g,"");if(!i||i==="call")continue;let c=n.source==="mcp.member"?`mcp.${i}`:i;t.push(Ii(e,o.index??0,c,n.source))}}};function Ii(s,e,t,r){let o=s.slice(0,e).split(/\r?\n/);return{column:o[o.length-1].length+1,line:o.length,rawName:t,source:r}}function vl(s){let e=new Set,t=[];for(let r of s){let n=`${r.rawName}\0${r.source}\0${r.line}\0${r.column}`;e.has(n)||(e.add(n),t.push(r))}return t}function xl(s){try{let e=JSON.parse(s);return R(e)?e:{}}catch{return{}}}function vi(s){return Array.isArray(s)?s.filter(e=>typeof e=="string"):[]}function Sl(s){return Math.min(Math.max(io(s,so),1),20)}function Rl(s){return Math.min(Math.max(io(s,rl),1),sl)}function kl(s){return Math.max(io(s,We),nl)}function io(s,e){if(typeof s!="number"||!Number.isFinite(s))return e;let t=Math.floor(s);return t>0?t:e}function Gs(s,e){let t=e.trim();if(!t)return;let r=Q([t,ce(t),t.startsWith("mcp.")?t:`mcp.${t}`,t.startsWith("mcp_")?t:`mcp_${ce(t)}`]);for(let o of s){let i=Q([o.name,o.alias,o.canonicalName??"",o.canonicalName?ce(o.canonicalName):""].filter(Boolean));for(let c of r)if(i.includes(c))return o.name}let n=s.filter(o=>Cl(o,t));return n.length===1?n[0].name:void 0}function Cl(s,e){let t=ce(e),r=s.name.split(".").slice(1).join("."),n=s.remoteToolName||s.name.split(".").at(-1)||"",o=Q([s.canonicalName??"",s.canonicalName?ce(s.canonicalName):"",r,ce(r),n,ce(n)].filter(Boolean));return o.includes(e)||o.includes(t)}function Tl(s){return s.map(e=>{let t=Ol(e.toolName),r=`${t}Args`;return["/**",` * ${e.description||e.title}`,` * Exact tool name: "${e.toolName}".`,` * Callable references: "${e.toolName}", "${e.alias}".`," */",`type ${r} = ${El(e.inputSchema)};`,`type ${t}Call = { tool: "${e.toolName}"; args: ${r}; };`].join(`
39
39
  `)}).join(`
40
40
 
41
- `)}function Il(s){if(!R(s)||!R(s.properties))return"Record<string, unknown>";let e=new Set(ds(s)),t=["{"];for(let[r,n]of Object.entries(s.properties)){let o=R(n)?n:{};t.push(` ${JSON.stringify(r)}${e.has(r)?"":"?"}: ${xl(o)};`)}return t.push("}"),t.join(`
42
- `)}function xl(s){if(Array.isArray(s.enum)&&s.enum.every(e=>typeof e=="string"))return s.enum.map(e=>JSON.stringify(e)).join(" | ")||"string";switch(s.type){case"array":return"unknown[]";case"boolean":return"boolean";case"integer":case"number":return"number";case"object":return"Record<string, unknown>";case"string":return"string";default:return"unknown"}}function vl(s){return s.replace(/[^a-zA-Z0-9]+/g," ").trim().split(/\s+/).map(r=>`${r.slice(0,1).toUpperCase()}${r.slice(1)}`).join("")||"Tool"}function Sl(s,e,t){let r=Gs(s),n=new Set(r),o=[e.toolName,e.alias,e.canonicalName,e.remoteToolName,e.serverId,e.serverLabel??"",e.title,e.description,...e.tags].join(" "),i=Gs(o),c=t.get(e.remoteToolName)??t.get(e.toolName)??0;for(let d of i)n.has(d)&&(c+=d.length>4?3:1);return e.invocation.sideEffect&&(c-=8),c}function Rl(s){let e=new Set(Gs(s)),t=s.toLowerCase(),r=new Map,n=(o,i)=>r.set(o,Math.max(r.get(o)??0,i));return(us(e,["app","book","booking","browse","buy","cart","checkout","coffee","delivery","latte","order","pickup","product","purchase","restaurant","search","shop","store","website"])||/咖啡|拿铁|生椰|点单|下单|外卖|配送|自取|门店|商品|购买|结账|订单/.test(t))&&(n("browser_session_open",120),n("browser_navigate",112),n("browser_snapshot",108),n("browser_ax_query",96),n("browser_element_input",88),n("browser_element_click",84),n("browser_screenshot",60),n("browser_events_await",44)),(us(e,["address","delivery","geo","geolocation","location","nearby","pickup","store"])||/地址|定位|位置|附近|配送|外卖|自取|门店/.test(t))&&(n("location_permission_status",90),n("location_get_current",86)),(us(e,["ask","choice","confirm","confirmation","missing","option","preference","question","select","user"])||/确认|选择|偏好|口味|缺少|询问|用户/.test(t))&&n("user_interaction_collect",82),r}function Gs(s){let e=s.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>1&&!kl.has(t));return Q(e)}var kl=new Set(["a","an","and","are","as","be","by","for","from","in","is","it","need","of","or","the","then","to","with"]);function Cl(s){let e=new Set,t=[];for(let r of s)e.has(r.toolName)||(e.add(r.toolName),t.push(r));return t}function Tl(s){return s.length>0?s.slice(0,5).map(e=>`await callTool(${JSON.stringify(e.toolName)}, {});`).join(`
43
- `):void 0}function El(s){let e=`${s.name} ${s.title??""} ${s.description??""}`,t=$l(e),r=new Set(t),n=us(r,["book","cancel","commit","create","delete","execute","merge","post","publish","purchase","push","remove","reserve","run","send","submit","update","write"]);return{mode:us(r,["batch","bulk","foreach","iterate","parallel"])||Bn(t,["for","each"])||Bn(t,["sync","all"])||Bn(t,["export","all"])?"workflow":"both",sideEffect:n}}function $l(s){return s.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/[^a-zA-Z0-9_]+/g," ").toLowerCase().split(/\s+|_+/).filter(Boolean)}function us(s,e){return e.some(t=>s.has(t))}function Bn(s,e){if(e.length===0||s.length<e.length)return!1;for(let t=0;t<=s.length-e.length;t+=1)if(e.every((r,n)=>s[t+n]===r))return!0;return!1}function Ol(s){let e=s.map((r,n)=>({index:n,rank:Ai(r),tool:r})).filter(r=>!r.tool.invocation.sideEffect);return(e.length?e:s.map((r,n)=>({index:n,rank:Ai(r),tool:r}))).sort((r,n)=>r.rank.derivedRequiredCount-n.rank.derivedRequiredCount||n.rank.userSuppliedRequiredCount-r.rank.userSuppliedRequiredCount||r.rank.requiredCount-n.rank.requiredCount||r.index-n.index)[0]?.tool}function Ai(s){let e=ds(s.inputSchema);return{derivedRequiredCount:e.filter(Nl).length,requiredCount:e.length,userSuppliedRequiredCount:e.filter(Ml).length}}function Nl(s){let e=Oi(s);return/(?:dept|department|shop|store|merchant|product|goods|sku|cart|order|payment|coupon|address)id$/.test(e)||/(?:sku|order|product|goods|shop|store)(?:code|no|num|number)$/.test(e)||e==="id"||e.endsWith("list")}function Ml(s){let e=Oi(s);return e==="query"||e==="keyword"||e==="keywords"||e==="search"||e==="address"||e==="city"||e==="latitude"||e==="lat"||e==="longitude"||e==="lng"||e==="lon"||e.endsWith("name")||e.endsWith("text")}function Oi(s){return s.trim().toLowerCase().replace(/[^a-z0-9]+/g,"")}function ds(s){return Array.isArray(s?.required)?s.required.filter(e=>typeof e=="string"):[]}function bi(s){return s.transport==="stdio"?{...s,args:s.args?[...s.args]:void 0,env:s.env?{...s.env}:void 0}:{...s,headers:s.headers?{...s.headers}:void 0}}function jl(s,e){return!s||s.length===0?[...e.keys()]:Q(s.map(t=>t.trim()).filter(t=>e.has(t)))}var wi={readDiscovery(s,e){let t=Pi(),r=t.discovery[s];return r?r.configHash!==e?(delete t.discovery[s],Ii(t),null):{cachedAt:r.cachedAt,configHash:r.configHash,lastSeenOnlineAt:r.lastSeenOnlineAt,tools:r.tools.map(n=>({...n}))}:null},writeDiscovery(s,e,t,r=Date.now()){let n=Pi();n.discovery[s]={cachedAt:Date.now(),configHash:e,lastSeenOnlineAt:r,tools:t.map(o=>({...o}))},Ii(n)}};function Pi(){try{let s=Ni();if(!(0,_e.existsSync)(s))return Vn();let e=JSON.parse((0,_e.readFileSync)(s,"utf8"));return Ll(e)}catch{return Vn()}}function Ii(s){let e=Ni();(0,_e.mkdirSync)(Yn.default.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.tmp`;(0,_e.writeFileSync)(t,`${JSON.stringify(s,null,2)}
44
- `,{encoding:"utf8",mode:384}),(0,_e.renameSync)(t,e)}function Vn(){return{discovery:{},version:1}}function Ll(s){if(!R(s)||s.version!==1||!R(s.discovery))return Vn();let e={};for(let[t,r]of Object.entries(s.discovery))!R(r)||typeof r.configHash!="string"||!Array.isArray(r.tools)||(e[t]={cachedAt:typeof r.cachedAt=="number"&&Number.isFinite(r.cachedAt)?r.cachedAt:Date.now(),configHash:r.configHash,lastSeenOnlineAt:typeof r.lastSeenOnlineAt=="number"&&Number.isFinite(r.lastSeenOnlineAt)?r.lastSeenOnlineAt:void 0,tools:r.tools.map(Fl).filter(n=>!!n)});return{discovery:e,version:1}}function Fl(s){return!R(s)||typeof s.name!="string"||!s.name.trim()?null:{description:typeof s.description=="string"?s.description:"",inputSchema:Jn(s.inputSchema),name:s.name.trim(),outputSchema:Jn(s.outputSchema),tags:Array.isArray(s.tags)?s.tags.filter(e=>typeof e=="string"):void 0,title:typeof s.title=="string"&&s.title.trim()?s.title.trim():void 0}}function Ni(){return De("TOOLHUB_CACHE_FILE")||Yn.default.join(Ei.default.homedir(),".claude-code-router","toolhub-cache.json")}function Mi(s){return(0,Xs.createHash)("sha256").update(Xn(s)??"null").digest("hex")}function Xn(s){if(s===void 0)return;if(s===null||typeof s!="object")return JSON.stringify(s);if(Array.isArray(s))return`[${s.map(r=>Xn(r)??"null").join(",")}]`;let e=s;return`{${Object.keys(e).filter(r=>e[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${Xn(e[r])??"null"}`).join(",")}}`}function Kl(s){return s.trim().toLowerCase().replace(/\s+/g," ")}function xi(s){return typeof s=="string"&&s.trim()?s.trim():void 0}function Bl(s){try{let e=JSON.stringify(s);return e.length>600?`${e.slice(0,600)}...`:e}catch{return String(s)}}function Q(s){return[...new Set(s)]}function Ds(s,e){return{id:s,jsonrpc:"2.0",result:e}}function bt(s,e,t){return{error:{code:e,message:t},id:s,jsonrpc:"2.0"}}function Vs(s,e="content-length"){let t=JSON.stringify(s);if(e==="newline-json"){process.stdout.write(`${t}
41
+ `)}function El(s){if(!R(s)||!R(s.properties))return"Record<string, unknown>";let e=new Set(Br(s)),t=["{"];for(let[r,n]of Object.entries(s.properties)){let o=R(n)?n:{};t.push(` ${JSON.stringify(r)}${e.has(r)?"":"?"}: ${$l(o)};`)}return t.push("}"),t.join(`
42
+ `)}function $l(s){if(Array.isArray(s.enum)&&s.enum.every(e=>typeof e=="string"))return s.enum.map(e=>JSON.stringify(e)).join(" | ")||"string";switch(s.type){case"array":return"unknown[]";case"boolean":return"boolean";case"integer":case"number":return"number";case"object":return"Record<string, unknown>";case"string":return"string";default:return"unknown"}}function Ol(s){return s.replace(/[^a-zA-Z0-9]+/g," ").trim().split(/\s+/).map(r=>`${r.slice(0,1).toUpperCase()}${r.slice(1)}`).join("")||"Tool"}function Nl(s,e,t){let r=Xs(s),n=new Set(r),o=[e.toolName,e.alias,e.canonicalName,e.remoteToolName,e.serverId,e.serverLabel??"",e.title,e.description,...e.tags].join(" "),i=Xs(o),c=t.get(e.remoteToolName)??t.get(e.toolName)??0;for(let d of i)n.has(d)&&(c+=d.length>4?3:1);return e.invocation.sideEffect&&(c-=8),c}function Ml(s){let e=new Set(Xs(s)),t=s.toLowerCase(),r=new Map,n=(o,i)=>r.set(o,Math.max(r.get(o)??0,i));return(Fr(e,["app","book","booking","browse","buy","cart","checkout","coffee","delivery","latte","order","pickup","product","purchase","restaurant","search","shop","store","website"])||/咖啡|拿铁|生椰|点单|下单|外卖|配送|自取|门店|商品|购买|结账|订单/.test(t))&&(n("browser_session_open",120),n("browser_navigate",112),n("browser_snapshot",108),n("browser_ax_query",96),n("browser_element_input",88),n("browser_element_click",84),n("browser_screenshot",60),n("browser_events_await",44)),(Fr(e,["auth","chrome","cookie","cookies","import","localstorage","login","session","signin","storage"])||/chrome|cookie|cookies|localstorage|local storage|登录态|登录状态|导入登录|浏览器登录|本地存储/.test(t))&&(n("browser_chrome_login_import",128),n("browser_chrome_login_import_status",92)),(Fr(e,["address","delivery","geo","geolocation","location","nearby","pickup","store"])||/地址|定位|位置|附近|配送|外卖|自取|门店/.test(t))&&(n("location_permission_status",90),n("location_get_current",86)),(Fr(e,["ask","choice","confirm","confirmation","missing","option","preference","question","select","user"])||/确认|选择|偏好|口味|缺少|询问|用户/.test(t))&&n("user_interaction_collect",82),r}function qn(s,e){return Bi(s)?[e.find(t=>De(t)&&t.remoteToolName==="browser_chrome_login_import"),e.find(t=>De(t)&&t.remoteToolName==="browser_chrome_login_import_status")].filter(t=>!!t):[]}function Bi(s){let e=s.toLowerCase();return e.includes("browser_chrome_login_import")||/(chrome|谷歌浏览器|浏览器).*(login|signin|auth|cookie|localstorage|local storage|session|登录态|登录状态|登录信息|本地存储|cookie)/.test(e)||/(import|导入|迁移|同步).*(chrome|谷歌浏览器).*(login|signin|auth|cookie|localstorage|local storage|session|登录态|登录状态|登录信息|本地存储)/.test(e)||/(登录态|登录状态|登录信息).*(chrome|谷歌浏览器|浏览器).*(导入|迁移|同步)/.test(e)}function jl(s){return s.some(e=>De(e)&&e.remoteToolName==="browser_chrome_login_import")}function Xs(s){let e=s.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>1&&!Ll.has(t));return Q(e)}var Ll=new Set(["a","an","and","are","as","be","by","for","from","in","is","it","need","of","or","the","then","to","with"]);function hs(s){let e=new Set,t=[];for(let r of s)e.has(r.toolName)||(e.add(r.toolName),t.push(r));return t}function Dn(s,e){let t=hs(s),r=new Set(t.map(h=>h.toolName)),n=new Set(t.map(h=>h.remoteToolName)),o=t.some(h=>De(h)),i=t.some(h=>De(h)&&(h.remoteToolName==="browser_handoff_request"||h.remoteToolName==="askHumanHelp")),c=t.some(h=>De(h)&&h.remoteToolName==="browser_chrome_login_import"),d=new Set;o&&(d.add("browser_handoff_request"),d.add("browser_handoff_status"),d.add("browser_handoff_wait")),i&&d.add("browser_handoff_wait"),c&&d.add("browser_chrome_login_import_status");for(let h of d){if(n.has(h))continue;let g=e.find(m=>De(m)&&m.remoteToolName===h&&!r.has(m.toolName));g&&(t.push(g),r.add(g.toolName),n.add(g.remoteToolName))}return t}function De(s){return s.serverName==="ccr-browser-automation"||s.serverId==="ccr-browser-automation"||s.serverNamespace==="ccr_browser_automation"||s.toolName.startsWith("mcp.ccr_browser_automation.")}function Fl(s){return s.length>0?Ys(s):void 0}function Bl(s){return De(s)&&(s.toolName.endsWith("browser_session_open")||s.toolName.endsWith("browser_navigate")||s.remoteToolName==="browser_session_open"||s.remoteToolName==="browser_navigate")}function Kl(s,e){return(typeof s=="string"?s.trim():"")||Ys(e)}function Ys(s){if(s.length===0)return["async function runWithToolHub() {"," // Ask the user for missing task details before invoking tools.","}"].join(`
43
+ `);let e=["async function runWithToolHub() {"," // Invoke calls in this order unless the plan explicitly uses Promise.all."];return s.forEach((t,r)=>{e.push(` const step${r+1} = await callTool(${JSON.stringify(t.toolName)}, ${zl(t)});`)}),e.push("}"),e.join(`
44
+ `)}function zl(s){if(Bl(s))return'{ url, waitUntil: "interactive" }';let e=Br(s.inputSchema);return e.length===0?"{}":`{ ${e.map(t=>`${JSON.stringify(t)}: ${Ul(t)}`).join(", ")} }`}function Ul(s){let e=ce(s).replace(/^[A-Z]/,t=>t.toLowerCase());return!e||Yc.has(e)?"value":e}function ql(s){let e=`${s.name} ${s.title??""} ${s.description??""}`,t=Dl(e),r=new Set(t),n=Fr(r,["book","cancel","commit","create","delete","execute","merge","post","publish","purchase","push","remove","reserve","run","send","submit","update","write"]);return{mode:Fr(r,["batch","bulk","foreach","iterate","parallel"])||Hn(t,["for","each"])||Hn(t,["sync","all"])||Hn(t,["export","all"])?"workflow":"both",sideEffect:n}}function Dl(s){return s.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/[^a-zA-Z0-9_]+/g," ").toLowerCase().split(/\s+|_+/).filter(Boolean)}function Fr(s,e){return e.some(t=>s.has(t))}function Hn(s,e){if(e.length===0||s.length<e.length)return!1;for(let t=0;t<=s.length-e.length;t+=1)if(e.every((r,n)=>s[t+n]===r))return!0;return!1}function Hl(s){let e=s.map((r,n)=>({index:n,rank:xi(r),tool:r})).filter(r=>!r.tool.invocation.sideEffect);return(e.length?e:s.map((r,n)=>({index:n,rank:xi(r),tool:r}))).sort((r,n)=>r.rank.derivedRequiredCount-n.rank.derivedRequiredCount||n.rank.userSuppliedRequiredCount-r.rank.userSuppliedRequiredCount||r.rank.requiredCount-n.rank.requiredCount||r.index-n.index)[0]?.tool}function xi(s){let e=Br(s.inputSchema);return{derivedRequiredCount:e.filter(Wl).length,requiredCount:e.length,userSuppliedRequiredCount:e.filter(Jl).length}}function Wl(s){let e=Ki(s);return/(?:dept|department|shop|store|merchant|product|goods|sku|cart|order|payment|coupon|address)id$/.test(e)||/(?:sku|order|product|goods|shop|store)(?:code|no|num|number)$/.test(e)||e==="id"||e.endsWith("list")}function Jl(s){let e=Ki(s);return e==="query"||e==="keyword"||e==="keywords"||e==="search"||e==="address"||e==="city"||e==="latitude"||e==="lat"||e==="longitude"||e==="lng"||e==="lon"||e.endsWith("name")||e.endsWith("text")}function Ki(s){return s.trim().toLowerCase().replace(/[^a-z0-9]+/g,"")}function Br(s){return Array.isArray(s?.required)?s.required.filter(e=>typeof e=="string"):[]}function Si(s){return s.transport==="stdio"?{...s,args:s.args?[...s.args]:void 0,env:s.env?{...s.env}:void 0}:{...s,headers:s.headers?{...s.headers}:void 0}}function Gl(s,e){return!s||s.length===0?[...e.keys()]:Q(s.map(t=>t.trim()).filter(t=>e.has(t)))}var Ri={readDiscovery(s,e){let t=ki(),r=t.discovery[s];return r?r.configHash!==e?(delete t.discovery[s],Ci(t),null):{cachedAt:r.cachedAt,configHash:r.configHash,lastSeenOnlineAt:r.lastSeenOnlineAt,tools:r.tools.map(n=>({...n}))}:null},writeDiscovery(s,e,t,r=Date.now()){let n=ki();n.discovery[s]={cachedAt:Date.now(),configHash:e,lastSeenOnlineAt:r,tools:t.map(o=>({...o}))},Ci(n)}};function ki(){try{let s=zi();if(!(0,_e.existsSync)(s))return eo();let e=JSON.parse((0,_e.readFileSync)(s,"utf8"));return Vl(e)}catch{return eo()}}function Ci(s){let e=zi();(0,_e.mkdirSync)(ro.default.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.tmp`;(0,_e.writeFileSync)(t,`${JSON.stringify(s,null,2)}
45
+ `,{encoding:"utf8",mode:384}),(0,_e.renameSync)(t,e)}function eo(){return{discovery:{},version:1}}function Vl(s){if(!R(s)||s.version!==1||!R(s.discovery))return eo();let e={};for(let[t,r]of Object.entries(s.discovery))!R(r)||typeof r.configHash!="string"||!Array.isArray(r.tools)||(e[t]={cachedAt:typeof r.cachedAt=="number"&&Number.isFinite(r.cachedAt)?r.cachedAt:Date.now(),configHash:r.configHash,lastSeenOnlineAt:typeof r.lastSeenOnlineAt=="number"&&Number.isFinite(r.lastSeenOnlineAt)?r.lastSeenOnlineAt:void 0,tools:r.tools.map(Xl).filter(n=>!!n)});return{discovery:e,version:1}}function Xl(s){return!R(s)||typeof s.name!="string"||!s.name.trim()?null:{description:typeof s.description=="string"?s.description:"",inputSchema:Qn(s.inputSchema),name:s.name.trim(),outputSchema:Qn(s.outputSchema),tags:Array.isArray(s.tags)?s.tags.filter(e=>typeof e=="string"):void 0,title:typeof s.title=="string"&&s.title.trim()?s.title.trim():void 0}}function zi(){return He("TOOLHUB_CACHE_FILE")||ro.default.join(Li.default.homedir(),".claude-code-router","toolhub-cache.json")}function Ui(s){return(0,Zs.createHash)("sha256").update(to(s)??"null").digest("hex")}function to(s){if(s===void 0)return;if(s===null||typeof s!="object")return JSON.stringify(s);if(Array.isArray(s))return`[${s.map(r=>to(r)??"null").join(",")}]`;let e=s;return`{${Object.keys(e).filter(r=>e[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${to(e[r])??"null"}`).join(",")}}`}function Yl(s){return s.trim().toLowerCase().replace(/\s+/g," ")}function Ti(s){return typeof s=="string"&&s.trim()?s.trim():void 0}function Ql(s){try{let e=JSON.stringify(s);return e.length>600?`${e.slice(0,600)}...`:e}catch{return String(s)}}function Q(s){return[...new Set(s)]}function Ws(s,e){return{id:s,jsonrpc:"2.0",result:e}}function Pt(s,e,t){return{error:{code:e,message:t},id:s,jsonrpc:"2.0"}}function Qs(s,e="content-length"){let t=JSON.stringify(s);if(e==="newline-json"){process.stdout.write(`${t}
45
46
  `);return}process.stdout.write(`Content-Length: ${Buffer.byteLength(t,"utf8")}\r
46
47
  \r
47
- ${t}`)}function vi(s,e){return{content:[{text:`${s}: ${e}`,type:"text"}],isError:!0}}function Hs(s){return{...s,content:[{text:JSON.stringify(s,null,2),type:"text"}],structuredContent:s}}function De(s){return process.env[s]?.trim()??""}function Si(s,e){let t=Number(process.env[s]);return Number.isFinite(t)?t:e}function zl(s){let e=typeof s=="number"?s:Number(s);return Number.isFinite(e)?Math.min(Math.max(Math.floor(e),1),20):Qn}function Ri(s,e){let t=typeof s=="number"?s:Number(s);return Number.isFinite(t)?Math.min(Math.max(Math.floor(t),100),6e5):e}function R(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function ki(s){return R(s)&&Object.values(s).every(e=>typeof e=="string")}function Lr(s){return s instanceof Error?s.message:String(s)}function Ci(s){return s instanceof Error?s:new Error(String(s))}
48
+ ${t}`)}function Ei(s,e){return{content:[{text:`${s}: ${e}`,type:"text"}],isError:!0}}function Js(s){return{...s,content:[{text:JSON.stringify(s,null,2),type:"text"}],structuredContent:s}}function He(s){return process.env[s]?.trim()??""}function $i(s,e){let t=Number(process.env[s]);return Number.isFinite(t)?t:e}function Zl(s){let e=typeof s=="number"?s:Number(s);return Number.isFinite(e)?Math.min(Math.max(Math.floor(e),1),20):so}function Oi(s,e){let t=typeof s=="number"?s:Number(s);return Number.isFinite(t)?Math.min(Math.max(Math.floor(t),100),6e5):e}function R(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function Ni(s){return R(s)&&Object.values(s).every(e=>typeof e=="string")}function Kr(s){return s instanceof Error?s.message:String(s)}function Mi(s){return s instanceof Error?s:new Error(String(s))}