kaibanjs
Version:
AI Multi-Agent library for Javascript Developers.
1 lines • 1.56 MB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("uuid")):"function"==typeof define&&define.amd?define(["exports","uuid"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).KaibanJS={},e.uuid)}(this,(function(e,t){"use strict";function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var r=n(t);const o="0.37.0";let a,s,i,u,l,c,d=!1;let p=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};a||function(e,t={auto:!1}){if(d)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${e.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(a)throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${e.kind}'\` after \`import '@anthropic-ai/sdk/shims/${a}'\``);d=t.auto,a=e.kind,s=e.fetch,i=e.File,u=e.ReadableStream,l=e.getDefaultAgent,c=e.fileFromPath}(function({manuallyImported:e}={}){const t=e?"You may need to use polyfills":"Add one of these imports before your first `import … from '@anthropic-ai/sdk'`:\n- `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)\n- `import '@anthropic-ai/sdk/shims/web'` (otherwise)\n";let n,r,o,a;try{n=fetch,r=Request,o=Response,a=Headers}catch(e){throw new Error(`this environment is missing the following Web Fetch API type: ${e.message}. ${t}`)}return{kind:"web",fetch:n,Request:r,Response:o,Headers:a,FormData:"undefined"!=typeof FormData?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${t}`)}},Blob:"undefined"!=typeof Blob?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${t}`)}},File:"undefined"!=typeof File?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${t}`)}},ReadableStream:"undefined"!=typeof ReadableStream?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${t}`)}},getMultipartRequestOptions:async(e,t)=>({...t,body:new p(e)}),getDefaultAgent:e=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads")},isFsReadStream:e=>!1}}(),{auto:!0});class h extends Error{}let f=class e extends h{constructor(t,n,r,o){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=o,this.request_id=o?.["request-id"],this.error=n}static makeMessage(e,t,n){const r=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(t,n,r,o){if(!t||!o)return new b({message:r,cause:ie(n)});const a=n;return 400===t?new y(t,a,r,o):401===t?new _(t,a,r,o):403===t?new v(t,a,r,o):404===t?new S(t,a,r,o):409===t?new w(t,a,r,o):422===t?new O(t,a,r,o):429===t?new T(t,a,r,o):t>=500?new $(t,a,r,o):new e(t,a,r,o)}},m=class extends f{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},b=class extends f{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},g=class extends b{constructor({message:e}={}){super({message:e??"Request timed out."})}},y=class extends f{},_=class extends f{},v=class extends f{},S=class extends f{},w=class extends f{},O=class extends f{},T=class extends f{},$=class extends f{};var k,C=function(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n},j=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};let P=class{constructor(){k.set(this,void 0),this.buffer=new Uint8Array,C(this,k,null,"f")}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?(new TextEncoder).encode(e):e;let n=new Uint8Array(this.buffer.length+t.length);n.set(this.buffer),n.set(t,this.buffer.length),this.buffer=n;const r=[];let o;for(;null!=(o=R(this.buffer,j(this,k,"f")));){if(o.carriage&&null==j(this,k,"f")){C(this,k,o.index,"f");continue}if(null!=j(this,k,"f")&&(o.index!==j(this,k,"f")+1||o.carriage)){r.push(this.decodeText(this.buffer.slice(0,j(this,k,"f")-1))),this.buffer=this.buffer.slice(j(this,k,"f")),C(this,k,null,"f");continue}const e=null!==j(this,k,"f")?o.preceding-1:o.preceding,t=this.decodeText(this.buffer.slice(0,e));r.push(t),this.buffer=this.buffer.slice(o.index),C(this,k,null,"f")}return r}decodeText(e){if(null==e)return"";if("string"==typeof e)return e;if("undefined"!=typeof Buffer){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new h(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new h(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new h("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode("\n"):[]}};function R(e,t){for(let n=t??0;n<e.length;n++){if(10===e[n])return{preceding:n,index:n+1,carriage:!1};if(13===e[n])return{preceding:n,index:n+1,carriage:!0}}return null}function I(e){for(let t=0;t<e.length-1;t++){if(10===e[t]&&10===e[t+1])return t+2;if(13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return-1}function A(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}k=new WeakMap,P.NEWLINE_CHARS=new Set(["\n","\r"]),P.NEWLINE_REGEXP=/\r\n|[\n\r]/g;let E=class e{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(t,n){let r=!1;return new e((async function*(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let e=!1;try{for await(const e of async function*(e,t){if(!e.body)throw t.abort(),new h("Attempted to iterate over a response with no body");const n=new M,r=new P,o=A(e.body);for await(const e of async function*(e){let t=new Uint8Array;for await(const n of e){if(null==n)continue;const e=n instanceof ArrayBuffer?new Uint8Array(n):"string"==typeof n?(new TextEncoder).encode(n):n;let r,o=new Uint8Array(t.length+e.length);for(o.set(t),o.set(e,t.length),t=o;-1!==(r=I(t));)yield t.slice(0,r),t=t.slice(r)}t.length>0&&(yield t)}(o))for(const t of r.decode(e)){const e=n.decode(t);e&&(yield e)}for(const e of r.flush()){const t=n.decode(e);t&&(yield t)}}(t,n)){if("completion"===e.event)try{yield JSON.parse(e.data)}catch(t){throw console.error("Could not parse message into JSON:",e.data),console.error("From chunk:",e.raw),t}if("message_start"===e.event||"message_delta"===e.event||"message_stop"===e.event||"content_block_start"===e.event||"content_block_delta"===e.event||"content_block_stop"===e.event)try{yield JSON.parse(e.data)}catch(t){throw console.error("Could not parse message into JSON:",e.data),console.error("From chunk:",e.raw),t}if("ping"!==e.event&&"error"===e.event)throw f.generate(void 0,`SSE Error: ${e.data}`,e.data,G(t.headers))}e=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{e||n.abort()}}),n)}static fromReadableStream(t,n){let r=!1;return new e((async function*(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let e=!1;try{for await(const n of async function*(){const e=new P,n=A(t);for await(const t of n)for(const n of e.decode(t))yield n;for(const t of e.flush())yield t}())e||n&&(yield JSON.parse(n));e=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{e||n.abort()}}),n)}[Symbol.asyncIterator](){return this.iterator()}tee(){const t=[],n=[],r=this.iterator(),o=e=>({next:()=>{if(0===e.length){const e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e((()=>o(t)),this.controller),new e((()=>o(n)),this.controller)]}toReadableStream(){const e=this;let t;const n=new TextEncoder;return new u({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:r,done:o}=await t.next();if(o)return e.close();const a=n.encode(JSON.stringify(r)+"\n");e.enqueue(a)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}};let M=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;const e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,r]=function(e,t){const n=e.indexOf(t);if(-1!==n)return[e.substring(0,n),t,e.substring(n+t.length)];return[e,"",""]}(e,":");return r.startsWith(" ")&&(r=r.substring(1)),"event"===t?this.event=r:"data"===t&&this.data.push(r),null}};const x=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;const N=e=>"string"==typeof e?e:"undefined"!=typeof Buffer&&e instanceof Buffer?String(e):void 0,F=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],L=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag];var D,J=function(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n},U=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};async function q(e){const{response:t}=e;if(e.options.stream)return pe("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):E.fromSSEResponse(t,e.controller);if(204===t.status)return null;if(e.options.__binaryResponse)return t;const n=t.headers.get("content-type");if(n?.includes("application/json")||n?.includes("application/vnd.api+json")){const e=await t.json();return pe("response",t.status,t.url,t.headers,e),B(e,t)}const r=await t.text();return pe("response",t.status,t.url,t.headers,r),r}function B(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("request-id"),enumerable:!1})}let Z=class e extends Promise{constructor(e,t=q){super((e=>{e(null)})),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(t){return new e(this.responsePromise,(async e=>B(t(await this.parseResponse(e),e),e.response)))}asResponse(){return this.responsePromise.then((e=>e.response))}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}},z=class{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:r,fetch:o}){this.baseURL=e,this.maxRetries=se("maxRetries",t),this.timeout=se("timeout",n),this.httpAgent=r,this.fetch=o??s}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...te(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${he()}`}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((async n=>{const r=n&&x(n?.body)?new DataView(await n.body.arrayBuffer()):n?.body instanceof DataView?n.body:n?.body instanceof ArrayBuffer?new DataView(n.body):n&&ArrayBuffer.isView(n?.body)?new DataView(n.body.buffer):n?.body;return{method:e,path:t,...n,body:r}})))}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}calculateContentLength(e){if("string"==typeof e){if("undefined"!=typeof Buffer)return Buffer.byteLength(e,"utf8").toString();if("undefined"!=typeof TextEncoder){return(new TextEncoder).encode(e).length.toString()}}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){e={...e};const{method:n,path:r,query:o,headers:a={}}=e,s=ArrayBuffer.isView(e.body)||e.__binaryRequest&&"string"==typeof e.body?e.body:L(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,i=this.calculateContentLength(s),u=this.buildURL(r,o);"timeout"in e&&se("timeout",e.timeout),e.timeout=e.timeout??this.timeout;const c=e.httpAgent??this.httpAgent??l(u),d=e.timeout+1e3;"number"==typeof c?.options?.timeout&&d>(c.options.timeout??0)&&(c.options.timeout=d),this.idempotencyHeader&&"get"!==n&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);return{req:{method:n,...s&&{body:s},headers:this.buildHeaders({options:e,headers:a,contentLength:i,retryCount:t}),...c&&{agent:c},signal:e.signal??null},url:u,timeout:e.timeout}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:r}){const o={};n&&(o["content-length"]=n);const s=this.defaultHeaders(e);return de(o,s),de(o,t),L(e.body)&&"node"!==a&&delete o["content-type"],void 0===fe(s,"x-stainless-retry-count")&&void 0===fe(t,"x-stainless-retry-count")&&(o["x-stainless-retry-count"]=String(r)),void 0===fe(s,"x-stainless-timeout")&&void 0===fe(t,"x-stainless-timeout")&&e.timeout&&(o["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(o,t),o}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new h("Streaming is strongly recommended for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details");return 6e5}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map((e=>[...e]))):{...e}:{}}makeStatusError(e,t,n,r){return f.generate(e,t,n,r)}request(e,t=null){return new Z(this.makeRequest(e,t))}async makeRequest(e,t){const n=await e,r=n.maxRetries??this.maxRetries;null==t&&(t=r),await this.prepareOptions(n);const{req:o,url:a,timeout:s}=this.buildRequest(n,{retryCount:r-t});if(await this.prepareRequest(o,{url:a,options:n}),pe("request",a,n,o.headers),n.signal?.aborted)throw new m;const i=new AbortController,u=await this.fetchWithTimeout(a,o,s,i).catch(ie);if(u instanceof Error){if(n.signal?.aborted)throw new m;if(t)return this.retryRequest(n,t);if("AbortError"===u.name)throw new g;throw new b({cause:u})}const l=G(u.headers);if(!u.ok){if(t&&this.shouldRetry(u)){return pe(`response (error; ${`retrying, ${t} attempts remaining`})`,u.status,a,l),this.retryRequest(n,t,l)}const e=await u.text().catch((e=>ie(e).message)),r=ne(e),o=r?void 0:e;pe(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,u.status,a,l,o);throw this.makeStatusError(u.status,r,o,l)}return{response:u,options:n,controller:i}}requestAPIList(e,t){const n=this.makeRequest(t,null);return new H(this,n,e)}buildURL(e,t){const n=oe(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),r=this.defaultQuery();return le(r)||(t={...r,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(n.search=this.stringifyQuery(t)),n.toString()}stringifyQuery(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new h(`Cannot stringify type ${typeof t}; 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("&")}async fetchWithTimeout(e,t,n,r){const{signal:o,...a}=t||{};o&&o.addEventListener("abort",(()=>r.abort()));const s=setTimeout((()=>r.abort()),n),i={signal:r.signal,...a};i.method&&(i.method=i.method.toUpperCase());const u=setTimeout((()=>{if(i&&i?.agent?.sockets)for(const e of Object.values(i?.agent?.sockets).flat())e?.setKeepAlive&&e.setKeepAlive(!0,6e4)}),6e4);return this.fetch.call(void 0,e,i).finally((()=>{clearTimeout(s),clearTimeout(u)}))}shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,n){let r;const o=n?.["retry-after-ms"];if(o){const e=parseFloat(o);Number.isNaN(e)||(r=e)}const a=n?.["retry-after"];if(a&&!r){const e=parseFloat(a);r=Number.isNaN(e)?Date.parse(a)-Date.now():1e3*e}if(!(r&&0<=r&&r<6e4)){const n=e.maxRetries??this.maxRetries;r=this.calculateDefaultRetryTimeoutMillis(t,n)}return await ae(r),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const n=t-e;return Math.min(.5*Math.pow(2,n),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${o}`}},K=class{constructor(e,t,n,r){D.set(this,void 0),J(this,D,e,"f"),this.options=r,this.response=t,this.body=n}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new h("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e&&"object"==typeof t.query)t.query={...t.query,...e.params};else if("url"in e){const n=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[t,r]of n)e.url.searchParams.set(t,r);t.query=void 0,t.path=e.url.toString()}return await U(this,D,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(D=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}},H=class extends Z{constructor(e,t,n){super(t,(async t=>new n(e,t.response,await q(t),t.options)))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}};const G=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){const n=t.toString();return e[n.toLowerCase()]||e[n]}}),W={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},V=e=>"object"==typeof e&&null!==e&&!le(e)&&Object.keys(e).every((e=>ce(W,e))),X=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":o,"X-Stainless-OS":Q(Deno.build.os),"X-Stainless-Arch":Y(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":o,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":o,"X-Stainless-OS":Q(process.platform),"X-Stainless-Arch":Y(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const e=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{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(const{key:t,pattern:n}of e){const e=n.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":o,"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":o,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const Y=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",Q=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let ee;const te=()=>ee??(ee=X()),ne=e=>{try{return JSON.parse(e)}catch(e){return}},re=/^[a-z][a-z0-9+.-]*:/i,oe=e=>re.test(e),ae=e=>new Promise((t=>setTimeout(t,e))),se=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new h(`${e} must be an integer`);if(t<0)throw new h(`${e} must be a positive integer`);return t},ie=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e)try{return new Error(JSON.stringify(e))}catch{}return new Error(String(e))},ue=e=>"undefined"!=typeof process?process.env?.[e]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e)?.trim():void 0;function le(e){if(!e)return!0;for(const t in e)return!1;return!0}function ce(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function de(e,t){for(const n in t){if(!ce(t,n))continue;const r=n.toLowerCase();if(!r)continue;const o=t[n];null===o?delete e[r]:void 0!==o&&(e[r]=o)}}function pe(e,...t){"undefined"!=typeof process&&"true"===process?.env?.DEBUG&&console.log(`Anthropic:DEBUG:${e}`,...t)}const he=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),fe=(e,t)=>{const n=t.toLowerCase();if((e=>"function"==typeof e?.get)(e)){const r=t[0]?.toUpperCase()+t.substring(1).replace(/([^\w])(\w)/g,((e,t,n)=>t+n.toUpperCase()));for(const o of[t,n,t.toUpperCase(),r]){const t=e.get(o);if(t)return t}}for(const[r,o]of Object.entries(e))if(r.toLowerCase()===n)return Array.isArray(o)?(o.length<=1||console.warn(`Received ${o.length} entries for the ${t} header, using the first entry.`),o[0]):o};let me=class extends K{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){if(this.options.query?.before_id){const e=this.first_id;return e?{params:{before_id:e}}:null}const e=this.last_id;return e?{params:{after_id:e}}:null}},be=class{constructor(e){this._client=e}},ge=class extends be{retrieve(e,t){return this._client.get(`/v1/models/${e}?beta=true`,t)}list(e={},t){return V(e)?this.list({},e):this._client.getAPIList("/v1/models?beta=true",ye,{query:e,...t})}};class ye extends me{}ge.BetaModelInfosPage=ye;class _e{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new P;for await(const t of this.iterator)for(const n of e.decode(t))yield JSON.parse(n);for(const t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),new h("Attempted to iterate over a response with no body");return new _e(A(e.body),t)}}let ve=class extends be{create(e,t){const{betas:n,...r}=e;return this._client.post("/v1/messages/batches?beta=true",{body:r,...t,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}retrieve(e,t={},n){if(V(t))return this.retrieve(e,{},t);const{betas:r}=t;return this._client.get(`/v1/messages/batches/${e}?beta=true`,{...n,headers:{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}list(e={},t){if(V(e))return this.list({},e);const{betas:n,...r}=e;return this._client.getAPIList("/v1/messages/batches?beta=true",Se,{query:r,...t,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}delete(e,t={},n){if(V(t))return this.delete(e,{},t);const{betas:r}=t;return this._client.delete(`/v1/messages/batches/${e}?beta=true`,{...n,headers:{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}cancel(e,t={},n){if(V(t))return this.cancel(e,{},t);const{betas:r}=t;return this._client.post(`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}async results(e,t={},n){if(V(t))return this.results(e,{},t);const r=await this.retrieve(e);if(!r.results_url)throw new h(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);const{betas:o}=t;return this._client.get(r.results_url,{...n,headers:{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...n?.headers},__binaryResponse:!0})._thenUnwrap(((e,t)=>_e.fromResponse(t.response,t.controller)))}};class Se extends me{}ve.BetaMessageBatchesPage=Se;const we=e=>{if(0===e.length)return e;let t=e[e.length-1];switch(t.type){case"separator":return e=e.slice(0,e.length-1),we(e);case"number":let n=t.value[t.value.length-1];if("."===n||"-"===n)return e=e.slice(0,e.length-1),we(e);case"string":let r=e[e.length-2];if("delimiter"===r?.type)return e=e.slice(0,e.length-1),we(e);if("brace"===r?.type&&"{"===r.value)return e=e.slice(0,e.length-1),we(e);break;case"delimiter":return e=e.slice(0,e.length-1),we(e)}return e},Oe=e=>JSON.parse((e=>{let t="";return e.map((e=>{"string"===e.type?t+='"'+e.value+'"':t+=e.value})),t})((e=>{let t=[];return e.map((e=>{"brace"===e.type&&("{"===e.value?t.push("}"):t.splice(t.lastIndexOf("}"),1)),"paren"===e.type&&("["===e.value?t.push("]"):t.splice(t.lastIndexOf("]"),1))})),t.length>0&&t.reverse().map((t=>{"}"===t?e.push({type:"brace",value:"}"}):"]"===t&&e.push({type:"paren",value:"]"})})),e})(we((e=>{let t=0,n=[];for(;t<e.length;){let r=e[t];if("\\"===r){t++;continue}if("{"===r){n.push({type:"brace",value:"{"}),t++;continue}if("}"===r){n.push({type:"brace",value:"}"}),t++;continue}if("["===r){n.push({type:"paren",value:"["}),t++;continue}if("]"===r){n.push({type:"paren",value:"]"}),t++;continue}if(":"===r){n.push({type:"separator",value:":"}),t++;continue}if(","===r){n.push({type:"delimiter",value:","}),t++;continue}if('"'===r){let o="",a=!1;for(r=e[++t];'"'!==r;){if(t===e.length){a=!0;break}if("\\"===r){if(t++,t===e.length){a=!0;break}o+=r+e[t],r=e[++t]}else o+=r,r=e[++t]}r=e[++t],a||n.push({type:"string",value:o});continue}if(r&&/\s/.test(r)){t++;continue}let o=/[0-9]/;if(r&&o.test(r)||"-"===r||"."===r){let a="";for("-"===r&&(a+=r,r=e[++t]);r&&o.test(r)||"."===r;)a+=r,r=e[++t];n.push({type:"number",value:a});continue}let a=/[a-z]/i;if(r&&a.test(r)){let o="";for(;r&&a.test(r)&&t!==e.length;)o+=r,r=e[++t];if("true"!=o&&"false"!=o&&"null"!==o){t++;continue}n.push({type:"name",value:o})}else t++}return n})(e)))));var Te,$e,ke,Ce,je,Pe,Re,Ie,Ae,Ee,Me,xe,Ne,Fe,Le,De,Je,Ue,qe,Be,Ze,ze,Ke=function(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n},He=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};const Ge="__json_buf";class We{constructor(){Te.add(this),this.messages=[],this.receivedMessages=[],$e.set(this,void 0),this.controller=new AbortController,ke.set(this,void 0),Ce.set(this,(()=>{})),je.set(this,(()=>{})),Pe.set(this,void 0),Re.set(this,(()=>{})),Ie.set(this,(()=>{})),Ae.set(this,{}),Ee.set(this,!1),Me.set(this,!1),xe.set(this,!1),Ne.set(this,!1),Fe.set(this,void 0),Le.set(this,void 0),Ue.set(this,(e=>{if(Ke(this,Me,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new m),e instanceof m)return Ke(this,xe,!0,"f"),this._emit("abort",e);if(e instanceof h)return this._emit("error",e);if(e instanceof Error){const t=new h(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new h(String(e)))})),Ke(this,ke,new Promise(((e,t)=>{Ke(this,Ce,e,"f"),Ke(this,je,t,"f")})),"f"),Ke(this,Pe,new Promise(((e,t)=>{Ke(this,Re,e,"f"),Ke(this,Ie,t,"f")})),"f"),He(this,ke,"f").catch((()=>{})),He(this,Pe,"f").catch((()=>{}))}get response(){return He(this,Fe,"f")}get request_id(){return He(this,Le,"f")}async withResponse(){const e=await He(this,ke,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new We;return t._run((()=>t._fromReadableStream(e))),t}static createMessage(e,t,n){const r=new We;for(const e of t.messages)r._addMessageParam(e);return r._run((()=>r._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),r}_run(e){e().then((()=>{this._emitFinal(),this._emit("end")}),He(this,Ue,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort()))),He(this,Te,"m",qe).call(this);const{response:o,data:a}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(o);for await(const e of a)He(this,Te,"m",Be).call(this,e);if(a.controller.signal?.aborted)throw new m;He(this,Te,"m",Ze).call(this)}_connected(e){this.ended||(Ke(this,Fe,e,"f"),Ke(this,Le,e?.headers.get("request-id"),"f"),He(this,Ce,"f").call(this,e),this._emit("connect"))}get ended(){return He(this,Ee,"f")}get errored(){return He(this,Me,"f")}get aborted(){return He(this,xe,"f")}abort(){this.controller.abort()}on(e,t){return(He(this,Ae,"f")[e]||(He(this,Ae,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=He(this,Ae,"f")[e];if(!n)return this;const r=n.findIndex((e=>e.listener===t));return r>=0&&n.splice(r,1),this}once(e,t){return(He(this,Ae,"f")[e]||(He(this,Ae,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,n)=>{Ke(this,Ne,!0,"f"),"error"!==e&&this.once("error",n),this.once(e,t)}))}async done(){Ke(this,Ne,!0,"f"),await He(this,Pe,"f")}get currentMessage(){return He(this,$e,"f")}async finalMessage(){return await this.done(),He(this,Te,"m",De).call(this)}async finalText(){return await this.done(),He(this,Te,"m",Je).call(this)}_emit(e,...t){if(He(this,Ee,"f"))return;"end"===e&&(Ke(this,Ee,!0,"f"),He(this,Re,"f").call(this));const n=He(this,Ae,"f")[e];if(n&&(He(this,Ae,"f")[e]=n.filter((e=>!e.once)),n.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return He(this,Ne,"f")||n?.length||Promise.reject(e),He(this,je,"f").call(this,e),He(this,Ie,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];He(this,Ne,"f")||n?.length||Promise.reject(e),He(this,je,"f").call(this,e),He(this,Ie,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",He(this,Te,"m",De).call(this))}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),He(this,Te,"m",qe).call(this),this._connected(null);const r=E.fromReadableStream(e,this.controller);for await(const e of r)He(this,Te,"m",Be).call(this,e);if(r.controller.signal?.aborted)throw new m;He(this,Te,"m",Ze).call(this)}[($e=new WeakMap,ke=new WeakMap,Ce=new WeakMap,je=new WeakMap,Pe=new WeakMap,Re=new WeakMap,Ie=new WeakMap,Ae=new WeakMap,Ee=new WeakMap,Me=new WeakMap,xe=new WeakMap,Ne=new WeakMap,Fe=new WeakMap,Le=new WeakMap,Ue=new WeakMap,Te=new WeakSet,De=function(){if(0===this.receivedMessages.length)throw new h("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Je=function(){if(0===this.receivedMessages.length)throw new h("stream ended without producing a Message with role=assistant");const e=this.receivedMessages.at(-1).content.filter((e=>"text"===e.type)).map((e=>e.text));if(0===e.length)throw new h("stream ended without producing a content block with type=text");return e.join(" ")},qe=function(){this.ended||Ke(this,$e,void 0,"f")},Be=function(e){if(this.ended)return;const t=He(this,Te,"m",ze).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{const n=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===n.type&&this._emit("text",e.delta.text,n.text||"");break;case"citations_delta":"text"===n.type&&this._emit("citation",e.delta.citation,n.citations??[]);break;case"input_json_delta":"tool_use"===n.type&&n.input&&this._emit("inputJson",e.delta.partial_json,n.input);break;case"thinking_delta":"thinking"===n.type&&this._emit("thinking",e.delta.thinking,n.thinking);break;case"signature_delta":"thinking"===n.type&&this._emit("signature",n.signature);break;default:e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(t,!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":Ke(this,$e,t,"f")}},Ze=function(){if(this.ended)throw new h("stream has ended, this shouldn't happen");const e=He(this,$e,"f");if(!e)throw new h("request ended without sending any chunks");return Ke(this,$e,void 0,"f"),e},ze=function(e){let t=He(this,$e,"f");if("message_start"===e.type){if(t)throw new h(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new h(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":case"content_block_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,t;case"content_block_start":return t.content.push(e.content_block),t;case"content_block_delta":{const n=t.content.at(e.index);switch(e.delta.type){case"text_delta":"text"===n?.type&&(n.text+=e.delta.text);break;case"citations_delta":"text"===n?.type&&(n.citations??(n.citations=[]),n.citations.push(e.delta.citation));break;case"input_json_delta":if("tool_use"===n?.type){let t=n[Ge]||"";t+=e.delta.partial_json,Object.defineProperty(n,Ge,{value:t,enumerable:!1,writable:!0}),t&&(n.input=Oe(t))}break;case"thinking_delta":"thinking"===n?.type&&(n.thinking+=e.delta.thinking);break;case"signature_delta":"thinking"===n?.type&&(n.signature=e.delta.signature);break;default:e.delta}return t}}},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("streamEvent",(n=>{const r=t.shift();r?r.resolve(n):e.push(n)})),this.on("end",(()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{n=!0;for(const n of t)n.reject(e);t.length=0})),this.on("error",(e=>{n=!0;for(const n of t)n.reject(e);t.length=0})),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise(((e,n)=>t.push({resolve:e,reject:n}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new E(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}const Ve={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};let Xe=class extends be{constructor(){super(...arguments),this.batches=new ve(this._client)}create(e,t){const{betas:n,...r}=e;return r.model in Ve&&console.warn(`The model '${r.model}' is deprecated and will reach end-of-life on ${Ve[r.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages?beta=true",{body:r,timeout:this._client._options.timeout??(r.stream?6e5:this._client._calculateNonstreamingTimeout(r.max_tokens)),...t,headers:{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...t?.headers},stream:e.stream??!1})}stream(e,t){return We.createMessage(this,e,t)}countTokens(e,t){const{betas:n,...r}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:r,...t,headers:{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString(),...t?.headers}})}};Xe.Batches=ve,Xe.BetaMessageBatchesPage=Se;let Ye=class extends be{constructor(){super(...arguments),this.models=new ge(this._client),this.messages=new Xe(this._client)}};Ye.Models=ge,Ye.BetaModelInfosPage=ye,Ye.Messages=Xe;let Qe=class extends be{create(e,t){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}},et=class extends be{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/v1/messages/batches/${e}`,t)}list(e={},t){return V(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",tt,{query:e,...t})}delete(e,t){return this._client.delete(`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){const n=await this.retrieve(e);if(!n.results_url)throw new h(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})._thenUnwrap(((e,t)=>_e.fromResponse(t.response,t.controller)))}};class tt extends me{}et.MessageBatchesPage=tt;var nt,rt,ot,at,st,it,ut,lt,ct,dt,pt,ht,ft,mt,bt,gt,yt,_t,vt,St,wt,Ot,Tt=function(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n},$t=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};const kt="__json_buf";class Ct{constructor(){nt.add(this),this.messages=[],this.receivedMessages=[],rt.set(this,void 0),this.controller=new AbortController,ot.set(this,void 0),at.set(this,(()=>{})),st.set(this,(()=>{})),it.set(this,void 0),ut.set(this,(()=>{})),lt.set(this,(()=>{})),ct.set(this,{}),dt.set(this,!1),pt.set(this,!1),ht.set(this,!1),ft.set(this,!1),mt.set(this,void 0),bt.set(this,void 0),_t.set(this,(e=>{if(Tt(this,pt,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new m),e instanceof m)return Tt(this,ht,!0,"f"),this._emit("abort",e);if(e instanceof h)return this._emit("error",e);if(e instanceof Error){const t=new h(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new h(String(e)))})),Tt(this,ot,new Promise(((e,t)=>{Tt(this,at,e,"f"),Tt(this,st,t,"f")})),"f"),Tt(this,it,new Promise(((e,t)=>{Tt(this,ut,e,"f"),Tt(this,lt,t,"f")})),"f"),$t(this,ot,"f").catch((()=>{})),$t(this,it,"f").catch((()=>{}))}get response(){return $t(this,mt,"f")}get request_id(){return $t(this,bt,"f")}async withResponse(){const e=await $t(this,ot,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new Ct;return t._run((()=>t._fromReadableStream(e))),t}static createMessage(e,t,n){const r=new Ct;for(const e of t.messages)r._addMessageParam(e);return r._run((()=>r._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),r}_run(e){e().then((()=>{this._emitFinal(),this._emit("end")}),$t(this,_t,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort()))),$t(this,nt,"m",vt).call(this);const{response:o,data:a}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(o);for await(const e of a)$t(this,nt,"m",St).call(this,e);if(a.controller.signal?.aborted)throw new m;$t(this,nt,"m",wt).call(this)}_connected(e){this.ended||(Tt(this,mt,e,"f"),Tt(this,bt,e?.headers.get("request-id"),"f"),$t(this,at,"f").call(this,e),this._emit("connect"))}get ended(){return $t(this,dt,"f")}get errored(){return $t(this,pt,"f")}get aborted(){return $t(this,ht,"f")}abort(){this.controller.abort()}on(e,t){return($t(this,ct,"f")[e]||($t(this,ct,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=$t(this,ct,"f")[e];if(!n)return this;const r=n.findIndex((e=>e.listener===t));return r>=0&&n.splice(r,1),this}once(e,t){return($t(this,ct,"f")[e]||($t(this,ct,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,n)=>{Tt(this,ft,!0,"f"),"error"!==e&&this.once("error",n),this.once(e,t)}))}async done(){Tt(this,ft,!0,"f"),await $t(this,it,"f")}get currentMessage(){return $t(this,rt,"f")}async finalMessage(){return await this.done(),$t(this,nt,"m",gt).call(this)}async finalText(){return await this.done(),$t(this,nt,"m",yt).call(this)}_emit(e,...t){if($t(this,dt,"f"))return;"end"===e&&(Tt(this,dt,!0,"f"),$t(this,ut,"f").call(this));const n=$t(this,ct,"f")[e];if(n&&($t(this,ct,"f")[e]=n.filter((e=>!e.once)),n.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return $t(this,ft,"f")||n?.length||Promise.reject(e),$t(this,st,"f").call(this,e),$t(this,lt,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];$t(this,ft,"f")||n?.length||Promise.reject(e),$t(this,st,"f").call(this,e),$t(this,lt,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",$t(this,nt,"m",gt).call(this))}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),$t(this,nt,"m",vt).call(this),this._connected(null);const r=E.fromReadableStream(e,this.controller);for await(const e of r)$t(this,nt,"m",St).call(this,e);if(r.controller.signal?.aborted)throw new m;$t(this,nt,"m",wt).call(this)}[(rt=new WeakMap,ot=new WeakMap,at=new WeakMap,st=new WeakMap,it=new WeakMap,ut=new WeakMap,lt=new WeakMap,ct=new WeakMap,dt=new WeakMap,pt=new WeakMap,ht=new WeakMap,ft=new WeakMap,mt=new WeakMap,bt=new WeakMap,_t=new WeakMap,nt=new WeakSet,gt=function(){if(0===this.receivedMessages.length)throw new h("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},yt=function(){if(0===this.receivedMessages.length)throw new h("stream ended without producing a Message with role=assistant");const e=this.receivedMessages.at(-1).content.filter((e=>"text"===e.type)).map((e=>e.text));if(0===e.length)throw new h("stream ended without producing a content block with type=text");return e.join(" ")},vt=function(){this.ended||Tt(this,rt,void 0,"f")},St=function(e){if(this.ended)return;const t=$t(this,nt,"m",Ot).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{const n=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===n.type&&this._emit("text",e.delta.text,n.text||"");break;case"citations_delta":"text"===n.type&&this._emit("citation",e.delta.citation,n.citations??[]);break;case"input_json_delta":"tool_use"===n.type&&n.input&&this._emit("inputJson",e.delta.partial_json,n.input);break;case"thinking_delta":"thinking"===n.type&&this._emit("thinking",e.delta.thinking,n.thinking);break;case"signature_delta":"thinking"===n.type&&this._emit("signature",n.signature);break;default:e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(t,!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":Tt(this,rt,t,"f")}},wt=function(){if(this.ended)throw new h("stream has ended, this shouldn't happen");const e=$t(this,rt,"f");if(!e)throw new h("request ended without sending any chunks");return Tt(this,rt,void 0,"f"),e},Ot=function(e){let t=$t(this,rt,"f");if("message_start"===e.type){if(t)throw new h(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new h(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":case"content_block_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,t;case"content_block_start":return t.content.push(e.content_block),t;case"content_block_delta":{const n=t.content.at(e.index);switch(e.delta.type){case"text_delta":"text"===n?.type&&(n.text+=e.delta.text);break;case"citations_delta":"text"===n?.type&&(n.citations??(n.citations=[]),n.citations.push(e.delta.citation));break;case"input_json_delta":if("tool_use"===n?.type){let t=n[kt]||"";t+=e.delta.partial_json,Object.defineProperty(n,kt,{value:t,enumerable:!1,writable:!0}),t&&(n.input=Oe(t))}break;case"thinking_delta":"thinking"===n?.type&&(n.thinking+=e.delta.thinking);break;case"signature_delta":"thinking"===n?.type&&(n.signature=e.delta.signature);break;default:e.delta}return t}}},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("streamEvent",(n=>{const r=t.shift();r?r.resolve(n):e.push(n)})),this.on("end",(()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{n=!0;for(const n of t)n.reject(e);t.length=0})),this.on("error",(e=>{n=!0;for(const n of t)n.reject(e);t.length=0})),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise(((e,n)=>t.push({resolve:e,reject:n}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new E(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}let jt=class extends be{constructor(){super(...arguments),this.batches=new et(this._client)}create(e,t){return e.model in Pt&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Pt[e.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:e,timeout:this._client._options.timeout??(e.stream?6e5:this._client._calculateNonstreamingTimeout(e.max_tokens)),...t,stream:e.stream??!1})}stream(e,t){return Ct.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}};const Pt={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};jt.Batches=et,jt.MessageBatchesPage=tt;let Rt=class extends be{retrieve(e,t){return this._client.get(`/v1/models/${e}`,t)}list(e={},t){return V(e)?this.list({},e):this._client.getAPIList("/v1/models",It,{query:e,...t})}};class It extends me{}var At;Rt.ModelInfosPage=It;class Et extends z{constructor({baseURL:e=ue("ANTHROPIC_BASE_URL"),apiKey:t=ue("ANTHROPIC_API_KEY")??null,authToken:n=ue("ANTHROPIC_AUTH_TOKEN")??null,...r}={