@whoz-oss/coday-server 0.69.2 → 0.70.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
|
@@ -345,7 +345,7 @@ If you understand the risks and have appropriate mitigations in place,
|
|
|
345
345
|
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
346
346
|
|
|
347
347
|
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
348
|
-
`);this.baseURL=a.baseURL,this.timeout=a.timeout??Q$.DEFAULT_TIMEOUT,this.logger=a.logger??console;let o="warn";this.logLevel=o,this.logLevel=R$(a.logLevel,"ClientOptions.logLevel",this)??R$(Q4("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??o,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??aie(),Ze(this,_x,sie,"f"),this._options=a,this.apiKey=t,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(this.apiKey&&e.get("x-api-key"))&&!t.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!t.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return sr([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return sr([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return sr([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([t,n])=>typeof n<"u").map(([t,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(t)}=`;throw new ot(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Zl}`}defaultIdempotencyKey(){return`stainless-node-retry-${T$()}`}makeStatusError(e,t,n,i){return li.generate(e,t,n,i)}buildURL(e,t,n){let i=!he(this,X$,"m",Die).call(this)&&n||this.baseURL,a=Jne(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();return Kne(o)||(t={...o,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(a.search=this.stringifyQuery(t)),a.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new ot("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(i=>({method:e,path:t,...i})))}request(e,t=null){return new Uf(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let i=await e,a=i.maxRetries??this.maxRetries;t==null&&(t=a),await this.prepareOptions(i);let{req:o,url:s,timeout:c}=await this.buildRequest(i,{retryCount:a-t});await this.prepareRequest(o,{url:s,options:i});let u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=n===void 0?"":`, retryOf: ${n}`,f=Date.now();if(fi(this).debug(`[${u}] sending request`,gu({retryOfRequestLogID:n,method:i.method,url:s,options:i,headers:o.headers})),i.signal?.aborted)throw new Di;let d=new AbortController,p=await this.fetchWithTimeout(s,o,c,d).catch($4),m=Date.now();if(p instanceof globalThis.Error){let v=`retrying, ${t} attempts remaining`;if(i.signal?.aborted)throw new Di;let b=hu(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(t)return fi(this).info(`[${u}] connection ${b?"timed out":"failed"} - ${v}`),fi(this).debug(`[${u}] connection ${b?"timed out":"failed"} (${v})`,gu({retryOfRequestLogID:n,url:s,durationMs:m-f,message:p.message})),this.retryRequest(i,t,n??u);throw fi(this).info(`[${u}] connection ${b?"timed out":"failed"} - error; no more retries left`),fi(this).debug(`[${u}] connection ${b?"timed out":"failed"} (error; no more retries left)`,gu({retryOfRequestLogID:n,url:s,durationMs:m-f,message:p.message})),b?new p0:new Vl({cause:p})}let h=[...p.headers.entries()].filter(([v])=>v==="request-id").map(([v,b])=>", "+v+": "+JSON.stringify(b)).join(""),g=`[${u}${l}${h}] ${o.method} ${s} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${m-f}ms`;if(!p.ok){let v=await this.shouldRetry(p);if(t&&v){let $=`retrying, ${t} attempts remaining`;return await oie(p.body),fi(this).info(`${g} - ${$}`),fi(this).debug(`[${u}] response error (${$})`,gu({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:m-f})),this.retryRequest(i,t,n??u,p.headers)}let b=v?"error; no more retries left":"error; not retryable";fi(this).info(`${g} - ${b}`);let x=await p.text().catch($=>$4($).message),k=Yy(x),E=k?void 0:x;throw fi(this).debug(`[${u}] response error (${b})`,gu({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,message:E,durationMs:Date.now()-f})),this.makeStatusError(p.status,k,E,p.headers)}return fi(this).info(g),fi(this).debug(`[${u}] response start`,gu({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:m-f})),{response:p,options:i,controller:d,requestLogID:u,retryOfRequestLogID:n,startTime:f}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new L4(this,n,e)}async fetchWithTimeout(e,t,n,i){let{signal:a,method:o,...s}=t||{};a&&a.addEventListener("abort",()=>i.abort());let c=setTimeout(()=>i.abort(),n),u=globalThis.ReadableStream&&s.body instanceof globalThis.ReadableStream||typeof s.body=="object"&&s.body!==null&&Symbol.asyncIterator in s.body,l={signal:i.signal,...u?{duplex:"half"}:{},method:"GET",...s};o&&(l.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,l)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,i){let a,o=i?.get("retry-after-ms");if(o){let c=parseFloat(o);Number.isNaN(c)||(a=c)}let s=i?.get("retry-after");if(s&&!a){let c=parseFloat(s);Number.isNaN(c)?a=Date.parse(s)-Date.now():a=c*1e3}if(!(a&&0<=a&&a<60*1e3)){let c=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,c)}return await Qne(a),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let a=t-e,o=Math.min(.5*Math.pow(2,a),8),s=1-Math.random()*.25;return o*s*1e3}calculateNonstreamingTimeout(e,t){if(36e5*e/128e3>6e5||t!=null&&e>t)throw new ot("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:i,path:a,query:o,defaultBaseURL:s}=n,c=this.buildURL(a,o,s);"timeout"in n&&Xne("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:u,body:l}=this.buildBody({options:n}),f=await this.buildHeaders({options:e,method:i,bodyHeaders:u,retryCount:t});return{req:{method:i,headers:f,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:i}){let a={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);let o=sr([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...iie(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(o),o.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=sr([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Xy(e)}:he(this,_x,"f").call(this,{body:e,headers:n})}};Q$=mn,_x=new WeakMap,X$=new WeakSet,Die=function(){return this.baseURL!=="https://api.anthropic.com"};mn.Anthropic=Q$;mn.HUMAN_PROMPT=Oie;mn.AI_PROMPT=Iie;mn.DEFAULT_TIMEOUT=6e5;mn.AnthropicError=ot;mn.APIError=li;mn.APIConnectionError=Vl;mn.APIConnectionTimeoutError=p0;mn.APIUserAbortError=Di;mn.NotFoundError=g0;mn.ConflictError=v0;mn.RateLimitError=y0;mn.BadRequestError=d0;mn.AuthenticationError=h0;mn.InternalServerError=x0;mn.PermissionDeniedError=m0;mn.UnprocessableEntityError=b0;mn.toFile=nx;var pc=class extends mn{constructor(){super(...arguments),this.completions=new Wf(this),this.messages=new Xl(this),this.models=new Vf(this),this.beta=new fc(this)}};pc.Completions=Wf;pc.Messages=Xl;pc.Models=Vf;pc.Beta=fc;var Ex=Ar(vs(),1);var CZe=[{name:"claude-sonnet-4-5",alias:"BIG",contextWindow:2e5,temperature:.8,maxOutputTokens:64e3,price:{inputMTokens:3,cacheWrite:3.75,cacheRead:.3,outputMTokens:15}},{name:"claude-opus-4-5",alias:"BIGGEST",contextWindow:2e5,temperature:.8,maxOutputTokens:64e3,price:{inputMTokens:15,cacheWrite:18.75,cacheRead:1.5,outputMTokens:75}},{name:"claude-haiku-4-5",alias:"SMALL",contextWindow:2e5,temperature:.8,maxOutputTokens:64e3,price:{inputMTokens:1,cacheWrite:1.25,cacheRead:.1,outputMTokens:5}}],TZe=60,eR=.4,tR=.9,$ie=.5,PZe=5,Sx=class extends l0{constructor(t,n,i){super(n,i);this.interactor=t;this.name="Anthropic",this.mergeModels(CZe)}name;rateLimitInfo=null;async run(t,n){let i=this.isAnthropicReady(),a=this.getModel(t);if(!i||!a)return(0,Ex.of)();n.resetUsageForRun();let o=new Ex.Subject,s=this.startThinkingInterval();return this.processThread(i,t,a,n,o).catch(c=>{o.next(new Ia({error:c}))}).finally(()=>{this.stopThinkingInterval(s),this.showAgentAndUsage(t,"Anthropic",a.name,n);let c=n.usage?.price||0;this.logAgentUsage(t,a.name,c),o.complete()}),o}async processThread(t,n,i,a,o){await this.applyThrottlingDelay();let s=n.systemInstructions.length+n.tools.charLength+20,c=Math.max(i.contextWindow*this.charsPerToken-s,1e4),u,l;try{let p=await this.streamApiCall(t,i,n,a,c,o);u=p.data,l=p.response}catch(p){if(p.status===400&&p.error?.error?.message?.includes("prompt is too long")){this.interactor.displayText("\u26A0\uFE0F Context window exceeded. Forcing aggressive compaction...");let m=p.error.error.message.match(/(\d+) tokens > (\d+) maximum/);if(m){let h=parseInt(m[1]),g=parseInt(m[2]),v=h-g,b=Math.ceil(v*this.charsPerToken*1.2);c=Math.max(c-b,5e3),this.interactor.debug(`Token overshoot: ${v} tokens (${b} chars). Reduced budget to ${c} chars.`)}else c=Math.floor(c*.7),this.interactor.debug(`Reduced budget by 30% to ${c} chars.`);try{let h=await this.streamApiCall(t,i,n,a,c,o,!0);u=h.data,l=h.response,this.interactor.displayText("\u2705 Successfully recovered with compacted context")}catch(h){this.handleError(h,o,this.name);return}}else if(p.status===429&&p.headers){let m=parseInt(p.headers["retry-after"]??"60");this.interactor.displayText(`\u23F3 Rate limit hit. Waiting ${m} seconds before retry...`),this.updateRateLimitsFromHeaders(p.headers),this.displayRateLimitStatus(p.headers);try{await this.delay(m*1e3,"rate limit retry")}catch{this.handleError(new Error("Rate limit retry interrupted by shutdown"),o,this.name);return}this.interactor.displayText("\u{1F504} Retrying request...");try{let h=await this.streamApiCall(t,i,n,a,c,o);u=h.data,l=h.response}catch(h){this.handleError(h,o,this.name);return}}else{this.handleError(p,o,this.name);return}}if(l&&this.updateRateLimitsFromHeaders(l.headers),this.updateUsage(u?.usage,n,a),u.stop_reason==="max_tokens")throw new Error("Max tokens reached for Anthropic \u{1F62C}");let f=u.content.filter(p=>p.type==="text").map(p=>p.text.trim()).filter(p=>!!p).join(`
|
|
348
|
+
`);this.baseURL=a.baseURL,this.timeout=a.timeout??Q$.DEFAULT_TIMEOUT,this.logger=a.logger??console;let o="warn";this.logLevel=o,this.logLevel=R$(a.logLevel,"ClientOptions.logLevel",this)??R$(Q4("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??o,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??aie(),Ze(this,_x,sie,"f"),this._options=a,this.apiKey=t,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(this.apiKey&&e.get("x-api-key"))&&!t.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!t.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return sr([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return sr([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return sr([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([t,n])=>typeof n<"u").map(([t,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(t)}=`;throw new ot(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Zl}`}defaultIdempotencyKey(){return`stainless-node-retry-${T$()}`}makeStatusError(e,t,n,i){return li.generate(e,t,n,i)}buildURL(e,t,n){let i=!he(this,X$,"m",Die).call(this)&&n||this.baseURL,a=Jne(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();return Kne(o)||(t={...o,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(a.search=this.stringifyQuery(t)),a.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new ot("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(i=>({method:e,path:t,...i})))}request(e,t=null){return new Uf(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let i=await e,a=i.maxRetries??this.maxRetries;t==null&&(t=a),await this.prepareOptions(i);let{req:o,url:s,timeout:c}=await this.buildRequest(i,{retryCount:a-t});await this.prepareRequest(o,{url:s,options:i});let u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=n===void 0?"":`, retryOf: ${n}`,f=Date.now();if(fi(this).debug(`[${u}] sending request`,gu({retryOfRequestLogID:n,method:i.method,url:s,options:i,headers:o.headers})),i.signal?.aborted)throw new Di;let d=new AbortController,p=await this.fetchWithTimeout(s,o,c,d).catch($4),m=Date.now();if(p instanceof globalThis.Error){let v=`retrying, ${t} attempts remaining`;if(i.signal?.aborted)throw new Di;let b=hu(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(t)return fi(this).info(`[${u}] connection ${b?"timed out":"failed"} - ${v}`),fi(this).debug(`[${u}] connection ${b?"timed out":"failed"} (${v})`,gu({retryOfRequestLogID:n,url:s,durationMs:m-f,message:p.message})),this.retryRequest(i,t,n??u);throw fi(this).info(`[${u}] connection ${b?"timed out":"failed"} - error; no more retries left`),fi(this).debug(`[${u}] connection ${b?"timed out":"failed"} (error; no more retries left)`,gu({retryOfRequestLogID:n,url:s,durationMs:m-f,message:p.message})),b?new p0:new Vl({cause:p})}let h=[...p.headers.entries()].filter(([v])=>v==="request-id").map(([v,b])=>", "+v+": "+JSON.stringify(b)).join(""),g=`[${u}${l}${h}] ${o.method} ${s} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${m-f}ms`;if(!p.ok){let v=await this.shouldRetry(p);if(t&&v){let $=`retrying, ${t} attempts remaining`;return await oie(p.body),fi(this).info(`${g} - ${$}`),fi(this).debug(`[${u}] response error (${$})`,gu({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:m-f})),this.retryRequest(i,t,n??u,p.headers)}let b=v?"error; no more retries left":"error; not retryable";fi(this).info(`${g} - ${b}`);let x=await p.text().catch($=>$4($).message),k=Yy(x),E=k?void 0:x;throw fi(this).debug(`[${u}] response error (${b})`,gu({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,message:E,durationMs:Date.now()-f})),this.makeStatusError(p.status,k,E,p.headers)}return fi(this).info(g),fi(this).debug(`[${u}] response start`,gu({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:m-f})),{response:p,options:i,controller:d,requestLogID:u,retryOfRequestLogID:n,startTime:f}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new L4(this,n,e)}async fetchWithTimeout(e,t,n,i){let{signal:a,method:o,...s}=t||{};a&&a.addEventListener("abort",()=>i.abort());let c=setTimeout(()=>i.abort(),n),u=globalThis.ReadableStream&&s.body instanceof globalThis.ReadableStream||typeof s.body=="object"&&s.body!==null&&Symbol.asyncIterator in s.body,l={signal:i.signal,...u?{duplex:"half"}:{},method:"GET",...s};o&&(l.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,l)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,i){let a,o=i?.get("retry-after-ms");if(o){let c=parseFloat(o);Number.isNaN(c)||(a=c)}let s=i?.get("retry-after");if(s&&!a){let c=parseFloat(s);Number.isNaN(c)?a=Date.parse(s)-Date.now():a=c*1e3}if(!(a&&0<=a&&a<60*1e3)){let c=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,c)}return await Qne(a),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let a=t-e,o=Math.min(.5*Math.pow(2,a),8),s=1-Math.random()*.25;return o*s*1e3}calculateNonstreamingTimeout(e,t){if(36e5*e/128e3>6e5||t!=null&&e>t)throw new ot("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:i,path:a,query:o,defaultBaseURL:s}=n,c=this.buildURL(a,o,s);"timeout"in n&&Xne("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:u,body:l}=this.buildBody({options:n}),f=await this.buildHeaders({options:e,method:i,bodyHeaders:u,retryCount:t});return{req:{method:i,headers:f,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:i}){let a={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);let o=sr([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...iie(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(o),o.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=sr([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Xy(e)}:he(this,_x,"f").call(this,{body:e,headers:n})}};Q$=mn,_x=new WeakMap,X$=new WeakSet,Die=function(){return this.baseURL!=="https://api.anthropic.com"};mn.Anthropic=Q$;mn.HUMAN_PROMPT=Oie;mn.AI_PROMPT=Iie;mn.DEFAULT_TIMEOUT=6e5;mn.AnthropicError=ot;mn.APIError=li;mn.APIConnectionError=Vl;mn.APIConnectionTimeoutError=p0;mn.APIUserAbortError=Di;mn.NotFoundError=g0;mn.ConflictError=v0;mn.RateLimitError=y0;mn.BadRequestError=d0;mn.AuthenticationError=h0;mn.InternalServerError=x0;mn.PermissionDeniedError=m0;mn.UnprocessableEntityError=b0;mn.toFile=nx;var pc=class extends mn{constructor(){super(...arguments),this.completions=new Wf(this),this.messages=new Xl(this),this.models=new Vf(this),this.beta=new fc(this)}};pc.Completions=Wf;pc.Messages=Xl;pc.Models=Vf;pc.Beta=fc;var Ex=Ar(vs(),1);var CZe=[{name:"claude-sonnet-4-6",alias:"BIG",contextWindow:2e5,temperature:.8,maxOutputTokens:64e3,price:{inputMTokens:3,cacheWrite:3.75,cacheRead:.3,outputMTokens:15}},{name:"claude-opus-4-6",alias:"BIGGEST",contextWindow:2e5,temperature:.8,maxOutputTokens:64e3,price:{inputMTokens:5,cacheWrite:6.25,cacheRead:.5,outputMTokens:25}},{name:"claude-haiku-4-5",alias:"SMALL",contextWindow:2e5,temperature:.8,maxOutputTokens:64e3,price:{inputMTokens:1,cacheWrite:1.25,cacheRead:.1,outputMTokens:5}}],TZe=60,eR=.4,tR=.9,$ie=.5,PZe=5,Sx=class extends l0{constructor(t,n,i){super(n,i);this.interactor=t;this.name="Anthropic",this.mergeModels(CZe)}name;rateLimitInfo=null;async run(t,n){let i=this.isAnthropicReady(),a=this.getModel(t);if(!i||!a)return(0,Ex.of)();n.resetUsageForRun();let o=new Ex.Subject,s=this.startThinkingInterval();return this.processThread(i,t,a,n,o).catch(c=>{o.next(new Ia({error:c}))}).finally(()=>{this.stopThinkingInterval(s),this.showAgentAndUsage(t,"Anthropic",a.name,n);let c=n.usage?.price||0;this.logAgentUsage(t,a.name,c),o.complete()}),o}async processThread(t,n,i,a,o){await this.applyThrottlingDelay();let s=n.systemInstructions.length+n.tools.charLength+20,c=Math.max(i.contextWindow*this.charsPerToken-s,1e4),u,l;try{let p=await this.streamApiCall(t,i,n,a,c,o);u=p.data,l=p.response}catch(p){if(p.status===400&&p.error?.error?.message?.includes("prompt is too long")){this.interactor.displayText("\u26A0\uFE0F Context window exceeded. Forcing aggressive compaction...");let m=p.error.error.message.match(/(\d+) tokens > (\d+) maximum/);if(m){let h=parseInt(m[1]),g=parseInt(m[2]),v=h-g,b=Math.ceil(v*this.charsPerToken*1.2);c=Math.max(c-b,5e3),this.interactor.debug(`Token overshoot: ${v} tokens (${b} chars). Reduced budget to ${c} chars.`)}else c=Math.floor(c*.7),this.interactor.debug(`Reduced budget by 30% to ${c} chars.`);try{let h=await this.streamApiCall(t,i,n,a,c,o,!0);u=h.data,l=h.response,this.interactor.displayText("\u2705 Successfully recovered with compacted context")}catch(h){this.handleError(h,o,this.name);return}}else if(p.status===429&&p.headers){let m=parseInt(p.headers["retry-after"]??"60");this.interactor.displayText(`\u23F3 Rate limit hit. Waiting ${m} seconds before retry...`),this.updateRateLimitsFromHeaders(p.headers),this.displayRateLimitStatus(p.headers);try{await this.delay(m*1e3,"rate limit retry")}catch{this.handleError(new Error("Rate limit retry interrupted by shutdown"),o,this.name);return}this.interactor.displayText("\u{1F504} Retrying request...");try{let h=await this.streamApiCall(t,i,n,a,c,o);u=h.data,l=h.response}catch(h){this.handleError(h,o,this.name);return}}else{this.handleError(p,o,this.name);return}}if(l&&this.updateRateLimitsFromHeaders(l.headers),this.updateUsage(u?.usage,n,a),u.stop_reason==="max_tokens")throw new Error("Max tokens reached for Anthropic \u{1F62C}");let f=u.content.filter(p=>p.type==="text").map(p=>p.text.trim()).filter(p=>!!p).join(`
|
|
349
349
|
`);this.handleText(a,f,n,o);let d=u.content.filter(p=>p.type==="tool_use").map(p=>new $n({toolRequestId:p.id,name:p.name,args:JSON.stringify(p.input)}));await this.shouldProcessAgainAfterResponse(f,d,n,a)&&await this.processThread(t,n,i,a,o)}updateUsage(t,n,i){let a=this.getModel(n),o=(t?.input_tokens??0)*(a?.price?.inputMTokens??0),s=(t?.output_tokens??0)*(a?.price?.outputMTokens??0),c=(t?.cache_creation_input_tokens??0)*(a?.price?.cacheWrite??0),u=(t?.cache_read_input_tokens??0)*(a?.price?.cacheRead??0),l=(o+s+c+u)/1e6;i.addUsage({input:t?.input_tokens??0,output:t?.output_tokens??0,cache_read:t?.cache_read_input_tokens??0,cache_write:t?.cache_creation_input_tokens??0,price:l})}isAnthropicReady(){if(!this.apiKey){this.interactor.warn("ANTHROPIC_API_KEY not set, skipping AI command. Please configure your API key.");return}try{return new pc({apiKey:this.apiKey,defaultHeaders:{"anthropic-beta":"prompt-caching-2024-07-31"}})}catch(t){let n=t instanceof Error?t.message:"Unknown error";this.interactor.warn(`Failed to initialize Anthropic client: ${n}`),console.error("Anthropic client initialization error:",t);return}}toClaudeMessage(t,n,i=!1){let a=this.getOrUpdateCacheMarker(n,t,i);return t.map(o=>{let s,c=a&&o.timestamp===a;if(o instanceof fa)s={role:"user",content:[{type:"text",text:o.summary,...c&&{cache_control:{type:"ephemeral"}}}]};else if(o instanceof yr){let u=o.content,l=u.map((f,d)=>{let p;return f.type==="text"&&(p={type:"text",text:f.content}),f.type==="image"&&(p={type:"image",source:{type:"base64",media_type:f.mimeType,data:f.content}}),p?{...p,...c&&d===u.length-1&&{cache_control:{type:"ephemeral"}}}:(this.interactor.warn(`Unknown content type: ${f.type}`),null)}).filter(Boolean);s={role:o.role,content:l}}if(o instanceof $n&&(s={role:"assistant",content:[{type:"tool_use",id:o.toolRequestId,name:o.name,input:JSON.parse(o.args),...c&&{cache_control:{type:"ephemeral"}}}]}),o instanceof zn){let u;if(typeof o.output=="string")u=o.output;else{let l=o.output;if(l.type==="text")u=[{type:"text",text:l.content}];else if(l.type==="image")u=[{type:"image",source:{type:"base64",media_type:l.mimeType,data:l.content}}];else throw new Error(`Unknown content type: ${l.type}`)}s={role:"user",content:[{type:"tool_result",tool_use_id:o.toolRequestId,content:u,...c&&{cache_control:{type:"ephemeral"}}}]}}else if(o instanceof ua)s={role:"assistant",content:[{type:"text",text:o.invite,...c&&{cache_control:{type:"ephemeral"}}}]};else if(o instanceof la){let u=o.options.map((f,d)=>`${d+1}. ${f}`).join(`
|
|
350
350
|
`);s={role:"assistant",content:[{type:"text",text:o.optionalQuestion?`${o.optionalQuestion}
|
|
351
351
|
${o.invite}
|
|
@@ -699,7 +699,7 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
699
699
|
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
700
700
|
|
|
701
701
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
702
|
-
`);this.baseURL=s.baseURL,this.timeout=s.timeout??kN.DEFAULT_TIMEOUT,this.logger=s.logger??console;let c="warn";this.logLevel=c,this.logLevel=QF(s.logLevel,"ClientOptions.logLevel",this)??QF(S2("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??yle(),it(this,z_,wle,"f"),this._options=s,this.apiKey=typeof t=="string"?t:"Missing Key",this.organization=n,this.project=i,this.webhookSecret=a}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return De([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return YF(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${v2}`}defaultIdempotencyKey(){return`stainless-node-retry-${zF()}`}makeStatusError(e,t,n,i){return Yn.generate(e,t,n,i)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(n){throw n instanceof ze?n:new ze(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof t!="string"||!t)throw new ze(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,n){let i=!se(this,EN,"m",l2e).call(this)&&n||this.baseURL,a=ule(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();return lle(o)||(t={...o,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(a.search=this.stringifyQuery(t)),a.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(i=>({method:e,path:t,...i})))}request(e,t=null){return new mp(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let i=await e,a=i.maxRetries??this.maxRetries;t==null&&(t=a),await this.prepareOptions(i);let{req:o,url:s,timeout:c}=await this.buildRequest(i,{retryCount:a-t});await this.prepareRequest(o,{url:s,options:i});let u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=n===void 0?"":`, retryOf: ${n}`,f=Date.now();if(jn(this).debug(`[${u}] sending request`,Tu({retryOfRequestLogID:n,method:i.method,url:s,options:i,headers:o.headers})),i.signal?.aborted)throw new Hn;let d=new AbortController,p=await this.fetchWithTimeout(s,o,c,d).catch(a6),m=Date.now();if(p instanceof globalThis.Error){let v=`retrying, ${t} attempts remaining`;if(i.signal?.aborted)throw new Hn;let b=i6(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(t)return jn(this).info(`[${u}] connection ${b?"timed out":"failed"} - ${v}`),jn(this).debug(`[${u}] connection ${b?"timed out":"failed"} (${v})`,Tu({retryOfRequestLogID:n,url:s,durationMs:m-f,message:p.message})),this.retryRequest(i,t,n??u);throw jn(this).info(`[${u}] connection ${b?"timed out":"failed"} - error; no more retries left`),jn(this).debug(`[${u}] connection ${b?"timed out":"failed"} (error; no more retries left)`,Tu({retryOfRequestLogID:n,url:s,durationMs:m-f,message:p.message})),b?new g2:new m2({cause:p})}let h=[...p.headers.entries()].filter(([v])=>v==="x-request-id").map(([v,b])=>", "+v+": "+JSON.stringify(b)).join(""),g=`[${u}${l}${h}] ${o.method} ${s} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${m-f}ms`;if(!p.ok){let v=await this.shouldRetry(p);if(t&&v){let $=`retrying, ${t} attempts remaining`;return await xle(p.body),jn(this).info(`${g} - ${$}`),jn(this).debug(`[${u}] response error (${$})`,Tu({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:m-f})),this.retryRequest(i,t,n??u,p.headers)}let b=v?"error; no more retries left":"error; not retryable";jn(this).info(`${g} - ${b}`);let x=await p.text().catch($=>a6($).message),k=dle(x),E=k?void 0:x;throw jn(this).debug(`[${u}] response error (${b})`,Tu({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,message:E,durationMs:Date.now()-f})),this.makeStatusError(p.status,k,E,p.headers)}return jn(this).info(g),jn(this).debug(`[${u}] response start`,Tu({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:m-f})),{response:p,options:i,controller:d,requestLogID:u,retryOfRequestLogID:n,startTime:f}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new f6(this,n,e)}async fetchWithTimeout(e,t,n,i){let{signal:a,method:o,...s}=t||{};a&&a.addEventListener("abort",()=>i.abort());let c=setTimeout(()=>i.abort(),n),u=globalThis.ReadableStream&&s.body instanceof globalThis.ReadableStream||typeof s.body=="object"&&s.body!==null&&Symbol.asyncIterator in s.body,l={signal:i.signal,...u?{duplex:"half"}:{},method:"GET",...s};o&&(l.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,l)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,i){let a,o=i?.get("retry-after-ms");if(o){let c=parseFloat(o);Number.isNaN(c)||(a=c)}let s=i?.get("retry-after");if(s&&!a){let c=parseFloat(s);Number.isNaN(c)?a=Date.parse(s)-Date.now():a=c*1e3}if(!(a&&0<=a&&a<60*1e3)){let c=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,c)}return await wc(a),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let a=t-e,o=Math.min(.5*Math.pow(2,a),8),s=1-Math.random()*.25;return o*s*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:i,path:a,query:o,defaultBaseURL:s}=n,c=this.buildURL(a,o,s);"timeout"in n&&ple("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:u,body:l}=this.buildBody({options:n}),f=await this.buildHeaders({options:e,method:i,bodyHeaders:u,retryCount:t});return{req:{method:i,headers:f,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:i}){let a={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);let o=De([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ble(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(o),o.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=De([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:d_(e)}:se(this,z_,"f").call(this,{body:e,headers:n})}};kN=Ct,z_=new WeakMap,EN=new WeakSet,l2e=function(){return this.baseURL!=="https://api.openai.com/v1"};Ct.OpenAI=kN;Ct.DEFAULT_TIMEOUT=6e5;Ct.OpenAIError=ze;Ct.APIError=Yn;Ct.APIConnectionError=m2;Ct.APIConnectionTimeoutError=g2;Ct.APIUserAbortError=Hn;Ct.NotFoundError=dh;Ct.ConflictError=hh;Ct.RateLimitError=gh;Ct.BadRequestError=lh;Ct.AuthenticationError=fh;Ct.InternalServerError=vh;Ct.PermissionDeniedError=ph;Ct.UnprocessableEntityError=mh;Ct.InvalidWebhookSignatureError=xc;Ct.toFile=__;Ct.Completions=Ep;Ct.Chat=x2;Ct.Embeddings=Ap;Ct.Files=Tp;Ct.Images=Ip;Ct.Audio=kc;Ct.Moderations=Rp;Ct.Models=$p;Ct.FineTuning=Ts;Ct.Graders=T2;Ct.VectorStores=Fu;Ct.Webhooks=Fp;Ct.Beta=Cs;Ct.Batches=yp;Ct.Uploads=D2;Ct.Responses=ju;Ct.Realtime=Ru;Ct.Conversations=A2;Ct.Evals=C2;Ct.Containers=k2;Ct.Videos=jp;var AN=Ar(vs(),1);var snt=[{name:"gpt-5.1",contextWindow:1e6,alias:"BIG",temperature:.8,maxOutputTokens:12e4,price:{inputMTokens:1.25,cacheRead:.125,outputMTokens:10}},{name:"gpt-5-pro",contextWindow:1e6,alias:"BIGGEST",temperature:.8,maxOutputTokens:12e4,price:{inputMTokens:15,cacheRead:0,outputMTokens:120}},{name:"gpt-5-mini",alias:"SMALL",contextWindow:4e5,temperature:1,maxOutputTokens:128e3,price:{inputMTokens:.25,cacheRead:.025,outputMTokens:2}},{name:"gpt-5-nano",contextWindow:4e5,temperature:1,maxOutputTokens:128e3,price:{inputMTokens:.05,cacheRead:.005,outputMTokens:.4}}],e1=class r extends l0{constructor(t,n,i){super(n,i);this.interactor=t;this.mergeModels(snt),n.name.toLowerCase()!=="openai"&&(this.models=n.models??[]),this.name=n.name}name;static MAX_TOOLS=128;truncateToolsIfNeeded(t){return t.length<=r.MAX_TOOLS?t:(this.interactor.warn(`\u26A0\uFE0F OpenAI limits tools to ${r.MAX_TOOLS} maximum. Your agent has ${t.length} tools. Truncating to first ${r.MAX_TOOLS} tools. Consider reducing your integrations or using a shorter tool list for better performance.`),t.slice(0,r.MAX_TOOLS))}async run(t,n){n.resetUsageForRun();let i=this.isOpenaiReady();if(!i)return this.returnError("Client not ready");let a=this.getModel(t);if(!a)return this.returnError(`Model not found for agent ${t.name}`);if(t.definition.openaiAssistantId)return this.runAssistant(t,a,n);let o=new AN.Subject,s=this.startThinkingInterval();return this.processThread(i,t,a,n,o).catch(c=>{o.next(new Ia({error:c}))}).finally(()=>{this.stopThinkingInterval(s),this.showAgentAndUsage(t,this.aiProviderConfig.name,a.name,n);let c=n.usage?.price||0;this.logAgentUsage(t,a.name,c),o.complete()}),o}async runAssistant(t,n,i){let a=this.isOpenaiReady();if(!a)return this.returnError("Client not ready");let o=new AN.Subject;i.data.openai={price:i.data?.openai?.price??0,runPrice:0,assistantThreadData:i.data?.openai?.assistantThreadData??{}};let s=n.contextWindow*this.charsPerToken-t.systemInstructions.length-t.tools.charLength,c=await this.getMessages(i,s,n.name);c.compacted&&(i.data.openai.assistantThreadData={});let u=i.data.openai.assistantThreadData,l=this.startThinkingInterval();if(!u.threadId){let m=await a.beta.threads.create();this.interactor.displayText("Assistant thread created"),u.threadId=m.id}let f=c.messages,d=u.lastTimestamp?f.findIndex(m=>m.timestamp>=u.lastTimestamp):-1,p=f.slice(d+1);return this.updateAssistantThread(a,i,p).then(async()=>await this.processAssistantThread(a,t,n,i,o)).finally(()=>{this.stopThinkingInterval(l),this.showAgentAndUsage(t,this.aiProviderConfig.name,n.name,i);let m=i.usage?.price||0;this.logAgentUsage(t,n.name,m),o.complete()}),o}async processAssistantThread(t,n,i,a,o){let s=t.beta.threads.runs.stream(a.data.openai.assistantThreadData.threadId,{assistant_id:n.definition.openaiAssistantId,tools:this.truncateToolsIfNeeded([...n.tools.getTools(),{type:"file_search"}]),tool_choice:"auto",max_completion_tokens:12e4,max_prompt_tokens:12e4,parallel_tool_calls:!1});await this.processAssistantStream(s,n,i,t,a,o)}async processThread(t,n,i,a,o){try{let s=n.systemInstructions.length+n.tools.charLength+20,c=i.contextWindow*this.charsPerToken-s,u=await this.getMessages(a,c,i.name),l;try{l=await this.streamApiCall(t,i,n,a,u.messages,o)}catch(m){this.interactor.debug(`\u26A0\uFE0F Streaming failed (${m.message}), falling back to non-streaming mode...`),l=await this.nonStreamApiCall(t,i,n,u.messages)}this.updateUsage(l.usage,n,i,a);let f=l.choices[0];if(f.finish_reason==="length")throw new Error("Max tokens reached for Openai \u{1F62C}");let d=f.message.content?.trim();this.handleText(a,d,n,o);let p=f.message?.tool_calls?.filter(m=>m.type==="function").map(m=>new $n({toolRequestId:m.id,name:m.function.name,args:m.function.arguments}));await this.shouldProcessAgainAfterResponse(d,p,n,a)&&await this.processThread(t,n,i,a,o)}catch(s){this.handleError(s,o,this.aiProviderConfig.name)}}async streamApiCall(t,n,i,a,o,s){let c=await t.chat.completions.create({model:n.name,messages:this.toOpenAiMessage(i,o),tools:this.truncateToolsIfNeeded(i.tools.getTools()),max_completion_tokens:i.definition.maxOutputTokens??n.maxOutputTokens??void 0,temperature:i.definition.temperature??n.temperature??.8,stream:!0,stream_options:{include_usage:!0}}),u="",l=[],f=null,d;for await(let m of c){if(!this.shouldProceed(a))throw new Error("Stream interrupted by user");let h=m.choices[0]?.delta;if(h?.content&&(u+=h.content,s.next(new wl({chunk:h.content}))),h?.tool_calls)for(let g of h.tool_calls){let v=g.index;l[v]??={id:g.id||"",type:"function",function:{name:"",arguments:""}},g.id&&(l[v].id=g.id),g.function?.name&&(l[v].function.name+=g.function.name),g.function?.arguments&&(l[v].function.arguments+=g.function.arguments)}m.choices[0]?.finish_reason&&(f=m.choices[0].finish_reason),m.usage&&(d=m.usage)}return{id:"chatcmpl-stream",object:"chat.completion",created:Math.floor(Date.now()/1e3),model:n.name,choices:[{index:0,message:{role:"assistant",content:u||null,refusal:null,tool_calls:l.length>0?l:void 0},logprobs:null,finish_reason:f||"stop"}],usage:d}}async nonStreamApiCall(t,n,i,a){return await t.chat.completions.create({model:n.name,messages:this.toOpenAiMessage(i,a),tools:this.truncateToolsIfNeeded(i.tools.getTools()),max_completion_tokens:i.definition.maxOutputTokens??n.maxOutputTokens??void 0,temperature:i.definition.temperature??n.temperature??.8,stream:!1})}updateUsage(t,n,i,a){let o=t?.prompt_tokens_details?.cached_tokens??0,s=(t?.prompt_tokens??0)-o,c=s*(i?.price?.inputMTokens??0),u=t?.completion_tokens??0,l=u*(i?.price?.outputMTokens??0),f=o*(i?.price?.cacheRead??0),d=(c+l+f)/1e6;a.addUsage({input:s,output:u,cache_read:o,cache_write:0,price:d})}isOpenaiReady(){if(!this.aiProviderConfig.apiKey){this.interactor.warn(`${this.aiProviderConfig.name}_API_KEY not set, skipping AI command. Please configure your API key.`);return}try{return new Ct({apiKey:this.aiProviderConfig.apiKey,baseURL:this.aiProviderConfig.url})}catch(t){let n=t instanceof Error?t.message:"Unknown error";this.interactor.warn(`Failed to initialize ${this.aiProviderConfig.name} client: ${n}`),console.error(`${this.aiProviderConfig.name} client initialization error:`,t);return}}toOpenAiMessage(t,n){let i={content:t.systemInstructions,role:"system"},a=n.flatMap(o=>{if(o instanceof fa)return[{role:"user",content:o.summary}];if(o instanceof yr){let c=o.content.map(u=>{if(u.type==="text")return{type:"text",text:u.content};if(u.type==="image"){let l={type:"image_url",image_url:{url:`data:${u.mimeType};base64,${u.content}`,detail:"auto"}};return console.log("got an image in message event"),l}throw new Error(`Unknown content type: ${u.type}`)});return o.role==="assistant"?[{role:"assistant",content:typeof c=="string"?c:c.map(u=>u.type==="text"?u.text:"[Image]").join(" "),name:t.name}]:[{role:"user",content:c,name:o.name}]}if(o instanceof $n)return[{role:"assistant",name:t.name,tool_calls:[{type:"function",id:o.toolRequestId,function:{name:o.name,arguments:o.args}}]}];if(o instanceof zn){if(typeof o.output=="string")return[{role:"tool",content:o.output,tool_call_id:o.toolRequestId}];{let s=o.output;if(s.type==="image")return[{role:"tool",content:"Image retrieved successfully. See following message.",tool_call_id:o.toolRequestId},{role:"user",content:[{type:"image_url",image_url:{url:`data:${s.mimeType};base64,${s.content}`,detail:"auto"}}],name:"system"}];if(s.type==="text")return[{role:"tool",content:s.content,tool_call_id:o.toolRequestId}];throw new Error(`Unknown content type: ${s.type}`)}}if(o instanceof ua)return[{role:"assistant",content:o.invite,name:t.name}];if(o instanceof la){let s=o.options.map((u,l)=>`${l+1}. ${u}`).join(`
|
|
702
|
+
`);this.baseURL=s.baseURL,this.timeout=s.timeout??kN.DEFAULT_TIMEOUT,this.logger=s.logger??console;let c="warn";this.logLevel=c,this.logLevel=QF(s.logLevel,"ClientOptions.logLevel",this)??QF(S2("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??yle(),it(this,z_,wle,"f"),this._options=s,this.apiKey=typeof t=="string"?t:"Missing Key",this.organization=n,this.project=i,this.webhookSecret=a}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return De([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return YF(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${v2}`}defaultIdempotencyKey(){return`stainless-node-retry-${zF()}`}makeStatusError(e,t,n,i){return Yn.generate(e,t,n,i)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(n){throw n instanceof ze?n:new ze(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof t!="string"||!t)throw new ze(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,n){let i=!se(this,EN,"m",l2e).call(this)&&n||this.baseURL,a=ule(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();return lle(o)||(t={...o,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(a.search=this.stringifyQuery(t)),a.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(i=>({method:e,path:t,...i})))}request(e,t=null){return new mp(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let i=await e,a=i.maxRetries??this.maxRetries;t==null&&(t=a),await this.prepareOptions(i);let{req:o,url:s,timeout:c}=await this.buildRequest(i,{retryCount:a-t});await this.prepareRequest(o,{url:s,options:i});let u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=n===void 0?"":`, retryOf: ${n}`,f=Date.now();if(jn(this).debug(`[${u}] sending request`,Tu({retryOfRequestLogID:n,method:i.method,url:s,options:i,headers:o.headers})),i.signal?.aborted)throw new Hn;let d=new AbortController,p=await this.fetchWithTimeout(s,o,c,d).catch(a6),m=Date.now();if(p instanceof globalThis.Error){let v=`retrying, ${t} attempts remaining`;if(i.signal?.aborted)throw new Hn;let b=i6(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(t)return jn(this).info(`[${u}] connection ${b?"timed out":"failed"} - ${v}`),jn(this).debug(`[${u}] connection ${b?"timed out":"failed"} (${v})`,Tu({retryOfRequestLogID:n,url:s,durationMs:m-f,message:p.message})),this.retryRequest(i,t,n??u);throw jn(this).info(`[${u}] connection ${b?"timed out":"failed"} - error; no more retries left`),jn(this).debug(`[${u}] connection ${b?"timed out":"failed"} (error; no more retries left)`,Tu({retryOfRequestLogID:n,url:s,durationMs:m-f,message:p.message})),b?new g2:new m2({cause:p})}let h=[...p.headers.entries()].filter(([v])=>v==="x-request-id").map(([v,b])=>", "+v+": "+JSON.stringify(b)).join(""),g=`[${u}${l}${h}] ${o.method} ${s} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${m-f}ms`;if(!p.ok){let v=await this.shouldRetry(p);if(t&&v){let $=`retrying, ${t} attempts remaining`;return await xle(p.body),jn(this).info(`${g} - ${$}`),jn(this).debug(`[${u}] response error (${$})`,Tu({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:m-f})),this.retryRequest(i,t,n??u,p.headers)}let b=v?"error; no more retries left":"error; not retryable";jn(this).info(`${g} - ${b}`);let x=await p.text().catch($=>a6($).message),k=dle(x),E=k?void 0:x;throw jn(this).debug(`[${u}] response error (${b})`,Tu({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,message:E,durationMs:Date.now()-f})),this.makeStatusError(p.status,k,E,p.headers)}return jn(this).info(g),jn(this).debug(`[${u}] response start`,Tu({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:m-f})),{response:p,options:i,controller:d,requestLogID:u,retryOfRequestLogID:n,startTime:f}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new f6(this,n,e)}async fetchWithTimeout(e,t,n,i){let{signal:a,method:o,...s}=t||{};a&&a.addEventListener("abort",()=>i.abort());let c=setTimeout(()=>i.abort(),n),u=globalThis.ReadableStream&&s.body instanceof globalThis.ReadableStream||typeof s.body=="object"&&s.body!==null&&Symbol.asyncIterator in s.body,l={signal:i.signal,...u?{duplex:"half"}:{},method:"GET",...s};o&&(l.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,l)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,i){let a,o=i?.get("retry-after-ms");if(o){let c=parseFloat(o);Number.isNaN(c)||(a=c)}let s=i?.get("retry-after");if(s&&!a){let c=parseFloat(s);Number.isNaN(c)?a=Date.parse(s)-Date.now():a=c*1e3}if(!(a&&0<=a&&a<60*1e3)){let c=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,c)}return await wc(a),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let a=t-e,o=Math.min(.5*Math.pow(2,a),8),s=1-Math.random()*.25;return o*s*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:i,path:a,query:o,defaultBaseURL:s}=n,c=this.buildURL(a,o,s);"timeout"in n&&ple("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:u,body:l}=this.buildBody({options:n}),f=await this.buildHeaders({options:e,method:i,bodyHeaders:u,retryCount:t});return{req:{method:i,headers:f,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:i}){let a={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);let o=De([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ble(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(o),o.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=De([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:d_(e)}:se(this,z_,"f").call(this,{body:e,headers:n})}};kN=Ct,z_=new WeakMap,EN=new WeakSet,l2e=function(){return this.baseURL!=="https://api.openai.com/v1"};Ct.OpenAI=kN;Ct.DEFAULT_TIMEOUT=6e5;Ct.OpenAIError=ze;Ct.APIError=Yn;Ct.APIConnectionError=m2;Ct.APIConnectionTimeoutError=g2;Ct.APIUserAbortError=Hn;Ct.NotFoundError=dh;Ct.ConflictError=hh;Ct.RateLimitError=gh;Ct.BadRequestError=lh;Ct.AuthenticationError=fh;Ct.InternalServerError=vh;Ct.PermissionDeniedError=ph;Ct.UnprocessableEntityError=mh;Ct.InvalidWebhookSignatureError=xc;Ct.toFile=__;Ct.Completions=Ep;Ct.Chat=x2;Ct.Embeddings=Ap;Ct.Files=Tp;Ct.Images=Ip;Ct.Audio=kc;Ct.Moderations=Rp;Ct.Models=$p;Ct.FineTuning=Ts;Ct.Graders=T2;Ct.VectorStores=Fu;Ct.Webhooks=Fp;Ct.Beta=Cs;Ct.Batches=yp;Ct.Uploads=D2;Ct.Responses=ju;Ct.Realtime=Ru;Ct.Conversations=A2;Ct.Evals=C2;Ct.Containers=k2;Ct.Videos=jp;var AN=Ar(vs(),1);var snt=[{name:"gpt-5.2",contextWindow:4e5,alias:"BIG",temperature:.8,maxOutputTokens:128e3,price:{inputMTokens:1.75,cacheRead:.175,outputMTokens:14}},{name:"gpt-5-mini",alias:"SMALL",contextWindow:4e5,temperature:1,maxOutputTokens:128e3,price:{inputMTokens:.25,cacheRead:.025,outputMTokens:2}},{name:"gpt-5-nano",contextWindow:4e5,temperature:1,maxOutputTokens:128e3,price:{inputMTokens:.05,cacheRead:.005,outputMTokens:.4}}],e1=class r extends l0{constructor(t,n,i){super(n,i);this.interactor=t;this.mergeModels(snt),n.name.toLowerCase()!=="openai"&&(this.models=n.models??[]),this.name=n.name}name;static MAX_TOOLS=128;truncateToolsIfNeeded(t){return t.length<=r.MAX_TOOLS?t:(this.interactor.warn(`\u26A0\uFE0F OpenAI limits tools to ${r.MAX_TOOLS} maximum. Your agent has ${t.length} tools. Truncating to first ${r.MAX_TOOLS} tools. Consider reducing your integrations or using a shorter tool list for better performance.`),t.slice(0,r.MAX_TOOLS))}async run(t,n){n.resetUsageForRun();let i=this.isOpenaiReady();if(!i)return this.returnError("Client not ready");let a=this.getModel(t);if(!a)return this.returnError(`Model not found for agent ${t.name}`);if(t.definition.openaiAssistantId)return this.runAssistant(t,a,n);let o=new AN.Subject,s=this.startThinkingInterval();return this.processThread(i,t,a,n,o).catch(c=>{o.next(new Ia({error:c}))}).finally(()=>{this.stopThinkingInterval(s),this.showAgentAndUsage(t,this.aiProviderConfig.name,a.name,n);let c=n.usage?.price||0;this.logAgentUsage(t,a.name,c),o.complete()}),o}async runAssistant(t,n,i){let a=this.isOpenaiReady();if(!a)return this.returnError("Client not ready");let o=new AN.Subject;i.data.openai={price:i.data?.openai?.price??0,runPrice:0,assistantThreadData:i.data?.openai?.assistantThreadData??{}};let s=n.contextWindow*this.charsPerToken-t.systemInstructions.length-t.tools.charLength,c=await this.getMessages(i,s,n.name);c.compacted&&(i.data.openai.assistantThreadData={});let u=i.data.openai.assistantThreadData,l=this.startThinkingInterval();if(!u.threadId){let m=await a.beta.threads.create();this.interactor.displayText("Assistant thread created"),u.threadId=m.id}let f=c.messages,d=u.lastTimestamp?f.findIndex(m=>m.timestamp>=u.lastTimestamp):-1,p=f.slice(d+1);return this.updateAssistantThread(a,i,p).then(async()=>await this.processAssistantThread(a,t,n,i,o)).finally(()=>{this.stopThinkingInterval(l),this.showAgentAndUsage(t,this.aiProviderConfig.name,n.name,i);let m=i.usage?.price||0;this.logAgentUsage(t,n.name,m),o.complete()}),o}async processAssistantThread(t,n,i,a,o){let s=t.beta.threads.runs.stream(a.data.openai.assistantThreadData.threadId,{assistant_id:n.definition.openaiAssistantId,tools:this.truncateToolsIfNeeded([...n.tools.getTools(),{type:"file_search"}]),tool_choice:"auto",max_completion_tokens:12e4,max_prompt_tokens:12e4,parallel_tool_calls:!1});await this.processAssistantStream(s,n,i,t,a,o)}async processThread(t,n,i,a,o){try{let s=n.systemInstructions.length+n.tools.charLength+20,c=i.contextWindow*this.charsPerToken-s,u=await this.getMessages(a,c,i.name),l;try{l=await this.streamApiCall(t,i,n,a,u.messages,o)}catch(m){this.interactor.debug(`\u26A0\uFE0F Streaming failed (${m.message}), falling back to non-streaming mode...`),l=await this.nonStreamApiCall(t,i,n,u.messages)}this.updateUsage(l.usage,n,i,a);let f=l.choices[0];if(f.finish_reason==="length")throw new Error("Max tokens reached for Openai \u{1F62C}");let d=f.message.content?.trim();this.handleText(a,d,n,o);let p=f.message?.tool_calls?.filter(m=>m.type==="function").map(m=>new $n({toolRequestId:m.id,name:m.function.name,args:m.function.arguments}));await this.shouldProcessAgainAfterResponse(d,p,n,a)&&await this.processThread(t,n,i,a,o)}catch(s){this.handleError(s,o,this.aiProviderConfig.name)}}async streamApiCall(t,n,i,a,o,s){let c=await t.chat.completions.create({model:n.name,messages:this.toOpenAiMessage(i,o),tools:this.truncateToolsIfNeeded(i.tools.getTools()),max_completion_tokens:i.definition.maxOutputTokens??n.maxOutputTokens??void 0,temperature:i.definition.temperature??n.temperature??.8,stream:!0,stream_options:{include_usage:!0}}),u="",l=[],f=null,d;for await(let m of c){if(!this.shouldProceed(a))throw new Error("Stream interrupted by user");let h=m.choices[0]?.delta;if(h?.content&&(u+=h.content,s.next(new wl({chunk:h.content}))),h?.tool_calls)for(let g of h.tool_calls){let v=g.index;l[v]??={id:g.id||"",type:"function",function:{name:"",arguments:""}},g.id&&(l[v].id=g.id),g.function?.name&&(l[v].function.name+=g.function.name),g.function?.arguments&&(l[v].function.arguments+=g.function.arguments)}m.choices[0]?.finish_reason&&(f=m.choices[0].finish_reason),m.usage&&(d=m.usage)}return{id:"chatcmpl-stream",object:"chat.completion",created:Math.floor(Date.now()/1e3),model:n.name,choices:[{index:0,message:{role:"assistant",content:u||null,refusal:null,tool_calls:l.length>0?l:void 0},logprobs:null,finish_reason:f||"stop"}],usage:d}}async nonStreamApiCall(t,n,i,a){return await t.chat.completions.create({model:n.name,messages:this.toOpenAiMessage(i,a),tools:this.truncateToolsIfNeeded(i.tools.getTools()),max_completion_tokens:i.definition.maxOutputTokens??n.maxOutputTokens??void 0,temperature:i.definition.temperature??n.temperature??.8,stream:!1})}updateUsage(t,n,i,a){let o=t?.prompt_tokens_details?.cached_tokens??0,s=(t?.prompt_tokens??0)-o,c=s*(i?.price?.inputMTokens??0),u=t?.completion_tokens??0,l=u*(i?.price?.outputMTokens??0),f=o*(i?.price?.cacheRead??0),d=(c+l+f)/1e6;a.addUsage({input:s,output:u,cache_read:o,cache_write:0,price:d})}isOpenaiReady(){if(!this.aiProviderConfig.apiKey){this.interactor.warn(`${this.aiProviderConfig.name}_API_KEY not set, skipping AI command. Please configure your API key.`);return}try{return new Ct({apiKey:this.aiProviderConfig.apiKey,baseURL:this.aiProviderConfig.url})}catch(t){let n=t instanceof Error?t.message:"Unknown error";this.interactor.warn(`Failed to initialize ${this.aiProviderConfig.name} client: ${n}`),console.error(`${this.aiProviderConfig.name} client initialization error:`,t);return}}toOpenAiMessage(t,n){let i={content:t.systemInstructions,role:"system"},a=n.flatMap(o=>{if(o instanceof fa)return[{role:"user",content:o.summary}];if(o instanceof yr){let c=o.content.map(u=>{if(u.type==="text")return{type:"text",text:u.content};if(u.type==="image"){let l={type:"image_url",image_url:{url:`data:${u.mimeType};base64,${u.content}`,detail:"auto"}};return console.log("got an image in message event"),l}throw new Error(`Unknown content type: ${u.type}`)});return o.role==="assistant"?[{role:"assistant",content:typeof c=="string"?c:c.map(u=>u.type==="text"?u.text:"[Image]").join(" "),name:t.name}]:[{role:"user",content:c,name:o.name}]}if(o instanceof $n)return[{role:"assistant",name:t.name,tool_calls:[{type:"function",id:o.toolRequestId,function:{name:o.name,arguments:o.args}}]}];if(o instanceof zn){if(typeof o.output=="string")return[{role:"tool",content:o.output,tool_call_id:o.toolRequestId}];{let s=o.output;if(s.type==="image")return[{role:"tool",content:"Image retrieved successfully. See following message.",tool_call_id:o.toolRequestId},{role:"user",content:[{type:"image_url",image_url:{url:`data:${s.mimeType};base64,${s.content}`,detail:"auto"}}],name:"system"}];if(s.type==="text")return[{role:"tool",content:s.content,tool_call_id:o.toolRequestId}];throw new Error(`Unknown content type: ${s.type}`)}}if(o instanceof ua)return[{role:"assistant",content:o.invite,name:t.name}];if(o instanceof la){let s=o.options.map((u,l)=>`${l+1}. ${u}`).join(`
|
|
703
703
|
`);return[{role:"assistant",content:o.optionalQuestion?`${o.optionalQuestion}
|
|
704
704
|
${o.invite}
|
|
705
705
|
${s}`:`${o.invite}
|
|
@@ -713,7 +713,7 @@ ${s}`,name:t.name}]}if(o instanceof Hr)return[{role:"user",content:o.answer}];th
|
|
|
713
713
|
`);return{role:"assistant",content:t.optionalQuestion?`${t.optionalQuestion}
|
|
714
714
|
${t.invite}
|
|
715
715
|
${n}`:`${t.invite}
|
|
716
|
-
${n}`}}if(t instanceof Hr)return{role:"user",content:t.answer};throw new Error(`Unknown message type: ${t.type}`)}async processAssistantStream(t,n,i,a,o,s){try{t.on("textDone",c=>{o.data.openai.assistantThreadData.lastTimestamp=this.handleText(o,c.value,n,s)});for await(let c of t){if(this.interactor.thinking(),c.event==="thread.run.completed"){let u=c.data;this.updateUsage(u?.usage,n,i,o)}if(c.event==="thread.run.requires_action")try{let u=c.data.required_action?.submit_tool_outputs.tool_calls?.filter(d=>d.type==="function").map(d=>new $n({toolRequestId:d.id,name:d.function.name,args:d.function.arguments}))??[],l=[];await Promise.all(u.map(async d=>{let p;try{this.interactor.sendEvent(d),p=await n.tools.run(d)}catch(m){let h=`Error running tool ${d.name}: ${m}`;console.error(h),p=d.buildResponse(h)}this.interactor.sendEvent(p),o.addToolRequests(n.name,[d]),o.addToolResponseEvents([p]),l.push({tool_call_id:d.toolRequestId,output:p.getTextOutput()})}));let f=a.beta.threads.runs.submitToolOutputsStream(o.data.openai.assistantThreadData.threadId,{tool_outputs:l,thread_id:o.data.op.assistantThreadData.threadId});if(!this.shouldProceed(o))return;await this.processAssistantStream.call(this,f,n,i,a,o,s)}catch(u){console.error("Error processing tool call",u);let l=u instanceof Error?u.message:"Unknown error";this.interactor.displayText(`\u26A0\uFE0F Error processing tool call: ${l}`),s.next(new Ia({error:new Error(`Error processing OpenAI assistant tool call: ${l}`)}))}}}catch(c){this.handleError(c,s,this.aiProviderConfig.name)}}async complete(t,n){let i=this.isOpenaiReady();if(!i)throw new Error("OpenAI client not ready");let a=n?.model||this.models.find(o=>o.alias==="SMALL")?.name||"gpt-4o-mini";try{return(await i.chat.completions.create({model:a,messages:[{role:"user",content:t}],max_completion_tokens:n?.maxTokens??100,temperature:1})).choices[0]?.message?.content?.trim()||""}catch(o){throw console.error("OpenAI completion error:",o),new Error(`OpenAI completion failed: ${o.message}`)}}};var U_=class extends e1{models=[{name:"gemini-3-pro-preview",contextWindow:1048576,alias:"BIG",temperature:.8,maxOutputTokens:65536,price:{inputMTokens:2,cacheRead:.2,outputMTokens:12}},{name:"gemini-
|
|
716
|
+
${n}`}}if(t instanceof Hr)return{role:"user",content:t.answer};throw new Error(`Unknown message type: ${t.type}`)}async processAssistantStream(t,n,i,a,o,s){try{t.on("textDone",c=>{o.data.openai.assistantThreadData.lastTimestamp=this.handleText(o,c.value,n,s)});for await(let c of t){if(this.interactor.thinking(),c.event==="thread.run.completed"){let u=c.data;this.updateUsage(u?.usage,n,i,o)}if(c.event==="thread.run.requires_action")try{let u=c.data.required_action?.submit_tool_outputs.tool_calls?.filter(d=>d.type==="function").map(d=>new $n({toolRequestId:d.id,name:d.function.name,args:d.function.arguments}))??[],l=[];await Promise.all(u.map(async d=>{let p;try{this.interactor.sendEvent(d),p=await n.tools.run(d)}catch(m){let h=`Error running tool ${d.name}: ${m}`;console.error(h),p=d.buildResponse(h)}this.interactor.sendEvent(p),o.addToolRequests(n.name,[d]),o.addToolResponseEvents([p]),l.push({tool_call_id:d.toolRequestId,output:p.getTextOutput()})}));let f=a.beta.threads.runs.submitToolOutputsStream(o.data.openai.assistantThreadData.threadId,{tool_outputs:l,thread_id:o.data.op.assistantThreadData.threadId});if(!this.shouldProceed(o))return;await this.processAssistantStream.call(this,f,n,i,a,o,s)}catch(u){console.error("Error processing tool call",u);let l=u instanceof Error?u.message:"Unknown error";this.interactor.displayText(`\u26A0\uFE0F Error processing tool call: ${l}`),s.next(new Ia({error:new Error(`Error processing OpenAI assistant tool call: ${l}`)}))}}}catch(c){this.handleError(c,s,this.aiProviderConfig.name)}}async complete(t,n){let i=this.isOpenaiReady();if(!i)throw new Error("OpenAI client not ready");let a=n?.model||this.models.find(o=>o.alias==="SMALL")?.name||"gpt-4o-mini";try{return(await i.chat.completions.create({model:a,messages:[{role:"user",content:t}],max_completion_tokens:n?.maxTokens??100,temperature:1})).choices[0]?.message?.content?.trim()||""}catch(o){throw console.error("OpenAI completion error:",o),new Error(`OpenAI completion failed: ${o.message}`)}}};var U_=class extends e1{models=[{name:"gemini-3-pro-preview",contextWindow:1048576,alias:"BIG",temperature:.8,maxOutputTokens:65536,price:{inputMTokens:2,cacheRead:.2,outputMTokens:12}},{name:"gemini-3-flash-preview",alias:"SMALL",contextWindow:1048576,temperature:.8,maxOutputTokens:65536,price:{inputMTokens:.5,cacheRead:.05,outputMTokens:3}},{name:"gemini-2.5-pro",contextWindow:1048576,temperature:.8,maxOutputTokens:65536,price:{inputMTokens:1.25,cacheRead:.125,outputMTokens:10}},{name:"gemini-2.5-flash",contextWindow:1048576,temperature:.8,maxOutputTokens:65536,price:{inputMTokens:.3,cacheRead:.03,outputMTokens:2.5}}];constructor(e,t,n){let i={...t,url:t.url||"https://generativelanguage.googleapis.com/v1beta/openai/"};super(e,i,n)}};var Wn=class extends Fe{constructor(t,n){super(t);this.interactor=n}handlers=[];async handle(t,n){let i=this.getSubCommand(t),a=this.handlers.find(o=>o.accept(i,n));return a?a.handle(i,n):i.trim().length>0?(this.displayHelp(i),n):this.handleInteractiveSelection(n)}async handleInteractiveSelection(t){let n=this.buildHelpText();this.interactor.displayText(n);let i=this.handlers.filter(u=>!u.isInternal),a=new Map,o=i.map(u=>{let l=u.description.split(`
|
|
717
717
|
`)[0],f=`${u.commandWord}: ${l}`;return a.set(f,u.commandWord),f});o.push("exit: Cancel and return"),a.set("exit: Cancel and return","exit");let s=await this.interactor.chooseOption(o,"Select a command:","Enter your choice"),c=a.get(s);return!c||c==="exit"?t:this.handle(`${this.commandWord} ${c}`,t)}buildHelpText(t){let n=[];return t&&n.push(`Sub-command '${t}' not understood.`),n.push("Available commands:"),[...this.handlers].filter(a=>!a.isInternal).sort((a,o)=>a.commandWord.localeCompare(o.commandWord)).forEach(a=>{let o=a.description.split(`
|
|
718
718
|
`).map((s,c)=>c===0?s:` ${s}`).join(`
|
|
719
719
|
`);n.push(` - ${a.commandWord}: ${o}`)}),n.join(`
|