UNPKG

kaibanjs

Version:

AI Multi-Agent library for Javascript Developers.

1 lines 1.56 MB
"use strict";var e=require("uuid");function t(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 n=t(e);const r="0.37.0";let o,a,s,i,u,l,c=!1;let d=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};o||function(e,t={auto:!1}){if(c)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${e.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(o)throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${e.kind}'\` after \`import '@anthropic-ai/sdk/shims/${o}'\``);c=t.auto,o=e.kind,a=e.fetch,s=e.File,i=e.ReadableStream,u=e.getDefaultAgent,l=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 d(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 p extends Error{}let h=class e extends p{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 m({message:r,cause:se(n)});const a=n;return 400===t?new g(t,a,r,o):401===t?new y(t,a,r,o):403===t?new _(t,a,r,o):404===t?new v(t,a,r,o):409===t?new S(t,a,r,o):422===t?new w(t,a,r,o):429===t?new O(t,a,r,o):t>=500?new T(t,a,r,o):new e(t,a,r,o)}},f=class extends h{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},m=class extends h{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},b=class extends m{constructor({message:e}={}){super({message:e??"Request timed out."})}},g=class extends h{},y=class extends h{},_=class extends h{},v=class extends h{},S=class extends h{},w=class extends h{},O=class extends h{},T=class extends h{};var $,k=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},C=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 j=class{constructor(){$.set(this,void 0),this.buffer=new Uint8Array,k(this,$,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=P(this.buffer,C(this,$,"f")));){if(o.carriage&&null==C(this,$,"f")){k(this,$,o.index,"f");continue}if(null!=C(this,$,"f")&&(o.index!==C(this,$,"f")+1||o.carriage)){r.push(this.decodeText(this.buffer.slice(0,C(this,$,"f")-1))),this.buffer=this.buffer.slice(C(this,$,"f")),k(this,$,null,"f");continue}const e=null!==C(this,$,"f")?o.preceding-1:o.preceding,t=this.decodeText(this.buffer.slice(0,e));r.push(t),this.buffer=this.buffer.slice(o.index),k(this,$,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 p(`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 p(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new p("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode("\n"):[]}};function P(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 R(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 I(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}}}$=new WeakMap,j.NEWLINE_CHARS=new Set(["\n","\r"]),j.NEWLINE_REGEXP=/\r\n|[\n\r]/g;let A=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 p("Attempted to iterate over a response with no body");const n=new E,r=new j,o=I(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=R(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 h.generate(void 0,`SSE Error: ${e.data}`,e.data,H(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 j,n=I(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 i({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 E=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 M=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 x=e=>"string"==typeof e?e:"undefined"!=typeof Buffer&&e instanceof Buffer?String(e):void 0,N=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],F=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag];var L,D=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)};async function U(e){const{response:t}=e;if(e.options.stream)return de("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):A.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 de("response",t.status,t.url,t.headers,e),q(e,t)}const r=await t.text();return de("response",t.status,t.url,t.headers,r),r}function q(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 B=class e extends Promise{constructor(e,t=U){super((e=>{e(null)})),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(t){return new e(this.responsePromise,(async e=>q(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=ae("maxRetries",t),this.timeout=ae("timeout",n),this.httpAgent=r,this.fetch=o??a}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...ee(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${pe()}`}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&&M(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:F(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,i=this.calculateContentLength(s),l=this.buildURL(r,o);"timeout"in e&&ae("timeout",e.timeout),e.timeout=e.timeout??this.timeout;const c=e.httpAgent??this.httpAgent??u(l),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:l,timeout:e.timeout}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:r}){const a={};n&&(a["content-length"]=n);const s=this.defaultHeaders(e);return ce(a,s),ce(a,t),F(e.body)&&"node"!==o&&delete a["content-type"],void 0===he(s,"x-stainless-retry-count")&&void 0===he(t,"x-stainless-retry-count")&&(a["x-stainless-retry-count"]=String(r)),void 0===he(s,"x-stainless-timeout")&&void 0===he(t,"x-stainless-timeout")&&e.timeout&&(a["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(a,t),a}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new p("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 h.generate(e,t,n,r)}request(e,t=null){return new B(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}),de("request",a,n,o.headers),n.signal?.aborted)throw new f;const i=new AbortController,u=await this.fetchWithTimeout(a,o,s,i).catch(se);if(u instanceof Error){if(n.signal?.aborted)throw new f;if(t)return this.retryRequest(n,t);if("AbortError"===u.name)throw new b;throw new m({cause:u})}const l=H(u.headers);if(!u.ok){if(t&&this.shouldRetry(u)){return de(`response (error; ${`retrying, ${t} attempts remaining`})`,u.status,a,l),this.retryRequest(n,t,l)}const e=await u.text().catch((e=>se(e).message)),r=te(e),o=r?void 0:e;de(`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 K(this,n,e)}buildURL(e,t){const n=re(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),r=this.defaultQuery();return ue(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 p(`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 oe(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 ${r}`}},z=class{constructor(e,t,n,r){L.set(this,void 0),D(this,L,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 p("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 J(this,L,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(L=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}},K=class extends B{constructor(e,t,n){super(t,(async t=>new n(e,t.response,await U(t),t.options)))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}};const H=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){const n=t.toString();return e[n.toLowerCase()]||e[n]}}),G={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},W=e=>"object"==typeof e&&null!==e&&!ue(e)&&Object.keys(e).every((e=>le(G,e))),V=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":r,"X-Stainless-OS":Y(Deno.build.os),"X-Stainless-Arch":X(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":r,"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":r,"X-Stainless-OS":Y(process.platform),"X-Stainless-Arch":X(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":r,"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":r,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const X=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",Y=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 Q;const ee=()=>Q??(Q=V()),te=e=>{try{return JSON.parse(e)}catch(e){return}},ne=/^[a-z][a-z0-9+.-]*:/i,re=e=>ne.test(e),oe=e=>new Promise((t=>setTimeout(t,e))),ae=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new p(`${e} must be an integer`);if(t<0)throw new p(`${e} must be a positive integer`);return t},se=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))},ie=e=>"undefined"!=typeof process?process.env?.[e]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e)?.trim():void 0;function ue(e){if(!e)return!0;for(const t in e)return!1;return!0}function le(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ce(e,t){for(const n in t){if(!le(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 de(e,...t){"undefined"!=typeof process&&"true"===process?.env?.DEBUG&&console.log(`Anthropic:DEBUG:${e}`,...t)}const pe=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),he=(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 fe=class extends z{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}},me=class{constructor(e){this._client=e}},be=class extends me{retrieve(e,t){return this._client.get(`/v1/models/${e}?beta=true`,t)}list(e={},t){return W(e)?this.list({},e):this._client.getAPIList("/v1/models?beta=true",ge,{query:e,...t})}};class ge extends fe{}be.BetaModelInfosPage=ge;class ye{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new j;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 p("Attempted to iterate over a response with no body");return new ye(I(e.body),t)}}let _e=class extends me{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(W(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(W(e))return this.list({},e);const{betas:n,...r}=e;return this._client.getAPIList("/v1/messages/batches?beta=true",ve,{query:r,...t,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}delete(e,t={},n){if(W(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(W(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(W(t))return this.results(e,{},t);const r=await this.retrieve(e);if(!r.results_url)throw new p(`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)=>ye.fromResponse(t.response,t.controller)))}};class ve extends fe{}_e.BetaMessageBatchesPage=ve;const Se=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),Se(e);case"number":let n=t.value[t.value.length-1];if("."===n||"-"===n)return e=e.slice(0,e.length-1),Se(e);case"string":let r=e[e.length-2];if("delimiter"===r?.type)return e=e.slice(0,e.length-1),Se(e);if("brace"===r?.type&&"{"===r.value)return e=e.slice(0,e.length-1),Se(e);break;case"delimiter":return e=e.slice(0,e.length-1),Se(e)}return e},we=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})(Se((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 Oe,Te,$e,ke,Ce,je,Pe,Re,Ie,Ae,Ee,Me,xe,Ne,Fe,Le,De,Je,Ue,qe,Be,Ze,ze=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},Ke=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 He="__json_buf";class Ge{constructor(){Oe.add(this),this.messages=[],this.receivedMessages=[],Te.set(this,void 0),this.controller=new AbortController,$e.set(this,void 0),ke.set(this,(()=>{})),Ce.set(this,(()=>{})),je.set(this,void 0),Pe.set(this,(()=>{})),Re.set(this,(()=>{})),Ie.set(this,{}),Ae.set(this,!1),Ee.set(this,!1),Me.set(this,!1),xe.set(this,!1),Ne.set(this,void 0),Fe.set(this,void 0),Je.set(this,(e=>{if(ze(this,Ee,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new f),e instanceof f)return ze(this,Me,!0,"f"),this._emit("abort",e);if(e instanceof p)return this._emit("error",e);if(e instanceof Error){const t=new p(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new p(String(e)))})),ze(this,$e,new Promise(((e,t)=>{ze(this,ke,e,"f"),ze(this,Ce,t,"f")})),"f"),ze(this,je,new Promise(((e,t)=>{ze(this,Pe,e,"f"),ze(this,Re,t,"f")})),"f"),Ke(this,$e,"f").catch((()=>{})),Ke(this,je,"f").catch((()=>{}))}get response(){return Ke(this,Ne,"f")}get request_id(){return Ke(this,Fe,"f")}async withResponse(){const e=await Ke(this,$e,"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 Ge;return t._run((()=>t._fromReadableStream(e))),t}static createMessage(e,t,n){const r=new Ge;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")}),Ke(this,Je,"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()))),Ke(this,Oe,"m",Ue).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)Ke(this,Oe,"m",qe).call(this,e);if(a.controller.signal?.aborted)throw new f;Ke(this,Oe,"m",Be).call(this)}_connected(e){this.ended||(ze(this,Ne,e,"f"),ze(this,Fe,e?.headers.get("request-id"),"f"),Ke(this,ke,"f").call(this,e),this._emit("connect"))}get ended(){return Ke(this,Ae,"f")}get errored(){return Ke(this,Ee,"f")}get aborted(){return Ke(this,Me,"f")}abort(){this.controller.abort()}on(e,t){return(Ke(this,Ie,"f")[e]||(Ke(this,Ie,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=Ke(this,Ie,"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(Ke(this,Ie,"f")[e]||(Ke(this,Ie,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,n)=>{ze(this,xe,!0,"f"),"error"!==e&&this.once("error",n),this.once(e,t)}))}async done(){ze(this,xe,!0,"f"),await Ke(this,je,"f")}get currentMessage(){return Ke(this,Te,"f")}async finalMessage(){return await this.done(),Ke(this,Oe,"m",Le).call(this)}async finalText(){return await this.done(),Ke(this,Oe,"m",De).call(this)}_emit(e,...t){if(Ke(this,Ae,"f"))return;"end"===e&&(ze(this,Ae,!0,"f"),Ke(this,Pe,"f").call(this));const n=Ke(this,Ie,"f")[e];if(n&&(Ke(this,Ie,"f")[e]=n.filter((e=>!e.once)),n.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return Ke(this,xe,"f")||n?.length||Promise.reject(e),Ke(this,Ce,"f").call(this,e),Ke(this,Re,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];Ke(this,xe,"f")||n?.length||Promise.reject(e),Ke(this,Ce,"f").call(this,e),Ke(this,Re,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",Ke(this,Oe,"m",Le).call(this))}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),Ke(this,Oe,"m",Ue).call(this),this._connected(null);const r=A.fromReadableStream(e,this.controller);for await(const e of r)Ke(this,Oe,"m",qe).call(this,e);if(r.controller.signal?.aborted)throw new f;Ke(this,Oe,"m",Be).call(this)}[(Te=new WeakMap,$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,Je=new WeakMap,Oe=new WeakSet,Le=function(){if(0===this.receivedMessages.length)throw new p("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},De=function(){if(0===this.receivedMessages.length)throw new p("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 p("stream ended without producing a content block with type=text");return e.join(" ")},Ue=function(){this.ended||ze(this,Te,void 0,"f")},qe=function(e){if(this.ended)return;const t=Ke(this,Oe,"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":ze(this,Te,t,"f")}},Be=function(){if(this.ended)throw new p("stream has ended, this shouldn't happen");const e=Ke(this,Te,"f");if(!e)throw new p("request ended without sending any chunks");return ze(this,Te,void 0,"f"),e},Ze=function(e){let t=Ke(this,Te,"f");if("message_start"===e.type){if(t)throw new p(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new p(`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[He]||"";t+=e.delta.partial_json,Object.defineProperty(n,He,{value:t,enumerable:!1,writable:!0}),t&&(n.input=we(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 A(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}const We={"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 Ve=class extends me{constructor(){super(...arguments),this.batches=new _e(this._client)}create(e,t){const{betas:n,...r}=e;return r.model in We&&console.warn(`The model '${r.model}' is deprecated and will reach end-of-life on ${We[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 Ge.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}})}};Ve.Batches=_e,Ve.BetaMessageBatchesPage=ve;let Xe=class extends me{constructor(){super(...arguments),this.models=new be(this._client),this.messages=new Ve(this._client)}};Xe.Models=be,Xe.BetaModelInfosPage=ge,Xe.Messages=Ve;let Ye=class extends me{create(e,t){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}},Qe=class extends me{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 W(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",et,{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 p(`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)=>ye.fromResponse(t.response,t.controller)))}};class et extends fe{}Qe.MessageBatchesPage=et;var tt,nt,rt,ot,at,st,it,ut,lt,ct,dt,pt,ht,ft,mt,bt,gt,yt,_t,vt,St,wt,Ot=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},Tt=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 $t="__json_buf";class kt{constructor(){tt.add(this),this.messages=[],this.receivedMessages=[],nt.set(this,void 0),this.controller=new AbortController,rt.set(this,void 0),ot.set(this,(()=>{})),at.set(this,(()=>{})),st.set(this,void 0),it.set(this,(()=>{})),ut.set(this,(()=>{})),lt.set(this,{}),ct.set(this,!1),dt.set(this,!1),pt.set(this,!1),ht.set(this,!1),ft.set(this,void 0),mt.set(this,void 0),yt.set(this,(e=>{if(Ot(this,dt,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new f),e instanceof f)return Ot(this,pt,!0,"f"),this._emit("abort",e);if(e instanceof p)return this._emit("error",e);if(e instanceof Error){const t=new p(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new p(String(e)))})),Ot(this,rt,new Promise(((e,t)=>{Ot(this,ot,e,"f"),Ot(this,at,t,"f")})),"f"),Ot(this,st,new Promise(((e,t)=>{Ot(this,it,e,"f"),Ot(this,ut,t,"f")})),"f"),Tt(this,rt,"f").catch((()=>{})),Tt(this,st,"f").catch((()=>{}))}get response(){return Tt(this,ft,"f")}get request_id(){return Tt(this,mt,"f")}async withResponse(){const e=await Tt(this,rt,"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 kt;return t._run((()=>t._fromReadableStream(e))),t}static createMessage(e,t,n){const r=new kt;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")}),Tt(this,yt,"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()))),Tt(this,tt,"m",_t).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)Tt(this,tt,"m",vt).call(this,e);if(a.controller.signal?.aborted)throw new f;Tt(this,tt,"m",St).call(this)}_connected(e){this.ended||(Ot(this,ft,e,"f"),Ot(this,mt,e?.headers.get("request-id"),"f"),Tt(this,ot,"f").call(this,e),this._emit("connect"))}get ended(){return Tt(this,ct,"f")}get errored(){return Tt(this,dt,"f")}get aborted(){return Tt(this,pt,"f")}abort(){this.controller.abort()}on(e,t){return(Tt(this,lt,"f")[e]||(Tt(this,lt,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=Tt(this,lt,"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(Tt(this,lt,"f")[e]||(Tt(this,lt,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,n)=>{Ot(this,ht,!0,"f"),"error"!==e&&this.once("error",n),this.once(e,t)}))}async done(){Ot(this,ht,!0,"f"),await Tt(this,st,"f")}get currentMessage(){return Tt(this,nt,"f")}async finalMessage(){return await this.done(),Tt(this,tt,"m",bt).call(this)}async finalText(){return await this.done(),Tt(this,tt,"m",gt).call(this)}_emit(e,...t){if(Tt(this,ct,"f"))return;"end"===e&&(Ot(this,ct,!0,"f"),Tt(this,it,"f").call(this));const n=Tt(this,lt,"f")[e];if(n&&(Tt(this,lt,"f")[e]=n.filter((e=>!e.once)),n.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return Tt(this,ht,"f")||n?.length||Promise.reject(e),Tt(this,at,"f").call(this,e),Tt(this,ut,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];Tt(this,ht,"f")||n?.length||Promise.reject(e),Tt(this,at,"f").call(this,e),Tt(this,ut,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",Tt(this,tt,"m",bt).call(this))}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),Tt(this,tt,"m",_t).call(this),this._connected(null);const r=A.fromReadableStream(e,this.controller);for await(const e of r)Tt(this,tt,"m",vt).call(this,e);if(r.controller.signal?.aborted)throw new f;Tt(this,tt,"m",St).call(this)}[(nt=new WeakMap,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,yt=new WeakMap,tt=new WeakSet,bt=function(){if(0===this.receivedMessages.length)throw new p("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},gt=function(){if(0===this.receivedMessages.length)throw new p("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 p("stream ended without producing a content block with type=text");return e.join(" ")},_t=function(){this.ended||Ot(this,nt,void 0,"f")},vt=function(e){if(this.ended)return;const t=Tt(this,tt,"m",wt).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":Ot(this,nt,t,"f")}},St=function(){if(this.ended)throw new p("stream has ended, this shouldn't happen");const e=Tt(this,nt,"f");if(!e)throw new p("request ended without sending any chunks");return Ot(this,nt,void 0,"f"),e},wt=function(e){let t=Tt(this,nt,"f");if("message_start"===e.type){if(t)throw new p(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new p(`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[$t]||"";t+=e.delta.partial_json,Object.defineProperty(n,$t,{value:t,enumerable:!1,writable:!0}),t&&(n.input=we(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 A(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}let Ct=class extends me{constructor(){super(...arguments),this.batches=new Qe(this._client)}create(e,t){return e.model in jt&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${jt[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 kt.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}};const jt={"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"};Ct.Batches=Qe,Ct.MessageBatchesPage=et;let Pt=class extends me{retrieve(e,t){return this._client.get(`/v1/models/${e}`,t)}list(e={},t){return W(e)?this.list({},e):this._client.getAPIList("/v1/models",Rt,{query:e,...t})}};class Rt extends fe{}var It;Pt.ModelInfosPage=Rt;class At extends Z{constructor({baseURL:e=ie("ANTHROPIC_BASE_URL"),apiKey:t=ie("ANTHROPIC_API_KEY")??null,authToken:n=ie("ANTHROPIC_AUTH_TOKEN")??null,...r}={}){const o={apiKey:t,authToken:n,...r,baseURL:e||"https://api.anthropic.com"};if(!o.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new p("It looks like you're running in a