@whoz-oss/coday-server 0.58.0 → 0.59.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/server.js +3 -3
package/package.json
CHANGED
package/server.js
CHANGED
|
@@ -981,7 +981,7 @@ Summary:
|
|
|
981
981
|
- Unique projects used: ${new Set(t.flatMap(u=>Array.from(u.projects))).size}`;return s+`
|
|
982
982
|
`+o.join(`
|
|
983
983
|
`)+c}};var kx=class extends An{constructor(t,n){super({commandWord:"stats",description:"Show usage statistics and analytics",isInternal:!0},t);this.services=n;this.handlers=[new Ax(this.interactor,this.services),new Cx(this.interactor,this.services)]}};var lYe=100,Tx=class{constructor(e,t,n,i){this.interactor=e;this.aiHandler=t;this.configHandler=n;this.services=i}handlers=[];maxIterations=lYe;killed=!1;processing=!1;init(e){try{let t=new Jv(this.interactor),n=new yx(this.interactor,this.services);if(this.handlers=[this.configHandler,new Qv(this.interactor),new Zv(this.interactor),t,n,new xx(this.interactor),new Ex(this.interactor),new kx(this.interactor,this.services)],_ae.forEach(i=>this.handlers.push(new xm(i,i.name))),e?.prompts)for(let[i,a]of Object.entries(e.prompts))this.handlers.push(new xm(a,i));this.handlers.push(this.aiHandler),this.handlers=this.handlers.filter(i=>i.requiredIntegrations.every(a=>this.services.integration.hasIntegration(a)))}catch(t){this.interactor.error(`Error initializing handlers: ${t}`)}}async handle(e){if(!e)throw new Error("Invalid command context");let t=0,n;this.processing=!0;try{do{if(this.killed)return e;if(n=e.getFirstCommand(),t++,this.isHelpAsked(n)){let a=["Available commands:",this.formatHelp("help/h/[nothing]","displays this help message"),...this.handlers.slice().filter(s=>!s.isInternal).map(s=>this.formatHelp(s.commandWord,s.description)).sort(),this.formatHelp("[any other text]","defaults to asking the AI with the current context.")];this.interactor.displayText(a.join(`
|
|
984
|
-
`));continue}if(!n)break;let i=this.handlers.find(a=>a.accept(n,e));try{if(i){if(e=await i.handle(n,e),e.aiThread?.runStatus==="STOPPED")return e.clearCommands(),this.processing=!1,e}else n.startsWith(this.aiHandler.commandWord)?this.interactor.error(`Could not handle request ${n}, check your AI integration`):e.addCommands(`${this.aiHandler.commandWord} ${n}`)}catch(a){this.interactor.error(`An error occurred while trying to process your request: ${a}`)}}while((n||t<this.maxIterations)&&this.processing)}finally{this.processing=!1}return t>=this.maxIterations&&this.interactor.warn("Maximum iterations reached for a command"),e}isHelpAsked(e){return e===""||e==="help"||e==="h"}formatHelp(e,t){return` - ${e.padEnd(15," ")} : ${t}`}stop(){this.processing=!1}kill(){this.stop(),this.killed=!0,this.aiHandler.kill()}};function Ze(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t}function ae(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}var BI=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return BI=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};function O4(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var I4=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};var Me=class extends Error{},jn=class r extends Me{constructor(e,t,n,i){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=i,this.requestID=i?.get("x-request-id"),this.error=t;let a=t;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let i=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,t,n,i){if(!e||!i)return new Al({message:n,cause:I4(t)});let a=t?.error;return e===400?new Vp(e,a,n,i):e===401?new Kp(e,a,n,i):e===403?new Jp(e,a,n,i):e===404?new Zp(e,a,n,i):e===409?new Yp(e,a,n,i):e===422?new Xp(e,a,n,i):e===429?new Qp(e,a,n,i):e>=500?new ed(e,a,n,i):new r(e,a,n,i)}},kn=class extends jn{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Al=class extends jn{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Cl=class extends Al{constructor({message:e}={}){super({message:e??"Request timed out."})}},Vp=class extends jn{},Kp=class extends jn{},Jp=class extends jn{},Zp=class extends jn{},Yp=class extends jn{},Xp=class extends jn{},Qp=class extends jn{},ed=class extends jn{},td=class extends Me{constructor(){super("Could not parse response content as the length limit was reached")}},rd=class extends Me{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Lo=class extends Error{constructor(e){super(e)}};var pYe=/^[a-z][a-z0-9+.-]*:/i,Sae=r=>pYe.test(r),Fi=r=>(Fi=Array.isArray,Fi(r)),zI=Fi;function UI(r){return typeof r!="object"?{}:r??{}}function Eae(r){if(!r)return!0;for(let e in r)return!1;return!0}function Aae(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function R4(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}var Cae=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Me(`${r} must be an integer`);if(e<0)throw new Me(`${r} must be a positive integer`);return e};var kae=r=>{try{return JSON.parse(r)}catch{return}};var Bo=r=>new Promise(e=>setTimeout(e,r));var kl="6.10.0";var Oae=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function dYe(){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 hYe=()=>{let r=dYe();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":kl,"X-Stainless-OS":Dae(Deno.build.os),"X-Stainless-Arch":Tae(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":kl,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":kl,"X-Stainless-OS":Dae(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Tae(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=mYe();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":kl,"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":kl,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function mYe(){if(typeof navigator>"u"||!navigator)return null;let r=[{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 r){let n=t.exec(navigator.userAgent);if(n){let i=n[1]||0,a=n[2]||0,s=n[3]||0;return{browser:e,version:`${i}.${a}.${s}`}}}return null}var Tae=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Dae=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),Pae,Iae=()=>Pae??(Pae=hYe());function Rae(){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 HI(...r){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(...r)}function Dx(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return HI({start(){},async pull(t){let{done:n,value:i}=await e.next();n?t.close():t.enqueue(i)},async cancel(){await e.return?.()}})}function WI(r){if(r[Symbol.asyncIterator])return r;let e=r.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 Fae(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}var jae=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Px="RFC3986",GI=r=>String(r),Ox={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:GI},VI="RFC1738";var Ix=(r,e)=>(Ix=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ix(r,e)),zo=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var KI=1024,Mae=(r,e,t,n,i)=>{if(r.length===0)return r;let a=r;if(typeof r=="symbol"?a=Symbol.prototype.toString.call(r):typeof r!="string"&&(a=String(r)),t==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let s="";for(let o=0;o<a.length;o+=KI){let c=a.length>=KI?a.slice(o,o+KI):a,u=[];for(let l=0;l<c.length;++l){let f=c.charCodeAt(l);if(f===45||f===46||f===95||f===126||f>=48&&f<=57||f>=65&&f<=90||f>=97&&f<=122||i===VI&&(f===40||f===41)){u[u.length]=c.charAt(l);continue}if(f<128){u[u.length]=zo[f];continue}if(f<2048){u[u.length]=zo[192|f>>6]+zo[128|f&63];continue}if(f<55296||f>=57344){u[u.length]=zo[224|f>>12]+zo[128|f>>6&63]+zo[128|f&63];continue}l+=1,f=65536+((f&1023)<<10|c.charCodeAt(l)&1023),u[u.length]=zo[240|f>>18]+zo[128|f>>12&63]+zo[128|f>>6&63]+zo[128|f&63]}s+=u.join("")}return s};function Nae(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function JI(r,e){if(Fi(r)){let t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}var $ae={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},Lae=function(r,e){Array.prototype.push.apply(r,Fi(e)?e:[e])},qae,Mn={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Mae,encodeValuesOnly:!1,format:Px,formatter:GI,indices:!1,serializeDate(r){return(qae??(qae=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function bYe(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var ZI={};function Bae(r,e,t,n,i,a,s,o,c,u,l,f,p,d,m,h,g,v){let b=r,x=v,E=0,C=!1;for(;(x=x.get(ZI))!==void 0&&!C;){let _=x.get(r);if(E+=1,typeof _<"u"){if(_===E)throw new RangeError("Cyclic object value");C=!0}typeof x.get(ZI)>"u"&&(E=0)}if(typeof u=="function"?b=u(e,b):b instanceof Date?b=p?.(b):t==="comma"&&Fi(b)&&(b=JI(b,function(_){return _ instanceof Date?p?.(_):_})),b===null){if(a)return c&&!h?c(e,Mn.encoder,g,"key",d):e;b=""}if(bYe(b)||Nae(b)){if(c){let _=h?e:c(e,Mn.encoder,g,"key",d);return[m?.(_)+"="+m?.(c(b,Mn.encoder,g,"value",d))]}return[m?.(e)+"="+m?.(String(b))]}let A=[];if(typeof b>"u")return A;let R;if(t==="comma"&&Fi(b))h&&c&&(b=JI(b,c)),R=[{value:b.length>0?b.join(",")||null:void 0}];else if(Fi(u))R=u;else{let _=Object.keys(b);R=l?_.sort(l):_}let I=o?String(e).replace(/\./g,"%2E"):String(e),w=n&&Fi(b)&&b.length===1?I+"[]":I;if(i&&Fi(b)&&b.length===0)return w+"[]";for(let _=0;_<R.length;++_){let y=R[_],T=typeof y=="object"&&typeof y.value<"u"?y.value:b[y];if(s&&T===null)continue;let P=f&&o?y.replace(/\./g,"%2E"):y,k=Fi(b)?typeof t=="function"?t(w,P):w:w+(f?"."+P:"["+P+"]");v.set(r,E);let D=new WeakMap;D.set(ZI,v),Lae(A,Bae(T,k,t,n,i,a,s,o,t==="comma"&&h&&Fi(b)?null:c,u,l,f,p,d,m,h,g,D))}return A}function yYe(r=Mn){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||Mn.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Px;if(typeof r.format<"u"){if(!Ix(Ox,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=Ox[t],i=Mn.filter;(typeof r.filter=="function"||Fi(r.filter))&&(i=r.filter);let a;if(r.arrayFormat&&r.arrayFormat in $ae?a=r.arrayFormat:"indices"in r?a=r.indices?"indices":"repeat":a=Mn.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let s=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:Mn.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:Mn.addQueryPrefix,allowDots:s,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:Mn.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:Mn.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?Mn.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:Mn.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:Mn.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:Mn.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:Mn.encodeValuesOnly,filter:i,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:Mn.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:Mn.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:Mn.strictNullHandling}}function YI(r,e={}){let t=r,n=yYe(e),i,a;typeof n.filter=="function"?(a=n.filter,t=a("",t)):Fi(n.filter)&&(a=n.filter,i=a);let s=[];if(typeof t!="object"||t===null)return"";let o=$ae[n.arrayFormat],c=o==="comma"&&n.commaRoundTrip;i||(i=Object.keys(t)),n.sort&&i.sort(n.sort);let u=new WeakMap;for(let p=0;p<i.length;++p){let d=i[p];n.skipNulls&&t[d]===null||Lae(s,Bae(t[d],d,o,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,u))}let l=s.join(n.delimiter),f=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?f+="utf8=%26%2310003%3B&":f+="utf8=%E2%9C%93&"),l.length>0?f+l:""}function Hae(r){let e=0;for(let i of r)e+=i.length;let t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}var zae;function nd(r){let e;return(zae??(e=new globalThis.TextEncoder,zae=e.encode.bind(e)))(r)}var Uae;function XI(r){let e;return(Uae??(e=new globalThis.TextDecoder,Uae=e.decode.bind(e)))(r)}var za,Ua,x3=class{constructor(){za.set(this,void 0),Ua.set(this,void 0),Ze(this,za,new Uint8Array,"f"),Ze(this,Ua,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?nd(e):e;Ze(this,za,Hae([ae(this,za,"f"),t]),"f");let n=[],i;for(;(i=wYe(ae(this,za,"f"),ae(this,Ua,"f")))!=null;){if(i.carriage&&ae(this,Ua,"f")==null){Ze(this,Ua,i.index,"f");continue}if(ae(this,Ua,"f")!=null&&(i.index!==ae(this,Ua,"f")+1||i.carriage)){n.push(XI(ae(this,za,"f").subarray(0,ae(this,Ua,"f")-1))),Ze(this,za,ae(this,za,"f").subarray(ae(this,Ua,"f")),"f"),Ze(this,Ua,null,"f");continue}let a=ae(this,Ua,"f")!==null?i.preceding-1:i.preceding,s=XI(ae(this,za,"f").subarray(0,a));n.push(s),Ze(this,za,ae(this,za,"f").subarray(i.index),"f"),Ze(this,Ua,null,"f")}return n}flush(){return ae(this,za,"f").length?this.decode(`
|
|
984
|
+
`));continue}if(!n)break;let i=this.handlers.find(a=>a.accept(n,e));try{if(i){if(e=await i.handle(n,e),e.aiThread?.runStatus==="STOPPED")return e.clearCommands(),this.processing=!1,e}else n.startsWith(this.aiHandler.commandWord)?this.interactor.error(`Could not handle request ${n}, check your AI integration`):e.addCommands(`${this.aiHandler.commandWord} ${n}`)}catch(a){this.interactor.error(`An error occurred while trying to process your request: ${a}`)}}while((n||t<this.maxIterations)&&this.processing)}finally{this.processing=!1}return t>=this.maxIterations&&this.interactor.warn("Maximum iterations reached for a command"),e}isHelpAsked(e){return e===""||e==="help"||e==="h"}formatHelp(e,t){return` - ${e.padEnd(15," ")} : ${t}`}stop(){this.processing=!1}kill(){this.stop(),this.killed=!0,this.aiHandler.kill()}};function Ze(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t}function ae(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}var BI=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return BI=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};function O4(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var I4=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};var Me=class extends Error{},jn=class r extends Me{constructor(e,t,n,i){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=i,this.requestID=i?.get("x-request-id"),this.error=t;let a=t;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let i=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,t,n,i){if(!e||!i)return new Al({message:n,cause:I4(t)});let a=t?.error;return e===400?new Vp(e,a,n,i):e===401?new Kp(e,a,n,i):e===403?new Jp(e,a,n,i):e===404?new Zp(e,a,n,i):e===409?new Yp(e,a,n,i):e===422?new Xp(e,a,n,i):e===429?new Qp(e,a,n,i):e>=500?new ed(e,a,n,i):new r(e,a,n,i)}},kn=class extends jn{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Al=class extends jn{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Cl=class extends Al{constructor({message:e}={}){super({message:e??"Request timed out."})}},Vp=class extends jn{},Kp=class extends jn{},Jp=class extends jn{},Zp=class extends jn{},Yp=class extends jn{},Xp=class extends jn{},Qp=class extends jn{},ed=class extends jn{},td=class extends Me{constructor(){super("Could not parse response content as the length limit was reached")}},rd=class extends Me{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Lo=class extends Error{constructor(e){super(e)}};var pYe=/^[a-z][a-z0-9+.-]*:/i,Sae=r=>pYe.test(r),Fi=r=>(Fi=Array.isArray,Fi(r)),zI=Fi;function UI(r){return typeof r!="object"?{}:r??{}}function Eae(r){if(!r)return!0;for(let e in r)return!1;return!0}function Aae(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function R4(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}var Cae=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Me(`${r} must be an integer`);if(e<0)throw new Me(`${r} must be a positive integer`);return e};var kae=r=>{try{return JSON.parse(r)}catch{return}};var Bo=r=>new Promise(e=>setTimeout(e,r));var kl="6.16.0";var Oae=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function dYe(){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 hYe=()=>{let r=dYe();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":kl,"X-Stainless-OS":Dae(Deno.build.os),"X-Stainless-Arch":Tae(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":kl,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":kl,"X-Stainless-OS":Dae(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Tae(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=mYe();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":kl,"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":kl,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function mYe(){if(typeof navigator>"u"||!navigator)return null;let r=[{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 r){let n=t.exec(navigator.userAgent);if(n){let i=n[1]||0,a=n[2]||0,s=n[3]||0;return{browser:e,version:`${i}.${a}.${s}`}}}return null}var Tae=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Dae=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),Pae,Iae=()=>Pae??(Pae=hYe());function Rae(){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 HI(...r){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(...r)}function Dx(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return HI({start(){},async pull(t){let{done:n,value:i}=await e.next();n?t.close():t.enqueue(i)},async cancel(){await e.return?.()}})}function WI(r){if(r[Symbol.asyncIterator])return r;let e=r.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 Fae(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}var jae=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Px="RFC3986",GI=r=>String(r),Ox={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:GI},VI="RFC1738";var Ix=(r,e)=>(Ix=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ix(r,e)),zo=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var KI=1024,Mae=(r,e,t,n,i)=>{if(r.length===0)return r;let a=r;if(typeof r=="symbol"?a=Symbol.prototype.toString.call(r):typeof r!="string"&&(a=String(r)),t==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let s="";for(let o=0;o<a.length;o+=KI){let c=a.length>=KI?a.slice(o,o+KI):a,u=[];for(let l=0;l<c.length;++l){let f=c.charCodeAt(l);if(f===45||f===46||f===95||f===126||f>=48&&f<=57||f>=65&&f<=90||f>=97&&f<=122||i===VI&&(f===40||f===41)){u[u.length]=c.charAt(l);continue}if(f<128){u[u.length]=zo[f];continue}if(f<2048){u[u.length]=zo[192|f>>6]+zo[128|f&63];continue}if(f<55296||f>=57344){u[u.length]=zo[224|f>>12]+zo[128|f>>6&63]+zo[128|f&63];continue}l+=1,f=65536+((f&1023)<<10|c.charCodeAt(l)&1023),u[u.length]=zo[240|f>>18]+zo[128|f>>12&63]+zo[128|f>>6&63]+zo[128|f&63]}s+=u.join("")}return s};function Nae(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function JI(r,e){if(Fi(r)){let t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}var $ae={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},Lae=function(r,e){Array.prototype.push.apply(r,Fi(e)?e:[e])},qae,Mn={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Mae,encodeValuesOnly:!1,format:Px,formatter:GI,indices:!1,serializeDate(r){return(qae??(qae=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function bYe(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var ZI={};function Bae(r,e,t,n,i,a,s,o,c,u,l,f,p,d,m,h,g,v){let b=r,x=v,E=0,C=!1;for(;(x=x.get(ZI))!==void 0&&!C;){let _=x.get(r);if(E+=1,typeof _<"u"){if(_===E)throw new RangeError("Cyclic object value");C=!0}typeof x.get(ZI)>"u"&&(E=0)}if(typeof u=="function"?b=u(e,b):b instanceof Date?b=p?.(b):t==="comma"&&Fi(b)&&(b=JI(b,function(_){return _ instanceof Date?p?.(_):_})),b===null){if(a)return c&&!h?c(e,Mn.encoder,g,"key",d):e;b=""}if(bYe(b)||Nae(b)){if(c){let _=h?e:c(e,Mn.encoder,g,"key",d);return[m?.(_)+"="+m?.(c(b,Mn.encoder,g,"value",d))]}return[m?.(e)+"="+m?.(String(b))]}let A=[];if(typeof b>"u")return A;let R;if(t==="comma"&&Fi(b))h&&c&&(b=JI(b,c)),R=[{value:b.length>0?b.join(",")||null:void 0}];else if(Fi(u))R=u;else{let _=Object.keys(b);R=l?_.sort(l):_}let I=o?String(e).replace(/\./g,"%2E"):String(e),w=n&&Fi(b)&&b.length===1?I+"[]":I;if(i&&Fi(b)&&b.length===0)return w+"[]";for(let _=0;_<R.length;++_){let y=R[_],T=typeof y=="object"&&typeof y.value<"u"?y.value:b[y];if(s&&T===null)continue;let P=f&&o?y.replace(/\./g,"%2E"):y,k=Fi(b)?typeof t=="function"?t(w,P):w:w+(f?"."+P:"["+P+"]");v.set(r,E);let D=new WeakMap;D.set(ZI,v),Lae(A,Bae(T,k,t,n,i,a,s,o,t==="comma"&&h&&Fi(b)?null:c,u,l,f,p,d,m,h,g,D))}return A}function yYe(r=Mn){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||Mn.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Px;if(typeof r.format<"u"){if(!Ix(Ox,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=Ox[t],i=Mn.filter;(typeof r.filter=="function"||Fi(r.filter))&&(i=r.filter);let a;if(r.arrayFormat&&r.arrayFormat in $ae?a=r.arrayFormat:"indices"in r?a=r.indices?"indices":"repeat":a=Mn.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let s=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:Mn.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:Mn.addQueryPrefix,allowDots:s,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:Mn.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:Mn.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?Mn.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:Mn.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:Mn.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:Mn.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:Mn.encodeValuesOnly,filter:i,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:Mn.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:Mn.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:Mn.strictNullHandling}}function YI(r,e={}){let t=r,n=yYe(e),i,a;typeof n.filter=="function"?(a=n.filter,t=a("",t)):Fi(n.filter)&&(a=n.filter,i=a);let s=[];if(typeof t!="object"||t===null)return"";let o=$ae[n.arrayFormat],c=o==="comma"&&n.commaRoundTrip;i||(i=Object.keys(t)),n.sort&&i.sort(n.sort);let u=new WeakMap;for(let p=0;p<i.length;++p){let d=i[p];n.skipNulls&&t[d]===null||Lae(s,Bae(t[d],d,o,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,u))}let l=s.join(n.delimiter),f=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?f+="utf8=%26%2310003%3B&":f+="utf8=%E2%9C%93&"),l.length>0?f+l:""}function Hae(r){let e=0;for(let i of r)e+=i.length;let t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}var zae;function nd(r){let e;return(zae??(e=new globalThis.TextEncoder,zae=e.encode.bind(e)))(r)}var Uae;function XI(r){let e;return(Uae??(e=new globalThis.TextDecoder,Uae=e.decode.bind(e)))(r)}var za,Ua,x3=class{constructor(){za.set(this,void 0),Ua.set(this,void 0),Ze(this,za,new Uint8Array,"f"),Ze(this,Ua,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?nd(e):e;Ze(this,za,Hae([ae(this,za,"f"),t]),"f");let n=[],i;for(;(i=wYe(ae(this,za,"f"),ae(this,Ua,"f")))!=null;){if(i.carriage&&ae(this,Ua,"f")==null){Ze(this,Ua,i.index,"f");continue}if(ae(this,Ua,"f")!=null&&(i.index!==ae(this,Ua,"f")+1||i.carriage)){n.push(XI(ae(this,za,"f").subarray(0,ae(this,Ua,"f")-1))),Ze(this,za,ae(this,za,"f").subarray(ae(this,Ua,"f")),"f"),Ze(this,Ua,null,"f");continue}let a=ae(this,Ua,"f")!==null?i.preceding-1:i.preceding,s=XI(ae(this,za,"f").subarray(0,a));n.push(s),Ze(this,za,ae(this,za,"f").subarray(i.index),"f"),Ze(this,Ua,null,"f")}return n}flush(){return ae(this,za,"f").length?this.decode(`
|
|
985
985
|
`):[]}};za=new WeakMap,Ua=new WeakMap;x3.NEWLINE_CHARS=new Set([`
|
|
986
986
|
`,"\r"]);x3.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function wYe(r,e){for(let i=e??0;i<r.length;i++){if(r[i]===10)return{preceding:i,index:i+1,carriage:!1};if(r[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function Wae(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}var Fx={off:0,error:200,warn:300,info:400,debug:500},QI=(r,e,t)=>{if(r){if(Aae(Fx,r))return r;vn(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(Fx))}`)}};function F4(){}function Rx(r,e,t){return!e||Fx[r]>Fx[t]?F4:e[r].bind(e)}var _Ye={error:F4,warn:F4,info:F4,debug:F4},Gae=new WeakMap;function vn(r){let e=r.logger,t=r.logLevel??"off";if(!e)return _Ye;let n=Gae.get(e);if(n&&n[0]===t)return n[1];let i={error:Rx("error",e,t),warn:Rx("warn",e,t),info:Rx("info",e,t),debug:Rx("debug",e,t)};return Gae.set(e,[t,i]),i}var Bc=r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r);var j4,Uo=class r{constructor(e,t,n){this.iterator=e,j4.set(this,void 0),this.controller=t,Ze(this,j4,n,"f")}static fromSSEResponse(e,t,n){let i=!1,a=n?vn(n):console;async function*s(){if(i)throw new Me("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let o=!1;try{for await(let c of SYe(e,t))if(!o){if(c.data.startsWith("[DONE]")){o=!0;continue}if(c.event===null||!c.event.startsWith("thread.")){let u;try{u=JSON.parse(c.data)}catch(l){throw a.error("Could not parse message into JSON:",c.data),a.error("From chunk:",c.raw),l}if(u&&u.error)throw new jn(void 0,u.error,void 0,e.headers);yield u}else{let u;try{u=JSON.parse(c.data)}catch(l){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),l}if(c.event=="error")throw new jn(void 0,u.error,u.message,void 0);yield{event:c.event,data:u}}}o=!0}catch(c){if(O4(c))return;throw c}finally{o||t.abort()}}return new r(s,t,n)}static fromReadableStream(e,t,n){let i=!1;async function*a(){let o=new x3,c=WI(e);for await(let u of c)for(let l of o.decode(u))yield l;for(let u of o.flush())yield u}async function*s(){if(i)throw new Me("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let o=!1;try{for await(let c of a())o||c&&(yield JSON.parse(c));o=!0}catch(c){if(O4(c))return;throw c}finally{o||t.abort()}}return new r(s,t,n)}[(j4=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),i=a=>({next:()=>{if(a.length===0){let s=n.next();e.push(s),t.push(s)}return a.shift()}});return[new r(()=>i(e),this.controller,ae(this,j4,"f")),new r(()=>i(t),this.controller,ae(this,j4,"f"))]}toReadableStream(){let e=this,t;return HI({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:i,done:a}=await t.next();if(a)return n.close();let s=nd(JSON.stringify(i)+`
|
|
987
987
|
`);n.enqueue(s)}catch(i){n.error(i)}},async cancel(){await t.return?.()}})}};async function*SYe(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Me("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 Me("Attempted to iterate over a response with no body");let t=new eR,n=new x3,i=WI(r.body);for await(let a of EYe(i))for(let s of n.decode(a)){let o=t.decode(s);o&&(yield o)}for(let a of n.flush()){let s=t.decode(a);s&&(yield s)}}async function*EYe(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?nd(t):t,i=new Uint8Array(e.length+n.length);i.set(e),i.set(n,e.length),e=i;let a;for(;(a=Wae(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}var eR=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 a={event:this.event,data:this.data.join(`
|
|
@@ -994,7 +994,7 @@ ${f}`)}return s},me=RYe(Xae);var _3=class extends xe{list(e,t={},n){return this.
|
|
|
994
994
|
${Vx(r)}`);if(A==null)throw new Me(`missing choices[${f}].tool_calls[${E}].type
|
|
995
995
|
${Vx(r)}`);if(_==null)throw new Me(`missing choices[${f}].tool_calls[${E}].function.name
|
|
996
996
|
${Vx(r)}`);if(w==null)throw new Me(`missing choices[${f}].tool_calls[${E}].function.arguments
|
|
997
|
-
${Vx(r)}`);return{...I,id:R,type:A,function:{...y,name:_,arguments:w}}})}}:{...d,message:{...v,content:m,role:b,refusal:u.refusal??null},finish_reason:l,index:f,logprobs:p}}),created:i,model:a,object:"chat.completion",...s?{system_fingerprint:s}:{}};return Qae(c,e)}function Vx(r){return JSON.stringify(r)}var K4=class r extends E3{static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,n){let i=new r(t),a={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(e,t,a)),i}};var Wc=class extends xe{constructor(){super(...arguments),this.messages=new _3(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(me`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(me`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/chat/completions",Ct,{query:e,...t})}delete(e,t){return this._client.delete(me`/chat/completions/${e}`,t)}parse(e,t){return rse(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>z4(n,e))}runTools(e,t){return e.stream?K4.runTools(this._client,e,t):V4.runTools(this._client,e,t)}stream(e,t){return E3.createChatCompletion(this._client,e,t)}};Wc.Messages=_3;var Pl=class extends xe{constructor(){super(...arguments),this.completions=new Wc(this._client)}};Pl.Completions=Wc;var cse=Symbol("brand.privateNullableHeaders");function*UYe(r){if(!r)return;if(cse in r){let{values:n,nulls:i}=r;yield*n.entries();for(let a of i)yield[a,null];return}let e=!1,t;r instanceof Headers?t=r.entries():zI(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let n of t){let i=n[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let a=zI(n[1])?n[1]:[n[1]],s=!1;for(let o of a)o!==void 0&&(e&&!s&&(s=!0,yield[i,null]),yield[i,o])}}var ke=r=>{let e=new Headers,t=new Set;for(let n of r){let i=new Set;for(let[a,s]of UYe(n)){let o=a.toLowerCase();i.has(o)||(e.delete(a),i.add(o)),s===null?(e.delete(a),t.add(o)):(e.append(a,s),t.delete(o))}}return{[cse]:!0,values:e,nulls:t}};var ud=class extends xe{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:ke([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};var ld=class extends xe{create(e,t){return this._client.post("/audio/transcriptions",Ha({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};var fd=class extends xe{create(e,t){return this._client.post("/audio/translations",Ha({body:e,...t,__metadata:{model:e.model}},this._client))}};var Wo=class extends xe{constructor(){super(...arguments),this.transcriptions=new ld(this._client),this.translations=new fd(this._client),this.speech=new ud(this._client)}};Wo.Transcriptions=ld;Wo.Translations=fd;Wo.Speech=ud;var A3=class extends xe{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(me`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",Ct,{query:e,...t})}cancel(e,t){return this._client.post(me`/batches/${e}/cancel`,t)}};var pd=class extends xe{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(me`/assistants/${e}`,{...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(me`/assistants/${e}`,{body:t,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",Ct,{query:e,...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(me`/assistants/${e}`,{...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var dd=class extends xe{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var hd=class extends xe{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var Ol=class extends xe{constructor(){super(...arguments),this.sessions=new dd(this._client),this.transcriptionSessions=new hd(this._client)}};Ol.Sessions=dd;Ol.TranscriptionSessions=hd;var md=class extends xe{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:ke([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(me`/chatkit/sessions/${e}/cancel`,{...t,headers:ke([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}};var gd=class extends xe{retrieve(e,t){return this._client.get(me`/chatkit/threads/${e}`,{...t,headers:ke([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",zc,{query:e,...t,headers:ke([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(me`/chatkit/threads/${e}`,{...t,headers:ke([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},n){return this._client.getAPIList(me`/chatkit/threads/${e}/items`,zc,{query:t,...n,headers:ke([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}};var Il=class extends xe{constructor(){super(...arguments),this.sessions=new md(this._client),this.threads=new gd(this._client)}};Il.Sessions=md;Il.Threads=gd;var vd=class extends xe{create(e,t,n){return this._client.post(me`/threads/${e}/messages`,{body:t,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{thread_id:i}=t;return this._client.get(me`/threads/${i}/messages/${e}`,{...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{thread_id:i,...a}=t;return this._client.post(me`/threads/${i}/messages/${e}`,{body:a,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(me`/threads/${e}/messages`,Ct,{query:t,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t,n){let{thread_id:i}=t;return this._client.delete(me`/threads/${i}/messages/${e}`,{...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var bd=class extends xe{retrieve(e,t,n){let{thread_id:i,run_id:a,...s}=t;return this._client.get(me`/threads/${i}/runs/${a}/steps/${e}`,{query:s,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t,n){let{thread_id:i,...a}=t;return this._client.getAPIList(me`/threads/${i}/runs/${e}/steps`,Ct,{query:a,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var use=r=>{if(typeof Buffer<"u"){let e=Buffer.from(r,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(r),t=e.length,n=new Uint8Array(t);for(let i=0;i<t;i++)n[i]=e.charCodeAt(i);return Array.from(new Float32Array(n.buffer))}};var Rl=r=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()};var gi,k3,_R,Go,Kx,Ys,T3,yd,C3,Yx,Wa,Jx,Zx,Y4,J4,Z4,lse,fse,pse,dse,hse,mse,gse,Gc=class extends Tl{constructor(){super(...arguments),gi.add(this),_R.set(this,[]),Go.set(this,{}),Kx.set(this,{}),Ys.set(this,void 0),T3.set(this,void 0),yd.set(this,void 0),C3.set(this,void 0),Yx.set(this,void 0),Wa.set(this,void 0),Jx.set(this,void 0),Zx.set(this,void 0),Y4.set(this,void 0)}[(_R=new WeakMap,Go=new WeakMap,Kx=new WeakMap,Ys=new WeakMap,T3=new WeakMap,yd=new WeakMap,C3=new WeakMap,Yx=new WeakMap,Wa=new WeakMap,Jx=new WeakMap,Zx=new WeakMap,Y4=new WeakMap,gi=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("event",i=>{let a=t.shift();a?a.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{n=!0;for(let a of t)a.reject(i);t.length=0}),this.on("error",i=>{n=!0;for(let a of t)a.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,s)=>t.push({resolve:a,reject:s})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new k3;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let i=Uo.fromReadableStream(e,this.controller);for await(let a of i)ae(this,gi,"m",J4).call(this,a);if(i.controller.signal?.aborted)throw new kn;return this._addRun(ae(this,gi,"m",Z4).call(this))}toReadableStream(){return new Uo(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,i){let a=new k3;return a._run(()=>a._runToolAssistantStream(e,t,n,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,t,n,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));let s={...n,stream:!0},o=await e.submitToolOutputs(t,s,{...i,signal:this.controller.signal});this._connected();for await(let c of o)ae(this,gi,"m",J4).call(this,c);if(o.controller.signal?.aborted)throw new kn;return this._addRun(ae(this,gi,"m",Z4).call(this))}static createThreadAssistantStream(e,t,n){let i=new k3;return i._run(()=>i._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}static createAssistantStream(e,t,n,i){let a=new k3;return a._run(()=>a._runAssistantStream(e,t,n,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return ae(this,Jx,"f")}currentRun(){return ae(this,Zx,"f")}currentMessageSnapshot(){return ae(this,Ys,"f")}currentRunStepSnapshot(){return ae(this,Y4,"f")}async finalRunSteps(){return await this.done(),Object.values(ae(this,Go,"f"))}async finalMessages(){return await this.done(),Object.values(ae(this,Kx,"f"))}async finalRun(){if(await this.done(),!ae(this,T3,"f"))throw Error("Final run was not received.");return ae(this,T3,"f")}async _createThreadAssistantStream(e,t,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let a={...t,stream:!0},s=await e.createAndRun(a,{...n,signal:this.controller.signal});this._connected();for await(let o of s)ae(this,gi,"m",J4).call(this,o);if(s.controller.signal?.aborted)throw new kn;return this._addRun(ae(this,gi,"m",Z4).call(this))}async _createAssistantStream(e,t,n,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));let s={...n,stream:!0},o=await e.create(t,s,{...i,signal:this.controller.signal});this._connected();for await(let c of o)ae(this,gi,"m",J4).call(this,c);if(o.controller.signal?.aborted)throw new kn;return this._addRun(ae(this,gi,"m",Z4).call(this))}static accumulateDelta(e,t){for(let[n,i]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=i;continue}let a=e[n];if(a==null){e[n]=i;continue}if(n==="index"||n==="type"){e[n]=i;continue}if(typeof a=="string"&&typeof i=="string")a+=i;else if(typeof a=="number"&&typeof i=="number")a+=i;else if(R4(a)&&R4(i))a=this.accumulateDelta(a,i);else if(Array.isArray(a)&&Array.isArray(i)){if(a.every(s=>typeof s=="string"||typeof s=="number")){a.push(...i);continue}for(let s of i){if(!R4(s))throw new Error(`Expected array delta entry to be an object but got: ${s}`);let o=s.index;if(o==null)throw console.error(s),new Error("Expected array delta entry to have an `index` property");if(typeof o!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${o}`);let c=a[o];c==null?a.push(s):a[o]=this.accumulateDelta(c,s)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${i}, accValue: ${a}`);e[n]=a}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,i){return await this._createAssistantStream(t,e,n,i)}async _runToolAssistantStream(e,t,n,i){return await this._createToolAssistantStream(t,e,n,i)}};k3=Gc,J4=function(e){if(!this.ended)switch(Ze(this,Jx,e,"f"),ae(this,gi,"m",pse).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":ae(this,gi,"m",gse).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":ae(this,gi,"m",fse).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":ae(this,gi,"m",lse).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},Z4=function(){if(this.ended)throw new Me("stream has ended, this shouldn't happen");if(!ae(this,T3,"f"))throw Error("Final run has not been received");return ae(this,T3,"f")},lse=function(e){let[t,n]=ae(this,gi,"m",hse).call(this,e,ae(this,Ys,"f"));Ze(this,Ys,t,"f"),ae(this,Kx,"f")[t.id]=t;for(let i of n){let a=t.content[i.index];a?.type=="text"&&this._emit("textCreated",a.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 i of e.data.delta.content){if(i.type=="text"&&i.text){let a=i.text,s=t.content[i.index];if(s&&s.type=="text")this._emit("textDelta",a,s.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(i.index!=ae(this,yd,"f")){if(ae(this,C3,"f"))switch(ae(this,C3,"f").type){case"text":this._emit("textDone",ae(this,C3,"f").text,ae(this,Ys,"f"));break;case"image_file":this._emit("imageFileDone",ae(this,C3,"f").image_file,ae(this,Ys,"f"));break}Ze(this,yd,i.index,"f")}Ze(this,C3,t.content[i.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(ae(this,yd,"f")!==void 0){let i=e.data.content[ae(this,yd,"f")];if(i)switch(i.type){case"image_file":this._emit("imageFileDone",i.image_file,ae(this,Ys,"f"));break;case"text":this._emit("textDone",i.text,ae(this,Ys,"f"));break}}ae(this,Ys,"f")&&this._emit("messageDone",e.data),Ze(this,Ys,void 0,"f")}},fse=function(e){let t=ae(this,gi,"m",dse).call(this,e);switch(Ze(this,Y4,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let a of n.step_details.tool_calls)a.index==ae(this,Yx,"f")?this._emit("toolCallDelta",a,t.step_details.tool_calls[a.index]):(ae(this,Wa,"f")&&this._emit("toolCallDone",ae(this,Wa,"f")),Ze(this,Yx,a.index,"f"),Ze(this,Wa,t.step_details.tool_calls[a.index],"f"),ae(this,Wa,"f")&&this._emit("toolCallCreated",ae(this,Wa,"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":Ze(this,Y4,void 0,"f"),e.data.step_details.type=="tool_calls"&&ae(this,Wa,"f")&&(this._emit("toolCallDone",ae(this,Wa,"f")),Ze(this,Wa,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},pse=function(e){ae(this,_R,"f").push(e),this._emit("event",e)},dse=function(e){switch(e.event){case"thread.run.step.created":return ae(this,Go,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=ae(this,Go,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let i=k3.accumulateDelta(t,n.delta);ae(this,Go,"f")[e.data.id]=i}return ae(this,Go,"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":ae(this,Go,"f")[e.data.id]=e.data;break}if(ae(this,Go,"f")[e.data.id])return ae(this,Go,"f")[e.data.id];throw new Error("No snapshot available")},hse=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let i=e.data;if(i.delta.content)for(let a of i.delta.content)if(a.index in t.content){let s=t.content[a.index];t.content[a.index]=ae(this,gi,"m",mse).call(this,a,s)}else t.content[a.index]=a,n.push(a);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},mse=function(e,t){return k3.accumulateDelta(t,e)},gse=function(e){switch(Ze(this,Zx,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":Ze(this,T3,e.data,"f"),ae(this,Wa,"f")&&(this._emit("toolCallDone",ae(this,Wa,"f")),Ze(this,Wa,void 0,"f"));break;case"thread.run.cancelling":break}};var D3=class extends xe{constructor(){super(...arguments),this.steps=new bd(this._client)}create(e,t,n){let{include:i,...a}=t;return this._client.post(me`/threads/${e}/runs`,{query:{include:i},body:a,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1})}retrieve(e,t,n){let{thread_id:i}=t;return this._client.get(me`/threads/${i}/runs/${e}`,{...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{thread_id:i,...a}=t;return this._client.post(me`/threads/${i}/runs/${e}`,{body:a,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(me`/threads/${e}/runs`,Ct,{query:t,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,t,n){let{thread_id:i}=t;return this._client.post(me`/threads/${i}/runs/${e}/cancel`,{...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let i=await this.create(e,t,n);return await this.poll(i.id,{thread_id:e},n)}createAndStream(e,t,n){return Gc.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let i=ke([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:a,response:s}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...i}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let o=5e3;if(n?.pollIntervalMs)o=n.pollIntervalMs;else{let c=s.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(o=u)}}await Bo(o);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,t,n){return Gc.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:i,...a}=t;return this._client.post(me`/threads/${i}/runs/${e}/submit_tool_outputs`,{body:a,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,n){let i=await this.submitToolOutputs(e,t,n);return await this.poll(i.id,t,n)}submitToolOutputsStream(e,t,n){return Gc.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};D3.Steps=bd;var Fl=class extends xe{constructor(){super(...arguments),this.runs=new D3(this._client),this.messages=new vd(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(me`/threads/${e}`,{...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(me`/threads/${e}`,{body:t,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t){return this._client.delete(me`/threads/${e}`,{...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return Gc.createThreadAssistantStream(e,this._client.beta.threads,t)}};Fl.Runs=D3;Fl.Messages=vd;var Xs=class extends xe{constructor(){super(...arguments),this.realtime=new Ol(this._client),this.chatkit=new Il(this._client),this.assistants=new pd(this._client),this.threads=new Fl(this._client)}};Xs.Realtime=Ol;Xs.ChatKit=Il;Xs.Assistants=pd;Xs.Threads=Fl;var P3=class extends xe{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};var xd=class extends xe{retrieve(e,t,n){let{container_id:i}=t;return this._client.get(me`/containers/${i}/files/${e}/content`,{...n,headers:ke([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}};var O3=class extends xe{constructor(){super(...arguments),this.content=new xd(this._client)}create(e,t,n){return this._client.post(me`/containers/${e}/files`,Ha({body:t,...n},this._client))}retrieve(e,t,n){let{container_id:i}=t;return this._client.get(me`/containers/${i}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(me`/containers/${e}/files`,Ct,{query:t,...n})}delete(e,t,n){let{container_id:i}=t;return this._client.delete(me`/containers/${i}/files/${e}`,{...n,headers:ke([{Accept:"*/*"},n?.headers])})}};O3.Content=xd;var jl=class extends xe{constructor(){super(...arguments),this.files=new O3(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(me`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",Ct,{query:e,...t})}delete(e,t){return this._client.delete(me`/containers/${e}`,{...t,headers:ke([{Accept:"*/*"},t?.headers])})}};jl.Files=O3;var wd=class extends xe{create(e,t,n){let{include:i,...a}=t;return this._client.post(me`/conversations/${e}/items`,{query:{include:i},body:a,...n})}retrieve(e,t,n){let{conversation_id:i,...a}=t;return this._client.get(me`/conversations/${i}/items/${e}`,{query:a,...n})}list(e,t={},n){return this._client.getAPIList(me`/conversations/${e}/items`,zc,{query:t,...n})}delete(e,t,n){let{conversation_id:i}=t;return this._client.delete(me`/conversations/${i}/items/${e}`,n)}};var Ml=class extends xe{constructor(){super(...arguments),this.items=new wd(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(me`/conversations/${e}`,t)}update(e,t,n){return this._client.post(me`/conversations/${e}`,{body:t,...n})}delete(e,t){return this._client.delete(me`/conversations/${e}`,t)}};Ml.Items=wd;var I3=class extends xe{create(e,t){let n=!!e.encoding_format,i=n?e.encoding_format:"base64";n&&vn(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let a=this._client.post("/embeddings",{body:{...e,encoding_format:i},...t});return n?a:(vn(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(s=>(s&&s.data&&s.data.forEach(o=>{let c=o.embedding;o.embedding=use(c)}),s)))}};var _d=class extends xe{retrieve(e,t,n){let{eval_id:i,run_id:a}=t;return this._client.get(me`/evals/${i}/runs/${a}/output_items/${e}`,n)}list(e,t,n){let{eval_id:i,...a}=t;return this._client.getAPIList(me`/evals/${i}/runs/${e}/output_items`,Ct,{query:a,...n})}};var R3=class extends xe{constructor(){super(...arguments),this.outputItems=new _d(this._client)}create(e,t,n){return this._client.post(me`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){let{eval_id:i}=t;return this._client.get(me`/evals/${i}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(me`/evals/${e}/runs`,Ct,{query:t,...n})}delete(e,t,n){let{eval_id:i}=t;return this._client.delete(me`/evals/${i}/runs/${e}`,n)}cancel(e,t,n){let{eval_id:i}=t;return this._client.post(me`/evals/${i}/runs/${e}`,n)}};R3.OutputItems=_d;var Nl=class extends xe{constructor(){super(...arguments),this.runs=new R3(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(me`/evals/${e}`,t)}update(e,t,n){return this._client.post(me`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/evals",Ct,{query:e,...t})}delete(e,t){return this._client.delete(me`/evals/${e}`,t)}};Nl.Runs=R3;var F3=class extends xe{create(e,t){return this._client.post("/files",Ha({body:e,...t},this._client))}retrieve(e,t){return this._client.get(me`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",Ct,{query:e,...t})}delete(e,t){return this._client.delete(me`/files/${e}`,t)}content(e,t){return this._client.get(me`/files/${e}/content`,{...t,headers:ke([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){let i=new Set(["processed","error","deleted"]),a=Date.now(),s=await this.retrieve(e);for(;!s.status||!i.has(s.status);)if(await Bo(t),s=await this.retrieve(e),Date.now()-a>n)throw new Cl({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return s}};var Sd=class extends xe{};var Ed=class extends xe{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};var j3=class extends xe{constructor(){super(...arguments),this.graders=new Ed(this._client)}};j3.Graders=Ed;var Ad=class extends xe{create(e,t,n){return this._client.getAPIList(me`/fine_tuning/checkpoints/${e}/permissions`,Ho,{body:t,method:"post",...n})}retrieve(e,t={},n){return this._client.get(me`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}delete(e,t,n){let{fine_tuned_model_checkpoint:i}=t;return this._client.delete(me`/fine_tuning/checkpoints/${i}/permissions/${e}`,n)}};var M3=class extends xe{constructor(){super(...arguments),this.permissions=new Ad(this._client)}};M3.Permissions=Ad;var Cd=class extends xe{list(e,t={},n){return this._client.getAPIList(me`/fine_tuning/jobs/${e}/checkpoints`,Ct,{query:t,...n})}};var N3=class extends xe{constructor(){super(...arguments),this.checkpoints=new Cd(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(me`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",Ct,{query:e,...t})}cancel(e,t){return this._client.post(me`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(me`/fine_tuning/jobs/${e}/events`,Ct,{query:t,...n})}pause(e,t){return this._client.post(me`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(me`/fine_tuning/jobs/${e}/resume`,t)}};N3.Checkpoints=Cd;var Qs=class extends xe{constructor(){super(...arguments),this.methods=new Sd(this._client),this.jobs=new N3(this._client),this.checkpoints=new M3(this._client),this.alpha=new j3(this._client)}};Qs.Methods=Sd;Qs.Jobs=N3;Qs.Checkpoints=M3;Qs.Alpha=j3;var kd=class extends xe{};var ql=class extends xe{constructor(){super(...arguments),this.graderModels=new kd(this._client)}};ql.GraderModels=kd;var q3=class extends xe{createVariation(e,t){return this._client.post("/images/variations",Ha({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",Ha({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}};var $3=class extends xe{retrieve(e,t){return this._client.get(me`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Ho,e)}delete(e,t){return this._client.delete(me`/models/${e}`,t)}};var L3=class extends xe{create(e,t){return this._client.post("/moderations",{body:e,...t})}};var Td=class extends xe{accept(e,t,n){return this._client.post(me`/realtime/calls/${e}/accept`,{body:t,...n,headers:ke([{Accept:"*/*"},n?.headers])})}hangup(e,t){return this._client.post(me`/realtime/calls/${e}/hangup`,{...t,headers:ke([{Accept:"*/*"},t?.headers])})}refer(e,t,n){return this._client.post(me`/realtime/calls/${e}/refer`,{body:t,...n,headers:ke([{Accept:"*/*"},n?.headers])})}reject(e,t={},n){return this._client.post(me`/realtime/calls/${e}/reject`,{body:t,...n,headers:ke([{Accept:"*/*"},n?.headers])})}};var Dd=class extends xe{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}};var Vc=class extends xe{constructor(){super(...arguments),this.clientSecrets=new Dd(this._client),this.calls=new Td(this._client)}};Vc.ClientSecrets=Dd;Vc.Calls=Td;function vse(r,e){return!e||!xXe(e)?{...r,output_parsed:null,output:r.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(n=>({...n,parsed:null}))}:t)}:SR(r,e)}function SR(r,e){let t=r.output.map(i=>{if(i.type==="function_call")return{...i,parsed_arguments:SXe(e,i)};if(i.type==="message"){let a=i.content.map(s=>s.type==="output_text"?{...s,parsed:yXe(e,s.text)}:s);return{...i,content:a}}return i}),n=Object.assign({},r,{output:t});return Object.getOwnPropertyDescriptor(r,"output_text")||Xx(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let i of n.output)if(i.type==="message"){for(let a of i.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function yXe(r,e){return r.text?.format?.type!=="json_schema"?null:"$parseRaw"in r.text?.format?(r.text?.format).$parseRaw(e):JSON.parse(e)}function xXe(r){return!!B4(r.text?.format)}function wXe(r){return r?.$brand==="auto-parseable-tool"}function _Xe(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function SXe(r,e){let t=_Xe(r.tools??[],e.name);return{...e,...e,parsed_arguments:wXe(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Xx(r){let e=[];for(let t of r.output)if(t.type==="message")for(let n of t.content)n.type==="output_text"&&e.push(n.text);r.output_text=e.join("")}var Pd,Qx,$l,ew,bse,yse,xse,wse,tw=class r extends Tl{constructor(e){super(),Pd.add(this),Qx.set(this,void 0),$l.set(this,void 0),ew.set(this,void 0),Ze(this,Qx,e,"f")}static createResponse(e,t,n){let i=new r(t);return i._run(()=>i._createOrRetrieveResponse(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createOrRetrieveResponse(e,t,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),ae(this,Pd,"m",bse).call(this);let a,s=null;"response_id"in t?(a=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),s=t.starting_after??null):a=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let o of a)ae(this,Pd,"m",yse).call(this,o,s);if(a.controller.signal?.aborted)throw new kn;return ae(this,Pd,"m",xse).call(this)}[(Qx=new WeakMap,$l=new WeakMap,ew=new WeakMap,Pd=new WeakSet,bse=function(){this.ended||Ze(this,$l,void 0,"f")},yse=function(t,n){if(this.ended)return;let i=(s,o)=>{(n==null||o.sequence_number>n)&&this._emit(s,o)},a=ae(this,Pd,"m",wse).call(this,t);switch(i("event",t),t.type){case"response.output_text.delta":{let s=a.output[t.output_index];if(!s)throw new Me(`missing output at index ${t.output_index}`);if(s.type==="message"){let o=s.content[t.content_index];if(!o)throw new Me(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new Me(`expected content to be 'output_text', got ${o.type}`);i("response.output_text.delta",{...t,snapshot:o.text})}break}case"response.function_call_arguments.delta":{let s=a.output[t.output_index];if(!s)throw new Me(`missing output at index ${t.output_index}`);s.type==="function_call"&&i("response.function_call_arguments.delta",{...t,snapshot:s.arguments});break}default:i(t.type,t);break}},xse=function(){if(this.ended)throw new Me("stream has ended, this shouldn't happen");let t=ae(this,$l,"f");if(!t)throw new Me("request ended without sending any events");Ze(this,$l,void 0,"f");let n=EXe(t,ae(this,Qx,"f"));return Ze(this,ew,n,"f"),n},wse=function(t){let n=ae(this,$l,"f");if(!n){if(t.type!=="response.created")throw new Me(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return n=Ze(this,$l,t.response,"f"),n}switch(t.type){case"response.output_item.added":{n.output.push(t.item);break}case"response.content_part.added":{let i=n.output[t.output_index];if(!i)throw new Me(`missing output at index ${t.output_index}`);let a=i.type,s=t.part;a==="message"&&s.type!=="reasoning_text"?i.content.push(s):a==="reasoning"&&s.type==="reasoning_text"&&(i.content||(i.content=[]),i.content.push(s));break}case"response.output_text.delta":{let i=n.output[t.output_index];if(!i)throw new Me(`missing output at index ${t.output_index}`);if(i.type==="message"){let a=i.content[t.content_index];if(!a)throw new Me(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new Me(`expected content to be 'output_text', got ${a.type}`);a.text+=t.delta}break}case"response.function_call_arguments.delta":{let i=n.output[t.output_index];if(!i)throw new Me(`missing output at index ${t.output_index}`);i.type==="function_call"&&(i.arguments+=t.delta);break}case"response.reasoning_text.delta":{let i=n.output[t.output_index];if(!i)throw new Me(`missing output at index ${t.output_index}`);if(i.type==="reasoning"){let a=i.content?.[t.content_index];if(!a)throw new Me(`missing content at index ${t.content_index}`);if(a.type!=="reasoning_text")throw new Me(`expected content to be 'reasoning_text', got ${a.type}`);a.text+=t.delta}break}case"response.completed":{Ze(this,$l,t.response,"f");break}}return n},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("event",i=>{let a=t.shift();a?a.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{n=!0;for(let a of t)a.reject(i);t.length=0}),this.on("error",i=>{n=!0;for(let a of t)a.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,s)=>t.push({resolve:a,reject:s})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=ae(this,ew,"f");if(!e)throw new Me("stream ended without producing a ChatCompletion");return e}};function EXe(r,e){return vse(r,e)}var Od=class extends xe{list(e,t={},n){return this._client.getAPIList(me`/responses/${e}/input_items`,Ct,{query:t,...n})}};var Id=class extends xe{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}};var Kc=class extends xe{constructor(){super(...arguments),this.inputItems=new Od(this._client),this.inputTokens=new Id(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&Xx(n),n))}retrieve(e,t={},n){return this._client.get(me`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})._thenUnwrap(i=>("object"in i&&i.object==="response"&&Xx(i),i))}delete(e,t){return this._client.delete(me`/responses/${e}`,{...t,headers:ke([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(n=>SR(n,e))}stream(e,t){return tw.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(me`/responses/${e}/cancel`,t)}compact(e={},t){return this._client.post("/responses/compact",{body:e,...t})}};Kc.InputItems=Od;Kc.InputTokens=Id;var Rd=class extends xe{create(e,t,n){return this._client.post(me`/uploads/${e}/parts`,Ha({body:t,...n},this._client))}};var Ll=class extends xe{constructor(){super(...arguments),this.parts=new Rd(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(me`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(me`/uploads/${e}/complete`,{body:t,...n})}};Ll.Parts=Rd;var _se=async r=>{let e=await Promise.allSettled(r),t=e.filter(i=>i.status==="rejected");if(t.length){for(let i of t)console.error(i.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let n=[];for(let i of e)i.status==="fulfilled"&&n.push(i.value);return n};var Fd=class extends xe{create(e,t,n){return this._client.post(me`/vector_stores/${e}/file_batches`,{body:t,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{vector_store_id:i}=t;return this._client.get(me`/vector_stores/${i}/file_batches/${e}`,{...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,t,n){let{vector_store_id:i}=t;return this._client.post(me`/vector_stores/${i}/file_batches/${e}/cancel`,{...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let i=await this.create(e,t);return await this.poll(e,i.id,n)}listFiles(e,t,n){let{vector_store_id:i,...a}=t;return this._client.getAPIList(me`/vector_stores/${i}/file_batches/${e}/files`,Ct,{query:a,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async poll(e,t,n){let i=ke([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:a,response:s}=await this.retrieve(t,{vector_store_id:e},{...n,headers:i}).withResponse();switch(a.status){case"in_progress":let o=5e3;if(n?.pollIntervalMs)o=n.pollIntervalMs;else{let c=s.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(o=u)}}await Bo(o);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},i){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 a=i?.maxConcurrency??5,s=Math.min(a,t.length),o=this._client,c=t.values(),u=[...n];async function l(p){for(let d of p){let m=await o.files.create({file:d,purpose:"assistants"},i);u.push(m.id)}}let f=Array(s).fill(c).map(l);return await _se(f),await this.createAndPoll(e,{file_ids:u})}};var jd=class extends xe{create(e,t,n){return this._client.post(me`/vector_stores/${e}/files`,{body:t,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{vector_store_id:i}=t;return this._client.get(me`/vector_stores/${i}/files/${e}`,{...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{vector_store_id:i,...a}=t;return this._client.post(me`/vector_stores/${i}/files/${e}`,{body:a,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(me`/vector_stores/${e}/files`,Ct,{query:t,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t,n){let{vector_store_id:i}=t;return this._client.delete(me`/vector_stores/${i}/files/${e}`,{...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let i=await this.create(e,t,n);return await this.poll(e,i.id,n)}async poll(e,t,n){let i=ke([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let a=await this.retrieve(t,{vector_store_id:e},{...n,headers:i}).withResponse(),s=a.data;switch(s.status){case"in_progress":let o=5e3;if(n?.pollIntervalMs)o=n.pollIntervalMs;else{let c=a.response.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(o=u)}}await Bo(o);break;case"failed":case"completed":return s}}}async upload(e,t,n){let i=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:i.id},n)}async uploadAndPoll(e,t,n){let i=await this.upload(e,t,n);return await this.poll(e,i.id,n)}content(e,t,n){let{vector_store_id:i}=t;return this._client.getAPIList(me`/vector_stores/${i}/files/${e}/content`,Ho,{...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var Jc=class extends xe{constructor(){super(...arguments),this.files=new jd(this._client),this.fileBatches=new Fd(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(me`/vector_stores/${e}`,{...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(me`/vector_stores/${e}`,{body:t,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",Ct,{query:e,...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(me`/vector_stores/${e}`,{...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,n){return this._client.getAPIList(me`/vector_stores/${e}/search`,Ho,{body:t,method:"post",...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};Jc.Files=jd;Jc.FileBatches=Fd;var B3=class extends xe{create(e,t){return this._client.post("/videos",aR({body:e,...t},this._client))}retrieve(e,t){return this._client.get(me`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",zc,{query:e,...t})}delete(e,t){return this._client.delete(me`/videos/${e}`,t)}downloadContent(e,t={},n){return this._client.get(me`/videos/${e}/content`,{query:t,...n,headers:ke([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}remix(e,t,n){return this._client.post(me`/videos/${e}/remix`,aR({body:t,...n},this._client))}};var Md,Sse,rw,z3=class extends xe{constructor(){super(...arguments),Md.add(this)}async unwrap(e,t,n=this._client.webhookSecret,i=300){return await this.verifySignature(e,t,n,i),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,i=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");ae(this,Md,"m",Sse).call(this,n);let a=ke([t]).values,s=ae(this,Md,"m",rw).call(this,a,"webhook-signature"),o=ae(this,Md,"m",rw).call(this,a,"webhook-timestamp"),c=ae(this,Md,"m",rw).call(this,a,"webhook-id"),u=parseInt(o,10);if(isNaN(u))throw new Lo("Invalid webhook timestamp format");let l=Math.floor(Date.now()/1e3);if(l-u>i)throw new Lo("Webhook timestamp is too old");if(u>l+i)throw new Lo("Webhook timestamp is too new");let f=s.split(" ").map(h=>h.startsWith("v1,")?h.substring(3):h),p=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),d=c?`${c}.${o}.${e}`:`${o}.${e}`,m=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let h of f)try{let g=Buffer.from(h,"base64");if(await crypto.subtle.verify("HMAC",m,g,new TextEncoder().encode(d)))return}catch{continue}throw new Lo("The given webhook signature does not match the expected signature")}};Md=new WeakSet,Sse=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")},rw=function(e,t){if(!e)throw new Error("Headers are required");let n=e.get(t);if(n==null)throw new Error(`Missing required header: ${t}`);return n};var ER,AR,nw,Ese,gt=class{constructor({baseURL:e=Rl("OPENAI_BASE_URL"),apiKey:t=Rl("OPENAI_API_KEY"),organization:n=Rl("OPENAI_ORG_ID")??null,project:i=Rl("OPENAI_PROJECT_ID")??null,webhookSecret:a=Rl("OPENAI_WEBHOOK_SECRET")??null,...s}={}){if(ER.add(this),nw.set(this,void 0),this.completions=new P3(this),this.chat=new Pl(this),this.embeddings=new I3(this),this.files=new F3(this),this.images=new q3(this),this.audio=new Wo(this),this.moderations=new L3(this),this.models=new $3(this),this.fineTuning=new Qs(this),this.graders=new ql(this),this.vectorStores=new Jc(this),this.webhooks=new z3(this),this.beta=new Xs(this),this.batches=new A3(this),this.uploads=new Ll(this),this.responses=new Kc(this),this.realtime=new Vc(this),this.conversations=new Ml(this),this.evals=new Nl(this),this.containers=new jl(this),this.videos=new B3(this),t===void 0)throw new Me("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let o={apiKey:t,organization:n,project:i,webhookSecret:a,...s,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&Oae())throw new Me(`It looks like you're running in a browser-like environment.
|
|
997
|
+
${Vx(r)}`);return{...I,id:R,type:A,function:{...y,name:_,arguments:w}}})}}:{...d,message:{...v,content:m,role:b,refusal:u.refusal??null},finish_reason:l,index:f,logprobs:p}}),created:i,model:a,object:"chat.completion",...s?{system_fingerprint:s}:{}};return Qae(c,e)}function Vx(r){return JSON.stringify(r)}var K4=class r extends E3{static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,n){let i=new r(t),a={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(e,t,a)),i}};var Wc=class extends xe{constructor(){super(...arguments),this.messages=new _3(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(me`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(me`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/chat/completions",Ct,{query:e,...t})}delete(e,t){return this._client.delete(me`/chat/completions/${e}`,t)}parse(e,t){return rse(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>z4(n,e))}runTools(e,t){return e.stream?K4.runTools(this._client,e,t):V4.runTools(this._client,e,t)}stream(e,t){return E3.createChatCompletion(this._client,e,t)}};Wc.Messages=_3;var Pl=class extends xe{constructor(){super(...arguments),this.completions=new Wc(this._client)}};Pl.Completions=Wc;var cse=Symbol("brand.privateNullableHeaders");function*UYe(r){if(!r)return;if(cse in r){let{values:n,nulls:i}=r;yield*n.entries();for(let a of i)yield[a,null];return}let e=!1,t;r instanceof Headers?t=r.entries():zI(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let n of t){let i=n[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let a=zI(n[1])?n[1]:[n[1]],s=!1;for(let o of a)o!==void 0&&(e&&!s&&(s=!0,yield[i,null]),yield[i,o])}}var ke=r=>{let e=new Headers,t=new Set;for(let n of r){let i=new Set;for(let[a,s]of UYe(n)){let o=a.toLowerCase();i.has(o)||(e.delete(a),i.add(o)),s===null?(e.delete(a),t.add(o)):(e.append(a,s),t.delete(o))}}return{[cse]:!0,values:e,nulls:t}};var ud=class extends xe{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:ke([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};var ld=class extends xe{create(e,t){return this._client.post("/audio/transcriptions",Ha({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};var fd=class extends xe{create(e,t){return this._client.post("/audio/translations",Ha({body:e,...t,__metadata:{model:e.model}},this._client))}};var Wo=class extends xe{constructor(){super(...arguments),this.transcriptions=new ld(this._client),this.translations=new fd(this._client),this.speech=new ud(this._client)}};Wo.Transcriptions=ld;Wo.Translations=fd;Wo.Speech=ud;var A3=class extends xe{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(me`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",Ct,{query:e,...t})}cancel(e,t){return this._client.post(me`/batches/${e}/cancel`,t)}};var pd=class extends xe{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(me`/assistants/${e}`,{...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(me`/assistants/${e}`,{body:t,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",Ct,{query:e,...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(me`/assistants/${e}`,{...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var dd=class extends xe{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var hd=class extends xe{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var Ol=class extends xe{constructor(){super(...arguments),this.sessions=new dd(this._client),this.transcriptionSessions=new hd(this._client)}};Ol.Sessions=dd;Ol.TranscriptionSessions=hd;var md=class extends xe{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:ke([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(me`/chatkit/sessions/${e}/cancel`,{...t,headers:ke([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}};var gd=class extends xe{retrieve(e,t){return this._client.get(me`/chatkit/threads/${e}`,{...t,headers:ke([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",zc,{query:e,...t,headers:ke([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(me`/chatkit/threads/${e}`,{...t,headers:ke([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},n){return this._client.getAPIList(me`/chatkit/threads/${e}/items`,zc,{query:t,...n,headers:ke([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}};var Il=class extends xe{constructor(){super(...arguments),this.sessions=new md(this._client),this.threads=new gd(this._client)}};Il.Sessions=md;Il.Threads=gd;var vd=class extends xe{create(e,t,n){return this._client.post(me`/threads/${e}/messages`,{body:t,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{thread_id:i}=t;return this._client.get(me`/threads/${i}/messages/${e}`,{...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{thread_id:i,...a}=t;return this._client.post(me`/threads/${i}/messages/${e}`,{body:a,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(me`/threads/${e}/messages`,Ct,{query:t,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t,n){let{thread_id:i}=t;return this._client.delete(me`/threads/${i}/messages/${e}`,{...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var bd=class extends xe{retrieve(e,t,n){let{thread_id:i,run_id:a,...s}=t;return this._client.get(me`/threads/${i}/runs/${a}/steps/${e}`,{query:s,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t,n){let{thread_id:i,...a}=t;return this._client.getAPIList(me`/threads/${i}/runs/${e}/steps`,Ct,{query:a,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var use=r=>{if(typeof Buffer<"u"){let e=Buffer.from(r,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(r),t=e.length,n=new Uint8Array(t);for(let i=0;i<t;i++)n[i]=e.charCodeAt(i);return Array.from(new Float32Array(n.buffer))}};var Rl=r=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()};var gi,k3,_R,Go,Kx,Ys,T3,yd,C3,Yx,Wa,Jx,Zx,Y4,J4,Z4,lse,fse,pse,dse,hse,mse,gse,Gc=class extends Tl{constructor(){super(...arguments),gi.add(this),_R.set(this,[]),Go.set(this,{}),Kx.set(this,{}),Ys.set(this,void 0),T3.set(this,void 0),yd.set(this,void 0),C3.set(this,void 0),Yx.set(this,void 0),Wa.set(this,void 0),Jx.set(this,void 0),Zx.set(this,void 0),Y4.set(this,void 0)}[(_R=new WeakMap,Go=new WeakMap,Kx=new WeakMap,Ys=new WeakMap,T3=new WeakMap,yd=new WeakMap,C3=new WeakMap,Yx=new WeakMap,Wa=new WeakMap,Jx=new WeakMap,Zx=new WeakMap,Y4=new WeakMap,gi=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("event",i=>{let a=t.shift();a?a.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{n=!0;for(let a of t)a.reject(i);t.length=0}),this.on("error",i=>{n=!0;for(let a of t)a.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,s)=>t.push({resolve:a,reject:s})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new k3;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let i=Uo.fromReadableStream(e,this.controller);for await(let a of i)ae(this,gi,"m",J4).call(this,a);if(i.controller.signal?.aborted)throw new kn;return this._addRun(ae(this,gi,"m",Z4).call(this))}toReadableStream(){return new Uo(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,i){let a=new k3;return a._run(()=>a._runToolAssistantStream(e,t,n,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,t,n,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));let s={...n,stream:!0},o=await e.submitToolOutputs(t,s,{...i,signal:this.controller.signal});this._connected();for await(let c of o)ae(this,gi,"m",J4).call(this,c);if(o.controller.signal?.aborted)throw new kn;return this._addRun(ae(this,gi,"m",Z4).call(this))}static createThreadAssistantStream(e,t,n){let i=new k3;return i._run(()=>i._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}static createAssistantStream(e,t,n,i){let a=new k3;return a._run(()=>a._runAssistantStream(e,t,n,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return ae(this,Jx,"f")}currentRun(){return ae(this,Zx,"f")}currentMessageSnapshot(){return ae(this,Ys,"f")}currentRunStepSnapshot(){return ae(this,Y4,"f")}async finalRunSteps(){return await this.done(),Object.values(ae(this,Go,"f"))}async finalMessages(){return await this.done(),Object.values(ae(this,Kx,"f"))}async finalRun(){if(await this.done(),!ae(this,T3,"f"))throw Error("Final run was not received.");return ae(this,T3,"f")}async _createThreadAssistantStream(e,t,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let a={...t,stream:!0},s=await e.createAndRun(a,{...n,signal:this.controller.signal});this._connected();for await(let o of s)ae(this,gi,"m",J4).call(this,o);if(s.controller.signal?.aborted)throw new kn;return this._addRun(ae(this,gi,"m",Z4).call(this))}async _createAssistantStream(e,t,n,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));let s={...n,stream:!0},o=await e.create(t,s,{...i,signal:this.controller.signal});this._connected();for await(let c of o)ae(this,gi,"m",J4).call(this,c);if(o.controller.signal?.aborted)throw new kn;return this._addRun(ae(this,gi,"m",Z4).call(this))}static accumulateDelta(e,t){for(let[n,i]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=i;continue}let a=e[n];if(a==null){e[n]=i;continue}if(n==="index"||n==="type"){e[n]=i;continue}if(typeof a=="string"&&typeof i=="string")a+=i;else if(typeof a=="number"&&typeof i=="number")a+=i;else if(R4(a)&&R4(i))a=this.accumulateDelta(a,i);else if(Array.isArray(a)&&Array.isArray(i)){if(a.every(s=>typeof s=="string"||typeof s=="number")){a.push(...i);continue}for(let s of i){if(!R4(s))throw new Error(`Expected array delta entry to be an object but got: ${s}`);let o=s.index;if(o==null)throw console.error(s),new Error("Expected array delta entry to have an `index` property");if(typeof o!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${o}`);let c=a[o];c==null?a.push(s):a[o]=this.accumulateDelta(c,s)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${i}, accValue: ${a}`);e[n]=a}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,i){return await this._createAssistantStream(t,e,n,i)}async _runToolAssistantStream(e,t,n,i){return await this._createToolAssistantStream(t,e,n,i)}};k3=Gc,J4=function(e){if(!this.ended)switch(Ze(this,Jx,e,"f"),ae(this,gi,"m",pse).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":ae(this,gi,"m",gse).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":ae(this,gi,"m",fse).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":ae(this,gi,"m",lse).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},Z4=function(){if(this.ended)throw new Me("stream has ended, this shouldn't happen");if(!ae(this,T3,"f"))throw Error("Final run has not been received");return ae(this,T3,"f")},lse=function(e){let[t,n]=ae(this,gi,"m",hse).call(this,e,ae(this,Ys,"f"));Ze(this,Ys,t,"f"),ae(this,Kx,"f")[t.id]=t;for(let i of n){let a=t.content[i.index];a?.type=="text"&&this._emit("textCreated",a.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 i of e.data.delta.content){if(i.type=="text"&&i.text){let a=i.text,s=t.content[i.index];if(s&&s.type=="text")this._emit("textDelta",a,s.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(i.index!=ae(this,yd,"f")){if(ae(this,C3,"f"))switch(ae(this,C3,"f").type){case"text":this._emit("textDone",ae(this,C3,"f").text,ae(this,Ys,"f"));break;case"image_file":this._emit("imageFileDone",ae(this,C3,"f").image_file,ae(this,Ys,"f"));break}Ze(this,yd,i.index,"f")}Ze(this,C3,t.content[i.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(ae(this,yd,"f")!==void 0){let i=e.data.content[ae(this,yd,"f")];if(i)switch(i.type){case"image_file":this._emit("imageFileDone",i.image_file,ae(this,Ys,"f"));break;case"text":this._emit("textDone",i.text,ae(this,Ys,"f"));break}}ae(this,Ys,"f")&&this._emit("messageDone",e.data),Ze(this,Ys,void 0,"f")}},fse=function(e){let t=ae(this,gi,"m",dse).call(this,e);switch(Ze(this,Y4,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let a of n.step_details.tool_calls)a.index==ae(this,Yx,"f")?this._emit("toolCallDelta",a,t.step_details.tool_calls[a.index]):(ae(this,Wa,"f")&&this._emit("toolCallDone",ae(this,Wa,"f")),Ze(this,Yx,a.index,"f"),Ze(this,Wa,t.step_details.tool_calls[a.index],"f"),ae(this,Wa,"f")&&this._emit("toolCallCreated",ae(this,Wa,"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":Ze(this,Y4,void 0,"f"),e.data.step_details.type=="tool_calls"&&ae(this,Wa,"f")&&(this._emit("toolCallDone",ae(this,Wa,"f")),Ze(this,Wa,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},pse=function(e){ae(this,_R,"f").push(e),this._emit("event",e)},dse=function(e){switch(e.event){case"thread.run.step.created":return ae(this,Go,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=ae(this,Go,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let i=k3.accumulateDelta(t,n.delta);ae(this,Go,"f")[e.data.id]=i}return ae(this,Go,"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":ae(this,Go,"f")[e.data.id]=e.data;break}if(ae(this,Go,"f")[e.data.id])return ae(this,Go,"f")[e.data.id];throw new Error("No snapshot available")},hse=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let i=e.data;if(i.delta.content)for(let a of i.delta.content)if(a.index in t.content){let s=t.content[a.index];t.content[a.index]=ae(this,gi,"m",mse).call(this,a,s)}else t.content[a.index]=a,n.push(a);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},mse=function(e,t){return k3.accumulateDelta(t,e)},gse=function(e){switch(Ze(this,Zx,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":Ze(this,T3,e.data,"f"),ae(this,Wa,"f")&&(this._emit("toolCallDone",ae(this,Wa,"f")),Ze(this,Wa,void 0,"f"));break;case"thread.run.cancelling":break}};var D3=class extends xe{constructor(){super(...arguments),this.steps=new bd(this._client)}create(e,t,n){let{include:i,...a}=t;return this._client.post(me`/threads/${e}/runs`,{query:{include:i},body:a,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1})}retrieve(e,t,n){let{thread_id:i}=t;return this._client.get(me`/threads/${i}/runs/${e}`,{...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{thread_id:i,...a}=t;return this._client.post(me`/threads/${i}/runs/${e}`,{body:a,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(me`/threads/${e}/runs`,Ct,{query:t,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,t,n){let{thread_id:i}=t;return this._client.post(me`/threads/${i}/runs/${e}/cancel`,{...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let i=await this.create(e,t,n);return await this.poll(i.id,{thread_id:e},n)}createAndStream(e,t,n){return Gc.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let i=ke([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:a,response:s}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...i}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let o=5e3;if(n?.pollIntervalMs)o=n.pollIntervalMs;else{let c=s.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(o=u)}}await Bo(o);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,t,n){return Gc.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:i,...a}=t;return this._client.post(me`/threads/${i}/runs/${e}/submit_tool_outputs`,{body:a,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,n){let i=await this.submitToolOutputs(e,t,n);return await this.poll(i.id,t,n)}submitToolOutputsStream(e,t,n){return Gc.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};D3.Steps=bd;var Fl=class extends xe{constructor(){super(...arguments),this.runs=new D3(this._client),this.messages=new vd(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(me`/threads/${e}`,{...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(me`/threads/${e}`,{body:t,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t){return this._client.delete(me`/threads/${e}`,{...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return Gc.createThreadAssistantStream(e,this._client.beta.threads,t)}};Fl.Runs=D3;Fl.Messages=vd;var Xs=class extends xe{constructor(){super(...arguments),this.realtime=new Ol(this._client),this.chatkit=new Il(this._client),this.assistants=new pd(this._client),this.threads=new Fl(this._client)}};Xs.Realtime=Ol;Xs.ChatKit=Il;Xs.Assistants=pd;Xs.Threads=Fl;var P3=class extends xe{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};var xd=class extends xe{retrieve(e,t,n){let{container_id:i}=t;return this._client.get(me`/containers/${i}/files/${e}/content`,{...n,headers:ke([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}};var O3=class extends xe{constructor(){super(...arguments),this.content=new xd(this._client)}create(e,t,n){return this._client.post(me`/containers/${e}/files`,Ha({body:t,...n},this._client))}retrieve(e,t,n){let{container_id:i}=t;return this._client.get(me`/containers/${i}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(me`/containers/${e}/files`,Ct,{query:t,...n})}delete(e,t,n){let{container_id:i}=t;return this._client.delete(me`/containers/${i}/files/${e}`,{...n,headers:ke([{Accept:"*/*"},n?.headers])})}};O3.Content=xd;var jl=class extends xe{constructor(){super(...arguments),this.files=new O3(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(me`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",Ct,{query:e,...t})}delete(e,t){return this._client.delete(me`/containers/${e}`,{...t,headers:ke([{Accept:"*/*"},t?.headers])})}};jl.Files=O3;var wd=class extends xe{create(e,t,n){let{include:i,...a}=t;return this._client.post(me`/conversations/${e}/items`,{query:{include:i},body:a,...n})}retrieve(e,t,n){let{conversation_id:i,...a}=t;return this._client.get(me`/conversations/${i}/items/${e}`,{query:a,...n})}list(e,t={},n){return this._client.getAPIList(me`/conversations/${e}/items`,zc,{query:t,...n})}delete(e,t,n){let{conversation_id:i}=t;return this._client.delete(me`/conversations/${i}/items/${e}`,n)}};var Ml=class extends xe{constructor(){super(...arguments),this.items=new wd(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(me`/conversations/${e}`,t)}update(e,t,n){return this._client.post(me`/conversations/${e}`,{body:t,...n})}delete(e,t){return this._client.delete(me`/conversations/${e}`,t)}};Ml.Items=wd;var I3=class extends xe{create(e,t){let n=!!e.encoding_format,i=n?e.encoding_format:"base64";n&&vn(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let a=this._client.post("/embeddings",{body:{...e,encoding_format:i},...t});return n?a:(vn(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(s=>(s&&s.data&&s.data.forEach(o=>{let c=o.embedding;o.embedding=use(c)}),s)))}};var _d=class extends xe{retrieve(e,t,n){let{eval_id:i,run_id:a}=t;return this._client.get(me`/evals/${i}/runs/${a}/output_items/${e}`,n)}list(e,t,n){let{eval_id:i,...a}=t;return this._client.getAPIList(me`/evals/${i}/runs/${e}/output_items`,Ct,{query:a,...n})}};var R3=class extends xe{constructor(){super(...arguments),this.outputItems=new _d(this._client)}create(e,t,n){return this._client.post(me`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){let{eval_id:i}=t;return this._client.get(me`/evals/${i}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(me`/evals/${e}/runs`,Ct,{query:t,...n})}delete(e,t,n){let{eval_id:i}=t;return this._client.delete(me`/evals/${i}/runs/${e}`,n)}cancel(e,t,n){let{eval_id:i}=t;return this._client.post(me`/evals/${i}/runs/${e}`,n)}};R3.OutputItems=_d;var Nl=class extends xe{constructor(){super(...arguments),this.runs=new R3(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(me`/evals/${e}`,t)}update(e,t,n){return this._client.post(me`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/evals",Ct,{query:e,...t})}delete(e,t){return this._client.delete(me`/evals/${e}`,t)}};Nl.Runs=R3;var F3=class extends xe{create(e,t){return this._client.post("/files",Ha({body:e,...t},this._client))}retrieve(e,t){return this._client.get(me`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",Ct,{query:e,...t})}delete(e,t){return this._client.delete(me`/files/${e}`,t)}content(e,t){return this._client.get(me`/files/${e}/content`,{...t,headers:ke([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){let i=new Set(["processed","error","deleted"]),a=Date.now(),s=await this.retrieve(e);for(;!s.status||!i.has(s.status);)if(await Bo(t),s=await this.retrieve(e),Date.now()-a>n)throw new Cl({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return s}};var Sd=class extends xe{};var Ed=class extends xe{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};var j3=class extends xe{constructor(){super(...arguments),this.graders=new Ed(this._client)}};j3.Graders=Ed;var Ad=class extends xe{create(e,t,n){return this._client.getAPIList(me`/fine_tuning/checkpoints/${e}/permissions`,Ho,{body:t,method:"post",...n})}retrieve(e,t={},n){return this._client.get(me`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}delete(e,t,n){let{fine_tuned_model_checkpoint:i}=t;return this._client.delete(me`/fine_tuning/checkpoints/${i}/permissions/${e}`,n)}};var M3=class extends xe{constructor(){super(...arguments),this.permissions=new Ad(this._client)}};M3.Permissions=Ad;var Cd=class extends xe{list(e,t={},n){return this._client.getAPIList(me`/fine_tuning/jobs/${e}/checkpoints`,Ct,{query:t,...n})}};var N3=class extends xe{constructor(){super(...arguments),this.checkpoints=new Cd(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(me`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",Ct,{query:e,...t})}cancel(e,t){return this._client.post(me`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(me`/fine_tuning/jobs/${e}/events`,Ct,{query:t,...n})}pause(e,t){return this._client.post(me`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(me`/fine_tuning/jobs/${e}/resume`,t)}};N3.Checkpoints=Cd;var Qs=class extends xe{constructor(){super(...arguments),this.methods=new Sd(this._client),this.jobs=new N3(this._client),this.checkpoints=new M3(this._client),this.alpha=new j3(this._client)}};Qs.Methods=Sd;Qs.Jobs=N3;Qs.Checkpoints=M3;Qs.Alpha=j3;var kd=class extends xe{};var ql=class extends xe{constructor(){super(...arguments),this.graderModels=new kd(this._client)}};ql.GraderModels=kd;var q3=class extends xe{createVariation(e,t){return this._client.post("/images/variations",Ha({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",Ha({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}};var $3=class extends xe{retrieve(e,t){return this._client.get(me`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Ho,e)}delete(e,t){return this._client.delete(me`/models/${e}`,t)}};var L3=class extends xe{create(e,t){return this._client.post("/moderations",{body:e,...t})}};var Td=class extends xe{accept(e,t,n){return this._client.post(me`/realtime/calls/${e}/accept`,{body:t,...n,headers:ke([{Accept:"*/*"},n?.headers])})}hangup(e,t){return this._client.post(me`/realtime/calls/${e}/hangup`,{...t,headers:ke([{Accept:"*/*"},t?.headers])})}refer(e,t,n){return this._client.post(me`/realtime/calls/${e}/refer`,{body:t,...n,headers:ke([{Accept:"*/*"},n?.headers])})}reject(e,t={},n){return this._client.post(me`/realtime/calls/${e}/reject`,{body:t,...n,headers:ke([{Accept:"*/*"},n?.headers])})}};var Dd=class extends xe{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}};var Vc=class extends xe{constructor(){super(...arguments),this.clientSecrets=new Dd(this._client),this.calls=new Td(this._client)}};Vc.ClientSecrets=Dd;Vc.Calls=Td;function vse(r,e){return!e||!xXe(e)?{...r,output_parsed:null,output:r.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(n=>({...n,parsed:null}))}:t)}:SR(r,e)}function SR(r,e){let t=r.output.map(i=>{if(i.type==="function_call")return{...i,parsed_arguments:SXe(e,i)};if(i.type==="message"){let a=i.content.map(s=>s.type==="output_text"?{...s,parsed:yXe(e,s.text)}:s);return{...i,content:a}}return i}),n=Object.assign({},r,{output:t});return Object.getOwnPropertyDescriptor(r,"output_text")||Xx(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let i of n.output)if(i.type==="message"){for(let a of i.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function yXe(r,e){return r.text?.format?.type!=="json_schema"?null:"$parseRaw"in r.text?.format?(r.text?.format).$parseRaw(e):JSON.parse(e)}function xXe(r){return!!B4(r.text?.format)}function wXe(r){return r?.$brand==="auto-parseable-tool"}function _Xe(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function SXe(r,e){let t=_Xe(r.tools??[],e.name);return{...e,...e,parsed_arguments:wXe(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Xx(r){let e=[];for(let t of r.output)if(t.type==="message")for(let n of t.content)n.type==="output_text"&&e.push(n.text);r.output_text=e.join("")}var Pd,Qx,$l,ew,bse,yse,xse,wse,tw=class r extends Tl{constructor(e){super(),Pd.add(this),Qx.set(this,void 0),$l.set(this,void 0),ew.set(this,void 0),Ze(this,Qx,e,"f")}static createResponse(e,t,n){let i=new r(t);return i._run(()=>i._createOrRetrieveResponse(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createOrRetrieveResponse(e,t,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),ae(this,Pd,"m",bse).call(this);let a,s=null;"response_id"in t?(a=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),s=t.starting_after??null):a=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let o of a)ae(this,Pd,"m",yse).call(this,o,s);if(a.controller.signal?.aborted)throw new kn;return ae(this,Pd,"m",xse).call(this)}[(Qx=new WeakMap,$l=new WeakMap,ew=new WeakMap,Pd=new WeakSet,bse=function(){this.ended||Ze(this,$l,void 0,"f")},yse=function(t,n){if(this.ended)return;let i=(s,o)=>{(n==null||o.sequence_number>n)&&this._emit(s,o)},a=ae(this,Pd,"m",wse).call(this,t);switch(i("event",t),t.type){case"response.output_text.delta":{let s=a.output[t.output_index];if(!s)throw new Me(`missing output at index ${t.output_index}`);if(s.type==="message"){let o=s.content[t.content_index];if(!o)throw new Me(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new Me(`expected content to be 'output_text', got ${o.type}`);i("response.output_text.delta",{...t,snapshot:o.text})}break}case"response.function_call_arguments.delta":{let s=a.output[t.output_index];if(!s)throw new Me(`missing output at index ${t.output_index}`);s.type==="function_call"&&i("response.function_call_arguments.delta",{...t,snapshot:s.arguments});break}default:i(t.type,t);break}},xse=function(){if(this.ended)throw new Me("stream has ended, this shouldn't happen");let t=ae(this,$l,"f");if(!t)throw new Me("request ended without sending any events");Ze(this,$l,void 0,"f");let n=EXe(t,ae(this,Qx,"f"));return Ze(this,ew,n,"f"),n},wse=function(t){let n=ae(this,$l,"f");if(!n){if(t.type!=="response.created")throw new Me(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return n=Ze(this,$l,t.response,"f"),n}switch(t.type){case"response.output_item.added":{n.output.push(t.item);break}case"response.content_part.added":{let i=n.output[t.output_index];if(!i)throw new Me(`missing output at index ${t.output_index}`);let a=i.type,s=t.part;a==="message"&&s.type!=="reasoning_text"?i.content.push(s):a==="reasoning"&&s.type==="reasoning_text"&&(i.content||(i.content=[]),i.content.push(s));break}case"response.output_text.delta":{let i=n.output[t.output_index];if(!i)throw new Me(`missing output at index ${t.output_index}`);if(i.type==="message"){let a=i.content[t.content_index];if(!a)throw new Me(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new Me(`expected content to be 'output_text', got ${a.type}`);a.text+=t.delta}break}case"response.function_call_arguments.delta":{let i=n.output[t.output_index];if(!i)throw new Me(`missing output at index ${t.output_index}`);i.type==="function_call"&&(i.arguments+=t.delta);break}case"response.reasoning_text.delta":{let i=n.output[t.output_index];if(!i)throw new Me(`missing output at index ${t.output_index}`);if(i.type==="reasoning"){let a=i.content?.[t.content_index];if(!a)throw new Me(`missing content at index ${t.content_index}`);if(a.type!=="reasoning_text")throw new Me(`expected content to be 'reasoning_text', got ${a.type}`);a.text+=t.delta}break}case"response.completed":{Ze(this,$l,t.response,"f");break}}return n},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("event",i=>{let a=t.shift();a?a.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{n=!0;for(let a of t)a.reject(i);t.length=0}),this.on("error",i=>{n=!0;for(let a of t)a.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,s)=>t.push({resolve:a,reject:s})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=ae(this,ew,"f");if(!e)throw new Me("stream ended without producing a ChatCompletion");return e}};function EXe(r,e){return vse(r,e)}var Od=class extends xe{list(e,t={},n){return this._client.getAPIList(me`/responses/${e}/input_items`,Ct,{query:t,...n})}};var Id=class extends xe{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}};var Kc=class extends xe{constructor(){super(...arguments),this.inputItems=new Od(this._client),this.inputTokens=new Id(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&Xx(n),n))}retrieve(e,t={},n){return this._client.get(me`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})._thenUnwrap(i=>("object"in i&&i.object==="response"&&Xx(i),i))}delete(e,t){return this._client.delete(me`/responses/${e}`,{...t,headers:ke([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(n=>SR(n,e))}stream(e,t){return tw.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(me`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}};Kc.InputItems=Od;Kc.InputTokens=Id;var Rd=class extends xe{create(e,t,n){return this._client.post(me`/uploads/${e}/parts`,Ha({body:t,...n},this._client))}};var Ll=class extends xe{constructor(){super(...arguments),this.parts=new Rd(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(me`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(me`/uploads/${e}/complete`,{body:t,...n})}};Ll.Parts=Rd;var _se=async r=>{let e=await Promise.allSettled(r),t=e.filter(i=>i.status==="rejected");if(t.length){for(let i of t)console.error(i.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let n=[];for(let i of e)i.status==="fulfilled"&&n.push(i.value);return n};var Fd=class extends xe{create(e,t,n){return this._client.post(me`/vector_stores/${e}/file_batches`,{body:t,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{vector_store_id:i}=t;return this._client.get(me`/vector_stores/${i}/file_batches/${e}`,{...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,t,n){let{vector_store_id:i}=t;return this._client.post(me`/vector_stores/${i}/file_batches/${e}/cancel`,{...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let i=await this.create(e,t);return await this.poll(e,i.id,n)}listFiles(e,t,n){let{vector_store_id:i,...a}=t;return this._client.getAPIList(me`/vector_stores/${i}/file_batches/${e}/files`,Ct,{query:a,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async poll(e,t,n){let i=ke([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:a,response:s}=await this.retrieve(t,{vector_store_id:e},{...n,headers:i}).withResponse();switch(a.status){case"in_progress":let o=5e3;if(n?.pollIntervalMs)o=n.pollIntervalMs;else{let c=s.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(o=u)}}await Bo(o);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},i){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 a=i?.maxConcurrency??5,s=Math.min(a,t.length),o=this._client,c=t.values(),u=[...n];async function l(p){for(let d of p){let m=await o.files.create({file:d,purpose:"assistants"},i);u.push(m.id)}}let f=Array(s).fill(c).map(l);return await _se(f),await this.createAndPoll(e,{file_ids:u})}};var jd=class extends xe{create(e,t,n){return this._client.post(me`/vector_stores/${e}/files`,{body:t,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{vector_store_id:i}=t;return this._client.get(me`/vector_stores/${i}/files/${e}`,{...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{vector_store_id:i,...a}=t;return this._client.post(me`/vector_stores/${i}/files/${e}`,{body:a,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(me`/vector_stores/${e}/files`,Ct,{query:t,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t,n){let{vector_store_id:i}=t;return this._client.delete(me`/vector_stores/${i}/files/${e}`,{...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let i=await this.create(e,t,n);return await this.poll(e,i.id,n)}async poll(e,t,n){let i=ke([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let a=await this.retrieve(t,{vector_store_id:e},{...n,headers:i}).withResponse(),s=a.data;switch(s.status){case"in_progress":let o=5e3;if(n?.pollIntervalMs)o=n.pollIntervalMs;else{let c=a.response.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(o=u)}}await Bo(o);break;case"failed":case"completed":return s}}}async upload(e,t,n){let i=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:i.id},n)}async uploadAndPoll(e,t,n){let i=await this.upload(e,t,n);return await this.poll(e,i.id,n)}content(e,t,n){let{vector_store_id:i}=t;return this._client.getAPIList(me`/vector_stores/${i}/files/${e}/content`,Ho,{...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var Jc=class extends xe{constructor(){super(...arguments),this.files=new jd(this._client),this.fileBatches=new Fd(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(me`/vector_stores/${e}`,{...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(me`/vector_stores/${e}`,{body:t,...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",Ct,{query:e,...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(me`/vector_stores/${e}`,{...t,headers:ke([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,n){return this._client.getAPIList(me`/vector_stores/${e}/search`,Ho,{body:t,method:"post",...n,headers:ke([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};Jc.Files=jd;Jc.FileBatches=Fd;var B3=class extends xe{create(e,t){return this._client.post("/videos",aR({body:e,...t},this._client))}retrieve(e,t){return this._client.get(me`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",zc,{query:e,...t})}delete(e,t){return this._client.delete(me`/videos/${e}`,t)}downloadContent(e,t={},n){return this._client.get(me`/videos/${e}/content`,{query:t,...n,headers:ke([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}remix(e,t,n){return this._client.post(me`/videos/${e}/remix`,aR({body:t,...n},this._client))}};var Md,Sse,rw,z3=class extends xe{constructor(){super(...arguments),Md.add(this)}async unwrap(e,t,n=this._client.webhookSecret,i=300){return await this.verifySignature(e,t,n,i),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,i=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");ae(this,Md,"m",Sse).call(this,n);let a=ke([t]).values,s=ae(this,Md,"m",rw).call(this,a,"webhook-signature"),o=ae(this,Md,"m",rw).call(this,a,"webhook-timestamp"),c=ae(this,Md,"m",rw).call(this,a,"webhook-id"),u=parseInt(o,10);if(isNaN(u))throw new Lo("Invalid webhook timestamp format");let l=Math.floor(Date.now()/1e3);if(l-u>i)throw new Lo("Webhook timestamp is too old");if(u>l+i)throw new Lo("Webhook timestamp is too new");let f=s.split(" ").map(h=>h.startsWith("v1,")?h.substring(3):h),p=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),d=c?`${c}.${o}.${e}`:`${o}.${e}`,m=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let h of f)try{let g=Buffer.from(h,"base64");if(await crypto.subtle.verify("HMAC",m,g,new TextEncoder().encode(d)))return}catch{continue}throw new Lo("The given webhook signature does not match the expected signature")}};Md=new WeakSet,Sse=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")},rw=function(e,t){if(!e)throw new Error("Headers are required");let n=e.get(t);if(n==null)throw new Error(`Missing required header: ${t}`);return n};var ER,AR,nw,Ese,gt=class{constructor({baseURL:e=Rl("OPENAI_BASE_URL"),apiKey:t=Rl("OPENAI_API_KEY"),organization:n=Rl("OPENAI_ORG_ID")??null,project:i=Rl("OPENAI_PROJECT_ID")??null,webhookSecret:a=Rl("OPENAI_WEBHOOK_SECRET")??null,...s}={}){if(ER.add(this),nw.set(this,void 0),this.completions=new P3(this),this.chat=new Pl(this),this.embeddings=new I3(this),this.files=new F3(this),this.images=new q3(this),this.audio=new Wo(this),this.moderations=new L3(this),this.models=new $3(this),this.fineTuning=new Qs(this),this.graders=new ql(this),this.vectorStores=new Jc(this),this.webhooks=new z3(this),this.beta=new Xs(this),this.batches=new A3(this),this.uploads=new Ll(this),this.responses=new Kc(this),this.realtime=new Vc(this),this.conversations=new Ml(this),this.evals=new Nl(this),this.containers=new jl(this),this.videos=new B3(this),t===void 0)throw new Me("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let o={apiKey:t,organization:n,project:i,webhookSecret:a,...s,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&Oae())throw new Me(`It looks like you're running in a browser-like environment.
|
|
998
998
|
|
|
999
999
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
1000
1000
|
If you understand the risks and have appropriate mitigations in place,
|
|
@@ -1292,7 +1292,7 @@ ${l}
|
|
|
1292
1292
|
|
|
1293
1293
|
`;let p=n.integrations?new Map(Object.entries(n.integrations).map(([x,E])=>{let C=!E||!E.length?[]:E;return[x,C]})):void 0,d=performance.now(),m=await this.toolbox.getTools({context:t,integrations:p,agentName:n.name}),h=performance.now()-d,g=new bE([...m]),v=new Kv(n,s,g),b=performance.now()-i;return this.interactor.debug(`\u2728 Agent '${n.name}' created: ${b.toFixed(2)}ms (client: ${o.toFixed(2)}ms, docs: ${f.toFixed(2)}ms, tools: ${h.toFixed(2)}ms)`),v}catch(a){let s=`Failed to create agent ${n.name}`;console.error(`${s}:`,a),this.interactor.error(s);return}}};var xE=class{constructor(e,t){this.userService=e;this.projectService=t}providerCache=new Map;mergedConfig=null;initialize(e){this.providerCache.clear(),this.mergedConfig=null,this.providerCache.set("coday",e.project.ai||[]),this.providerCache.set("project",this.projectService.selectedProject?.config?.ai||[]),this.providerCache.set("user",this.userService.config.ai||[])}getProviders(e){return this.providerCache.get(e)||[]}getProvider(e,t){return Ri.validate(t),this.getProviders(t).find(i=>i.name===e)}async saveProvider(e,t){Ri.validate(t);let n=this.getProviders(t),i=n.findIndex(a=>a.name===e.name);i>=0?n[i]=e:n.push(e),await this.saveProviders(n,t),this.mergedConfig=null}async deleteProvider(e,t){Ri.validate(t);let n=this.getProviders(t),i=n.filter(a=>a.name!==e);i.length!==n.length&&(await this.saveProviders(i,t),this.mergedConfig=null)}getModel(e,t,n){return Ri.validate(n),this.getProvider(e,n)?.models?.find(a=>a.name===t||a.alias===t)}async saveModel(e,t,n){Ri.validate(n);let i=this.getProvider(e,n);i||(i={name:e,models:[]},await this.saveProvider(i,n));let a=i.models||[],s=a.findIndex(o=>o.name===t.name||t.alias&&o.alias===t.alias);s>=0?a[s]=t:a.push(t),i.models=a,await this.saveProvider(i,n),this.mergedConfig=null}async deleteModel(e,t,n){Ri.validate(n);let i=this.getProvider(e,n);if(i?.models){let a=i.models.filter(s=>s.name!==t&&s.alias!==t);a.length!==i.models.length&&(i.models=a,await this.saveProvider(i,n),this.mergedConfig=null)}}getMergedConfiguration(){if(this.mergedConfig)return this.mergedConfig;let e=[],t=new Map;for(let n of["coday","project","user"]){let i=this.providerCache.get(n)||[];for(let a of i){let s=e.findIndex(o=>o.name===a.name);if(s>=0){let o=e[s];if(e[s]={...o,...a},a.models?.length){let c=o.models||[];for(let u of a.models){let l=c.findIndex(f=>f.name===u.name||u.alias&&f.alias===u.alias);l>=0?c[l]={...c[l],...u,price:{...c[l]?.price,...u.price}}:c.push(u),u.alias&&t.set(u.alias,{provider:a.name,model:u.name})}e[s].models=c}}else e.push({...a}),a.models?.forEach(o=>{o.alias&&t.set(o.alias,{provider:a.name,model:o.name})})}}return this.mergedConfig={providers:e,modelAliasMap:t},this.mergedConfig}resolveModelAlias(e){return this.getMergedConfiguration().modelAliasMap.get(e)}async saveProviders(e,t){switch(t){case"project":if(!this.projectService.selectedProject)throw new Error("No project selected");let n={...this.projectService.selectedProject.config,ai:e};this.projectService.save(n),this.providerCache.set(t,e);break;case"user":this.userService.config.ai=e,this.userService.save(),this.providerCache.set(t,e);break}}};import*as M4e from"path";var tdt=100,wE=class{constructor(e,t,n){this.interactor=e;this.options=t;this.services=n;this.interactor.debugLevelEnabled=t.debug,this.interactor.debug("Coday started with debug"),this.configHandler=new hx(e,this.services),this.maxIterations=tdt,this.aiThreadService=new Hv(n.user,n.thread.getThreadRepository(t.project),t.project,e),this.aiThreadService.activeThread.subscribe(i=>{!this.context||!i||(this.context.aiThread=i,this.replayThread(i))}),this.aiClientProvider=new n1(this.interactor,this.services.user,this.services.project,this.services.logger)}context=null;configHandler;handlerLooper;aiHandler;maxIterations;initialPrompts=[];aiThreadService;killed=!1;aiClientProvider;replay(){let e=this.aiThreadService.getCurrentThread();if(!e){console.log("No active thread to replay");return}this.replayThread(e),!this.options.oneshot&&e.runStatus!=="RUNNING"&&this.interactor.replayLastInvite()}upload(e){let t=this.aiThreadService.getCurrentThread();if(!t){this.interactor.error("No active thread available for upload");return}let n=this.services.user.username;e.forEach(a=>{t.addUserMessage(n,a)});let i=new rr({role:"user",content:e,name:n});this.interactor.sendEvent(i)}async run(){this.initialPrompts=this.options.prompts?[...this.options.prompts]:[],this.interactor.debug(`[CODAY] Starting run with ${this.initialPrompts.length} initial prompts`);try{do{if(this.killed)return;if(await this.initContext(),await this.initThread(),!this.context){this.interactor.error("Could not initialize context \u{1F62D}");break}let e=await this.initCommand();if(!e&&this.options.oneshot)break;let t=this.context?.aiThread;t&&(t.runStatus="RUNNING"),this.context?.addCommands(e),this.context=await this.handlerLooper?.handle(this.context)??null}while(!this.context?.oneshot)}finally{this.stop()}await this.cleanup()}stop(){let e=this.context?.aiThread;e&&(e.runStatus="STOPPED"),this.handlerLooper?.stop(),this.aiThreadService.autoSave()}async cleanup(){try{this.services.agent&&await this.services.agent.kill(),this.aiThreadService.kill(),this.aiClientProvider.cleanup(),this.context=null,this.handlerLooper=void 0,this.aiHandler=void 0}catch(e){console.error("Error during agent cleanup:",e)}}async kill(){this.killed=!0,this.stop();try{await this.cleanup()}catch(e){console.error("Error during kill cleanup:",e)}this.handlerLooper?.kill(),this.interactor.kill()}async replayThread(e){let t=(await e.getMessages(void 0,void 0)).messages;if(!t?.length)return;let n=[...t].sort((i,a)=>new Date(i.timestamp).getTime()-new Date(a.timestamp).getTime());for(let i of n)(i instanceof rr||i instanceof Sn||i instanceof En)&&this.interactor.sendEvent(i);this.interactor.displayText(`Selected thread '${e.name}'`)}async initContext(){this.context||(this.context=await this.configHandler.selectProjectHandler.selectProject(this.options.project),this.context&&(this.context.oneshot=this.options.oneshot,this.context.fileReadOnly=this.options.fileReadOnly,this.options.thread&&this.options.project&&(this.context.threadFilesRoot=M4e.join(this.options.configDir,"projects",this.options.project,"threads",`${this.options.thread}-files`),this.interactor.debug(`[CODAY] Thread files root: ${this.context.threadFilesRoot}`)),this.services.aiConfig=new xE(this.services.user,this.services.project),this.services.aiConfig.initialize(this.context),this.services.mcp.initialize(this.context),this.services.agent=new ah(this.interactor,this.aiClientProvider,this.services,this.context.project.root,this.options.agentFolders),this.aiHandler=new Yv(this.interactor,this.services.agent,this.aiThreadService),this.handlerLooper=new Tx(this.interactor,this.aiHandler,this.configHandler,this.services),this.aiClientProvider.init(this.context),this.handlerLooper.init(this.context.project),await this.services.agent.initialize(this.context)))}async initThread(){if(!this.context?.aiThread){if(!this.options.thread)throw Error("No thread given, cannot start Coday instance");await this.aiThreadService.select(this.options.thread)}}async initCommand(){let e;return this.interactor.debug(`[CODAY] initCommand: ${this.initialPrompts.length} prompts available, oneshot=${this.options.oneshot}`),this.initialPrompts.length?(e=this.initialPrompts.shift(),this.interactor.debug(`[CODAY] Using initial prompt: ${e}`),this.initialPrompts.length&&(this.interactor.debug(`[CODAY] Adding ${this.initialPrompts.length} remaining prompts to queue`),this.context?.addCommands(...this.initialPrompts),this.initialPrompts=[])):this.options.oneshot?this.interactor.debug("[CODAY] No initial prompts and oneshot mode, exiting"):(this.interactor.debug("[CODAY] No initial prompts, waiting for user input"),e=await this.interactor.promptText(WQ)),e}};import*as oh from"node:path";import{existsSync as sdt,mkdirSync as odt}from"fs";var N4e=xr(bl(),1);import{existsSync as rdt,readFileSync as ndt}from"fs";function f2(r){try{if(!rdt(r))return;let e=ndt(r,"utf-8");return N4e.parse(e)}catch(e){console.error(`Failed to file at ${r} :`,e);return}}var q4e=xr(bl(),1);import{writeFileSync as idt}from"node:fs";function ei(r,e){try{let t=q4e.stringify(e);idt(r,t)}catch(t){console.error(`Failed to write file ${r}:`,t)}}var $4e={version:1};import*as z4e from"node:os";function sh(r,e){let t=r.version?r:{...r,version:1},n=[...e].filter(i=>i.version>=t.version).sort((i,a)=>i.version-a.version);for(let i of n){let a=i.migrate({...t});a.version=i.version+1,t=a}return t}var adt=["anthropic","openai","google"],_E={version:1,description:"Migrate aiProviders to ai property",migrate:r=>{let{aiProviders:e,...t}=r,n=[];return e&&Object.keys(e).forEach(i=>{let a={name:i,apiKey:e[i]?.apiKey};if(!adt.includes(i)&&(a.type="openai",a.url=e[i]?.url,e[i]?.model)){let s={name:e[i].model,contextWindow:e[i]?.contextWindow??64e3};a.models=[s]}n.push(a)}),{...t,aiProviders:e,ai:n}}};var L4e=[_E];var p2=class{MASK_PATTERN="****";SENSITIVE_FIELD_NAMES=["apikey","api_key","password","token","secret","auth"];isSensitiveField(e){let t=e.toLowerCase();return this.SENSITIVE_FIELD_NAMES.some(n=>t.includes(n))}maskValue(e){if(!e||e.length===0)return e;if(e.length<=8)return this.MASK_PATTERN;if(e.length<12){let i=e.substring(0,2),a=e.substring(e.length-2);return`${i}${this.MASK_PATTERN}${a}`}let t=e.substring(0,4),n=e.substring(e.length-4);return`${t}${this.MASK_PATTERN}${n}`}isMasked(e){return typeof e=="string"&&e.includes(this.MASK_PATTERN)}maskConfig(e){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.maskConfig(n));let t={};for(let[n,i]of Object.entries(e))this.isSensitiveField(n)&&typeof i=="string"?t[n]=this.maskValue(i):n==="env"&&typeof i=="object"&&i!==null&&!Array.isArray(i)?t[n]=this.maskEnvObject(i):typeof i=="object"&&i!==null?t[n]=this.maskConfig(i):t[n]=i;return t}maskEnvObject(e){let t={};for(let[n,i]of Object.entries(e))typeof i=="string"?t[n]=this.maskValue(i):t[n]=i;return t}unmaskConfig(e,t){if(e==null||t==null||typeof e!="object")return e;if(Array.isArray(e))return e.map((s,o)=>{let c=Array.isArray(t)?t[o]:void 0;return this.unmaskConfig(s,c)});let n={},i=e,a=t;for(let[s,o]of Object.entries(i)){let c=a[s];this.isSensitiveField(s)&&typeof o=="string"?this.isMasked(o)?n[s]=c:n[s]=o:s==="env"&&typeof o=="object"&&o!==null&&!Array.isArray(o)?n[s]=this.unmaskEnvObject(o,c):typeof o=="object"&&o!==null?n[s]=this.unmaskConfig(o,c):n[s]=o}if(!Array.isArray(e))for(let[s,o]of Object.entries(a))s in i||(n[s]=o);return n}unmaskEnvObject(e,t){if(!t||typeof t!="object")return e;let n={};for(let[i,a]of Object.entries(e))typeof a=="string"&&this.isMasked(a)?n[i]=t[i]:n[i]=a;for(let[i,a]of Object.entries(t))i in e||(n[i]=a);return n}};var cdt="users",B4e="user.yaml",d2=class{constructor(e,t,n){this.username=t;this.interactor=n;this.sanitizedUsername=this.sanitizeUsername(t);let i=oh.join(z4e.userInfo().homedir,".coday"),a=oh.join(e??i,cdt);this.userConfigPath=oh.join(a,this.sanitizedUsername),odt(this.userConfigPath,{recursive:!0});let s=oh.join(this.userConfigPath,B4e);if(!sdt(s)){let c={...$4e,version:1};ei(s,c)}let o=f2(s);if(!o)throw Error(`Could not read user config for username ${this.sanitizedUsername}`);this.config=sh(o,L4e),this.config!==o&&(ei(s,this.config),this.interactor.displayText(`User configuration migrated to version ${this.config?.version}`))}userConfigPath;sanitizedUsername;config;maskingService=new p2;save(){if(this.config){let e=oh.join(this.userConfigPath,B4e);ei(e,this.config)}else console.error("No user configuration available to save.")}setProjectIntegration(e,t){this.config.projects??={},this.config.projects[e]??={integration:{}},this.config.projects[e].integration={...this.config.projects[e].integration,...t},this.save()}sanitizeUsername(e){return e.replace(/[^a-zA-Z0-9]/g,"_")}setBio(e){this.config.bio=e?.trim()||void 0,this.save()}getBio(){return this.config.bio}setProjectBio(e,t){this.config.projects??={},this.config.projects[e]??={integration:{}},this.config.projects[e].bio=t?.trim()||void 0,this.save()}getProjectBio(e){return this.config.projects?.[e]?.bio}getCombinedBio(e){let t=this.getBio(),n=e?this.getProjectBio(e):void 0;return t&&n?`${t}
|
|
1294
1294
|
|
|
1295
|
-
Project context: ${n}`:n??t}getUserData(e){return{username:this.username,bio:this.getCombinedBio(e)}}getConfigForClient(){return this.maskingService.maskConfig(this.config)}updateConfigFromClient(e){this.config=this.maskingService.unmaskConfig(e,this.config),this.save()}};var W4e=xr(zs(),1);import*as ch from"node:path";import*as H4e from"node:os";import{mkdirSync as udt}from"fs";var ldt="projects",U4e="project.yaml",uh=class{constructor(e,t,n){this.interactor=e;this.projectService=t;let i=ch.join(H4e.userInfo().homedir,".coday");this.projectsConfigPath=ch.join(n??i,ldt),udt(this.projectsConfigPath,{recursive:!0}),this.projects=this.projectService.listProjects().map(a=>a.name)}projectsConfigPath;maskingService=new p2;projects;selectedProjectBehaviorSubject=new W4e.BehaviorSubject(null);selectedProject$=this.selectedProjectBehaviorSubject.asObservable();selectProject(e){let t=ch.join(this.projectsConfigPath,e),n=ch.join(t,U4e),i=this.projectService.getProject(e)?.config;if(!i?.path){this.interactor.error("Invalid selection, project path needed \u{1F622}.");return}let s={name:e,config:i,configPath:t};this.updateSelectedProject(s),this.interactor.displayText(`Project local configuration used: ${n}`)}updateSelectedProject(e){this.selectedProjectBehaviorSubject.next(e)}get selectedProject(){return this.selectedProjectBehaviorSubject.value}save(e){let t=this.selectedProjectBehaviorSubject.value;if(!t){this.interactor.error("No current project selected, save not possible");return}let n={...t.config,...e};ei(ch.join(t.configPath,U4e),n),t.config=n,this.updateSelectedProject(t)}getConfigForClient(){let e=this.selectedProjectBehaviorSubject.value;return e?this.maskingService.maskConfig(e.config):null}updateConfigFromClient(e){let t=this.selectedProjectBehaviorSubject.value;if(!t){this.interactor.error("No current project selected, update not possible");return}let n=this.maskingService.unmaskConfig(e,t.config);this.save(n)}};var fdt="_API_KEY",lh=class{constructor(e,t,n){this.projectService=e;this.userService=t;this.interactor=n;e.selectedProject$.subscribe(i=>{if(!i){this.projectIntegrations={},this.userIntegrations={},this.integrations={};return}this.projectIntegrations=i.config.integration||{},this.userIntegrations=i.name&&this.userService.config.projects?this.userService.config.projects[i.name]?.integration||{}:{},this.integrations={...this.projectIntegrations},Object.keys(this.userIntegrations).forEach(a=>{let s=this.userIntegrations[a],o=this.integrations[a];o
|
|
1295
|
+
Project context: ${n}`:n??t}getUserData(e){return{username:this.username,bio:this.getCombinedBio(e)}}getConfigForClient(){return this.maskingService.maskConfig(this.config)}updateConfigFromClient(e){this.config=this.maskingService.unmaskConfig(e,this.config),this.save()}};var W4e=xr(zs(),1);import*as ch from"node:path";import*as H4e from"node:os";import{mkdirSync as udt}from"fs";var ldt="projects",U4e="project.yaml",uh=class{constructor(e,t,n){this.interactor=e;this.projectService=t;let i=ch.join(H4e.userInfo().homedir,".coday");this.projectsConfigPath=ch.join(n??i,ldt),udt(this.projectsConfigPath,{recursive:!0}),this.projects=this.projectService.listProjects().map(a=>a.name)}projectsConfigPath;maskingService=new p2;projects;selectedProjectBehaviorSubject=new W4e.BehaviorSubject(null);selectedProject$=this.selectedProjectBehaviorSubject.asObservable();selectProject(e){let t=ch.join(this.projectsConfigPath,e),n=ch.join(t,U4e),i=this.projectService.getProject(e)?.config;if(!i?.path){this.interactor.error("Invalid selection, project path needed \u{1F622}.");return}let s={name:e,config:i,configPath:t};this.updateSelectedProject(s),this.interactor.displayText(`Project local configuration used: ${n}`)}updateSelectedProject(e){this.selectedProjectBehaviorSubject.next(e)}get selectedProject(){return this.selectedProjectBehaviorSubject.value}save(e){let t=this.selectedProjectBehaviorSubject.value;if(!t){this.interactor.error("No current project selected, save not possible");return}let n={...t.config,...e};ei(ch.join(t.configPath,U4e),n),t.config=n,this.updateSelectedProject(t)}getConfigForClient(){let e=this.selectedProjectBehaviorSubject.value;return e?this.maskingService.maskConfig(e.config):null}updateConfigFromClient(e){let t=this.selectedProjectBehaviorSubject.value;if(!t){this.interactor.error("No current project selected, update not possible");return}let n=this.maskingService.unmaskConfig(e,t.config);this.save(n)}};var fdt="_API_KEY",lh=class{constructor(e,t,n){this.projectService=e;this.userService=t;this.interactor=n;e.selectedProject$.subscribe(i=>{if(!i){this.projectIntegrations={},this.userIntegrations={},this.integrations={};return}this.projectIntegrations=i.config.integration||{},this.userIntegrations=i.name&&this.userService.config.projects?this.userService.config.projects[i.name]?.integration||{}:{},this.integrations={...this.projectIntegrations},Object.keys(this.userIntegrations).forEach(a=>{let s=this.userIntegrations[a],o=this.integrations[a];if(!o)this.integrations[a]=s;else{let c={...o,...s};o.oauth2&&s.oauth2&&(c.oauth2={...o.oauth2,...s.oauth2}),this.integrations[a]=c}})})}integrations={};projectIntegrations={};userIntegrations={};hasIntegration(e){let t=Wv[e];return t?t.length?t.some(n=>this.hasIntegration(n)):Object.keys(this.integrations).includes(e):!1}getIntegration(e){return this.integrations[e]}getApiKey(e){if(!X2.includes(e))return;let t=process.env[`${e}${fdt}`];return t?(this.interactor?.displayText(`Using environment variable for ${e} API key`),t):this.integrations[e]?.apiKey}setIntegration(e,t){this.integrations[e]=t,this.projectService.save({integration:this.integrations})}getApiUrl(e){return this.integrations[e]?.apiUrl}getUsername(e){return this.integrations[e]?.username}};var G4e="********",fh=class{constructor(e,t,n){this.userService=e;this.projectService=t;this.interactor=n}getIntegrations(e){if(Ri.validate(e),e==="coday")throw new Error("CODAY level not supported for integrations");let t={};if(e==="project"){let n=this.projectService.selectedProject;if(!n)return{};t=n.config.integration||{}}else if(e==="user"){let n=this.projectService.selectedProject;if(!n)return{};t=(this.userService.config.projects||{})[n.name]?.integration||{}}return this.maskApiKeys(t)}async saveIntegration(e,t,n){if(Ri.validate(n),n==="coday")throw new Error("CODAY level not supported for integrations");if(n==="project"){let i=this.projectService.selectedProject;if(!i)throw new Error("No project selected");let s={...i.config.integration||{},[e]:t};this.projectService.save({integration:s})}else if(n==="user"){let i=this.projectService.selectedProject;if(!i)throw new Error("No project selected");this.userService.setProjectIntegration(i.name,{[e]:t})}this.interactor.debug(`Integration '${e}' saved at ${n.toLowerCase()} level`)}async deleteIntegration(e,t){if(Ri.validate(t),t==="coday")throw new Error("CODAY level not supported for integrations");if(t==="project"){let n=this.projectService.selectedProject;if(!n)throw new Error("No project selected");let i=n.config.integration||{};if(!i[e])throw new Error(`Integration '${e}' not found at project level`);let a={...i};delete a[e],this.projectService.save({integration:a})}else if(t==="user"){let n=this.projectService.selectedProject;if(!n)throw new Error("No project selected");let a=(this.userService.config.projects||{})[n.name]?.integration||{};if(!a[e])throw new Error(`Integration '${e}' not found at user level`);let s={...a};delete s[e],this.userService.config.projects||(this.userService.config.projects={}),this.userService.config.projects[n.name]||(this.userService.config.projects[n.name]={integration:{}}),this.userService.config.projects[n.name].integration=s,this.userService.save()}this.interactor.debug(`Integration '${e}' deleted from ${t.toLowerCase()} level`)}getMergedIntegrations(){let e=this.projectService.selectedProject;if(!e)return{};let t=e.config.integration||{},i=(this.userService.config.projects||{})[e.name]?.integration||{},a={...t};return Object.keys(i).forEach(s=>{let o=i[s],c=a[s];c?a[s]={...c,...o}:a[s]=o}),this.maskApiKeys(a)}maskApiKeys(e){let t={};return Object.keys(e).forEach(n=>{let i=e[n];t[n]={...i,...i.apiKey&&{apiKey:G4e}}}),t}isApiKeyMasked(e){return e===G4e}getUnmaskedIntegration(e,t){if(Ri.validate(t),t==="coday")throw new Error("CODAY level not supported for integrations");if(t==="project"){let n=this.projectService.selectedProject;return n?(n.config.integration||{})[e]:void 0}else if(t==="user"){let n=this.projectService.selectedProject;return n?((this.userService.config.projects||{})[n.name]?.integration||{})[e]:void 0}}};var V4e=xr(bl(),1);import*as SE from"node:path";import{existsSync as pdt,writeFileSync as ddt}from"node:fs";var K4e=xr(zs(),1),eL="memories.yaml",ph=class{memories=[];userMemoriesPath;projectMemoriesPath;constructor(e,t){this.userMemoriesPath=SE.join(t.userConfigPath,eL),e.selectedProject$.pipe((0,K4e.distinctUntilChanged)()).subscribe(n=>{this.projectMemoriesPath=n?.configPath?SE.join(n.configPath,eL):void 0,n&&this.loadMemoriesFrom(n)})}upsertMemory(e){this.checkInit();let t=this.memories.findIndex(n=>n.title===e.title);t===-1?this.memories.push(new D4(e)):this.memories[t]=new D4({...this.memories[t],...e}),this.saveMemories()}deleteMemory(e){this.checkInit();let t=this.memories.findIndex(n=>n.title===e);if(t!==-1)this.memories.splice(t,1),this.saveMemories();else throw new Error(`Memory with title '${e}' does not exist`)}listMemories(e,t){return this.checkInit(),this.memories.filter(n=>n.level===e&&(!n.agentName||n.agentName===t))}getFormattedMemories(e,t){let n=this.listMemories(e,t).map(i=>` - ${i.title}
|
|
1296
1296
|
${i.content}`);return n.length?(n.unshift(`## ${e} memories
|
|
1297
1297
|
|
|
1298
1298
|
Here are the information collected during previous chats:
|