@m4trix/trace-viewer 0.14.1 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -0
- package/dist/cli.js +5 -5
- package/dist/cli.js.map +1 -1
- package/dist/client/assets/anthropic-DUwMYY1S.js +44 -0
- package/dist/client/assets/aws-credential-providers-B7-NYDyv.js +1 -0
- package/dist/client/assets/bedrock-BIja-RWN.js +8 -0
- package/dist/client/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
- package/dist/client/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
- package/dist/client/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
- package/dist/client/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
- package/dist/client/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
- package/dist/client/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
- package/dist/client/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
- package/dist/client/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
- package/dist/client/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
- package/dist/client/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
- package/dist/client/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
- package/dist/client/assets/index-Cl5VyaKo.js +274 -0
- package/dist/client/assets/index-DVz5tq4u.css +1 -0
- package/dist/client/assets/node.browser-C_s9kvmM.js +1 -0
- package/dist/client/assets/node.browser-DWucOsQl.js +1 -0
- package/dist/client/assets/openai-mbLa3c0B.js +3 -0
- package/dist/client/index.html +2 -2
- package/dist/index.js +5 -5
- package/dist/index.js.map +1 -1
- package/package.json +8 -2
- package/dist/client/assets/index-BrxB6Y1i.css +0 -1
- package/dist/client/assets/index-ShWpAzD-.js +0 -53
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/node.browser-C_s9kvmM.js","assets/index-Cl5VyaKo.js","assets/index-DVz5tq4u.css","assets/node.browser-DWucOsQl.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as ce,g as Fo,P as qt,t as _s,k as cl}from"./index-Cl5VyaKo.js";function lt(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}const jn=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{const r=Object.prototype.toString.call(n);if(r==="[object Error]"||r==="[object DOMException]"){const e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};var S=(()=>{class n extends Error{}return n})();class z extends S{constructor(r,e,t,s,i){super(`${z.makeMessage(r,e,t)}`),this.status=r,this.headers=s,this.requestID=s?.get("request-id"),this.workspaceID=s?.get("anthropic-workspace-id"),this.error=e,this.type=i??null}static makeMessage(r,e,t){const s=e?.message?typeof e.message=="string"?e.message:JSON.stringify(e.message):e?JSON.stringify(e):t;return r&&s?`${r} ${s}`:r?`${r} status code (no body)`:s||"(no status code or body)"}static generate(r,e,t,s){if(!r||!s)return new ut({message:t,cause:jn(e)});const i=e,a=i?.error?.type;return r===400?new qo(r,i,t,s,a):r===401?new Ko(r,i,t,s,a):r===403?new Vo(r,i,t,s,a):r===404?new Jo(r,i,t,s,a):r===409?new Xo(r,i,t,s,a):r===422?new Go(r,i,t,s,a):r===429?new Qo(r,i,t,s,a):r>=500?new Yo(r,i,t,s,a):new z(r,i,t,s,a)}}class oe extends z{constructor({message:r}={}){super(void 0,void 0,r||"Request was aborted.",void 0)}}class ut extends z{constructor({message:r,cause:e}){super(void 0,void 0,r||"Connection error.",void 0),e&&(this.cause=e)}}class gs extends ut{constructor({message:r}={}){super({message:r??"Request timed out."})}}class ll extends S{constructor(r,{cause:e}={}){super(r??"Retryable error."),e!==void 0&&(this.cause=e)}}class qo extends z{}class Ko extends z{}class Vo extends z{}class Jo extends z{}class Xo extends z{}class Go extends z{}class Qo extends z{}class Yo extends z{}let Or=n=>(Or=Array.isArray,Or(n)),ms=Or;const Zo=Symbol.for("brand.privateNullableHeaders");function*ul(n){if(!n)return;if(Zo in n){const{values:t,nulls:s}=n;yield*t.entries();for(const i of s)yield[i,null];return}let r=!1,e;n instanceof Headers?e=n.entries():ms(n)?e=n:(r=!0,e=Object.entries(n??{}));for(let t of e){const s=t[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const i=ms(t[1])?t[1]:[t[1]];let a=!1;for(const c of i)c!==void 0&&(r&&!a&&(a=!0,yield[s,Un]),yield[s,c])}}const Un=Symbol("clear"),dl=new Set(["x-stainless-helper"]),hl=(n,r)=>{const e=n?n.split(",").map(t=>t.trim()).filter(Boolean):[];for(const t of r.split(",").map(s=>s.trim()))t&&!e.includes(t)&&e.push(t);return e.join(", ")},ec=n=>{const r=new Headers,e=new Set;for(const t of n){const s=new Set;for(const[i,a]of ul(t)){const c=i.toLowerCase();if(dl.has(c)){if(a===Un)continue;a===null?(r.delete(i),e.add(c)):(r.set(i,hl(r.get(i),a)),e.delete(c));continue}(a===Un||!s.has(c))&&(r.delete(i),s.add(c),a===Un)||(a===null?(r.delete(i),e.add(c)):(r.append(i,a),e.delete(c)))}}return{[Zo]:!0,values:r,nulls:e}};var fl={};const Gt=n=>{if(typeof globalThis.process<"u")return fl?.[n]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(n)?.trim()||void 0};function w(n,r,e,t,s){if(typeof r=="function"?n!==r||!0:!r.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r.set(n,e),e}function o(n,r,e,t){if(e==="a"&&!t)throw new TypeError("Private accessor was defined without a getter");if(typeof r=="function"?n!==r||!t:!r.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?t:e==="a"?t.call(n):t?t.value:r.get(n)}const pl=/^[a-z][a-z0-9+.-]*:/i,_l=n=>pl.test(n);let J=n=>(J=Array.isArray,J(n)),ws=J;function Fn(n){return typeof n!="object"?{}:n??{}}function ys(n){if(!n)return!0;for(const r in n)return!1;return!0}function gl(n,r){return Object.prototype.hasOwnProperty.call(n,r)}function bs(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}const Gn=(n,r)=>{if(typeof r!="number"||!Number.isInteger(r))throw new S(`${n} must be an integer`);if(r<0)throw new S(`${n} must be a positive integer`);return r},tc=n=>{try{return JSON.parse(n)}catch{return}};const Be=(n,r)=>new Promise(e=>{if(r?.aborted)return e();const t=()=>{clearTimeout(s),e()},s=setTimeout(()=>{r?.removeEventListener("abort",t),e()},n);r?.addEventListener("abort",t,{once:!0})}),ge="0.131.0",ml=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function wl(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const yl=()=>{const n=wl();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ge,"X-Stainless-OS":ks(Deno.build.os),"X-Stainless-Arch":vs(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ge,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process?.version??"unknown"};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ge,"X-Stainless-OS":ks(globalThis.process.platform??"unknown"),"X-Stainless-Arch":vs(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const r=bl();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ge,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${r.browser}`,"X-Stainless-Runtime-Version":r.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ge,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function bl(){if(typeof navigator>"u"||!navigator)return null;const n=[{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:r,pattern:e}of n){const t=e.exec(navigator.userAgent);if(t){const s=t[1]||0,i=t[2]||0,a=t[3]||0;return{browser:r,version:`${s}.${i}.${a}`}}}return null}const vs=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",ks=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown");let Ss;const es=()=>Ss??(Ss=yl()),qn=new WeakMap,nc=typeof globalThis.FinalizationRegistry=="function"?new globalThis.FinalizationRegistry(n=>De(n)):null;function vl(n,r){return()=>n.removeEventListener("abort",r)}function kl(n,r,e){qn.set(n,vl(r,e))}function Sl(n,r){qn.has(r)&&nc?.register(n,r,r)}function De(n){const r=qn.get(n);r&&(qn.delete(n),nc?.unregister(n),r())}function xl(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function rc(...n){const r=globalThis.ReadableStream;if(typeof r>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new r(...n)}function sc(n){let r=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return rc({start(){},async pull(e){const{done:t,value:s}=await r.next();t?e.close():e.enqueue(s)},async cancel(){await r.return?.()}})}function ts(n){if(n[Symbol.asyncIterator])return n;const r=n.getReader();return{async next(){try{const e=await r.read();return e?.done&&r.releaseLock(),e}catch(e){throw r.releaseLock(),e}},async return(){const e=r.cancel();return r.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Rl(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}const r=n.getReader(),e=r.cancel();r.releaseLock(),await e}const Al=({headers:n,body:r})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(r)}),ic="RFC3986",ac=n=>String(n),xs={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:ac},El="RFC1738";let Cr=(n,r)=>(Cr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Cr(n,r));const le=(()=>{const n=[];for(let r=0;r<256;++r)n.push("%"+((r<16?"0":"")+r.toString(16)).toUpperCase());return n})(),Qn=1024,Tl=(n,r,e,t,s)=>{if(n.length===0)return n;let i=n;if(typeof n=="symbol"?i=Symbol.prototype.toString.call(n):typeof n!="string"&&(i=String(n)),e==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,function(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let a="";for(let c=0;c<i.length;c+=Qn){const u=i.length>=Qn?i.slice(c,c+Qn):i,l=[];for(let p=0;p<u.length;++p){let d=u.charCodeAt(p);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||s===El&&(d===40||d===41)){l[l.length]=u.charAt(p);continue}if(d<128){l[l.length]=le[d];continue}if(d<2048){l[l.length]=le[192|d>>6]+le[128|d&63];continue}if(d<55296||d>=57344){l[l.length]=le[224|d>>12]+le[128|d>>6&63]+le[128|d&63];continue}p+=1,d=65536+((d&1023)<<10|u.charCodeAt(p)&1023),l[l.length]=le[240|d>>18]+le[128|d>>12&63]+le[128|d>>6&63]+le[128|d&63]}a+=l.join("")}return a};function $l(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function Rs(n,r){if(J(n)){const e=[];for(let t=0;t<n.length;t+=1)e.push(r(n[t]));return e}return r(n)}const oc={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,r){return String(n)+"["+r+"]"},repeat(n){return String(n)}},cc=function(n,r){Array.prototype.push.apply(n,J(r)?r:[r])};let As;const W={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Tl,encodeValuesOnly:!1,format:ic,formatter:ac,indices:!1,serializeDate(n){return(As??(As=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function Il(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}const Yn={};function lc(n,r,e,t,s,i,a,c,u,l,p,d,g,_,m,y,x,E){let b=n,k=E,R=0,T=!1;for(;(k=k.get(Yn))!==void 0&&!T;){const I=k.get(n);if(R+=1,typeof I<"u"){if(I===R)throw new RangeError("Cyclic object value");T=!0}typeof k.get(Yn)>"u"&&(R=0)}if(typeof l=="function"?b=l(r,b):b instanceof Date?b=g?.(b):e==="comma"&&J(b)&&(b=Rs(b,function(I){return I instanceof Date?g?.(I):I})),b===null){if(i)return u&&!y?u(r,W.encoder,x,"key",_):r;b=""}if(Il(b)||$l(b)){if(u){const I=y?r:u(r,W.encoder,x,"key",_);return[m?.(I)+"="+m?.(u(b,W.encoder,x,"value",_))]}return[m?.(r)+"="+m?.(String(b))]}const $=[];if(typeof b>"u")return $;let C;if(e==="comma"&&J(b))y&&u&&(b=Rs(b,u)),C=[{value:b.length>0?b.join(",")||null:void 0}];else if(J(l))C=l;else{const I=Object.keys(b);C=p?I.sort(p):I}const M=c?String(r).replace(/\./g,"%2E"):String(r),L=t&&J(b)&&b.length===1?M+"[]":M;if(s&&J(b)&&b.length===0)return L+"[]";for(let I=0;I<C.length;++I){const ne=C[I],we=typeof ne=="object"&&typeof ne.value<"u"?ne.value:b[ne];if(a&&we===null)continue;const ye=d&&c?ne.replace(/\./g,"%2E"):ne,ol=J(b)?typeof e=="function"?e(L,ye):L:L+(d?"."+ye:"["+ye+"]");E.set(n,R);const ps=new WeakMap;ps.set(Yn,E),cc($,lc(we,ol,e,t,s,i,a,c,e==="comma"&&y&&J(b)?null:u,l,p,d,g,_,m,y,x,ps))}return $}function Pl(n=W){if(typeof n.allowEmptyArrays<"u"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof n.encodeDotInKeys<"u"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder<"u"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");const r=n.charset||W.charset;if(typeof n.charset<"u"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let e=ic;if(typeof n.format<"u"){if(!Cr(xs,n.format))throw new TypeError("Unknown format option provided.");e=n.format}const t=xs[e];let s=W.filter;(typeof n.filter=="function"||J(n.filter))&&(s=n.filter);let i;if(n.arrayFormat&&n.arrayFormat in oc?i=n.arrayFormat:"indices"in n?i=n.indices?"indices":"repeat":i=W.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const a=typeof n.allowDots>"u"?n.encodeDotInKeys?!0:W.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:W.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:W.allowEmptyArrays,arrayFormat:i,charset:r,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:W.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?W.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:W.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:W.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:W.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:W.encodeValuesOnly,filter:s,format:e,formatter:t,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:W.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:W.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:W.strictNullHandling}}function Ml(n,r={}){let e=n;const t=Pl(r);let s,i;typeof t.filter=="function"?(i=t.filter,e=i("",e)):J(t.filter)&&(i=t.filter,s=i);const a=[];if(typeof e!="object"||e===null)return"";const c=oc[t.arrayFormat],u=c==="comma"&&t.commaRoundTrip;s||(s=Object.keys(e)),t.sort&&s.sort(t.sort);const l=new WeakMap;for(let g=0;g<s.length;++g){const _=s[g];t.skipNulls&&e[_]===null||cc(a,lc(e[_],_,c,u,t.allowEmptyArrays,t.strictNullHandling,t.skipNulls,t.encodeDotInKeys,t.encode?t.encoder:null,t.filter,t.sort,t.allowDots,t.serializeDate,t.format,t.formatter,t.encodeValuesOnly,t.charset,l))}const p=a.join(t.delimiter);let d=t.addQueryPrefix===!0?"?":"";return t.charsetSentinel&&(t.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),p.length>0?d+p:""}function Ol(n){return Ml(n,{arrayFormat:"brackets"})}const Cl="urn:ietf:params:oauth:grant-type:jwt-bearer",Ll="refresh_token",uc="/v1/oauth/token",Kn="oauth-2025-04-20",Nl="oidc-federation-2026-04-01",Bl=120,ns=30,Dl=5,Es=1<<20;function dc(n){if(!n)return;let r;try{r=new URL(n)}catch(t){throw new B(`Invalid token endpoint base URL "${n}": ${t}`)}if(r.protocol==="https:")return;const e=r.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!(r.protocol==="http:"&&(e==="localhost"||e==="127.0.0.1"||e==="::1")))throw new B(`Refusing to send credential over non-https token endpoint "${n}"`)}async function hc(n,r){const e=await Hl(n);let t;try{t=JSON.parse(e)}catch{throw new B(`Token endpoint returned non-JSON response (status ${n.status})`,n.status,ie(e),r)}if(!t.access_token)throw new B(`Token endpoint response missing access_token: ${JSON.stringify(ie(t))}`,n.status,ie(t),r);if(t.token_type&&t.token_type.toLowerCase()!=="bearer")throw new B(`Token endpoint response: unsupported token_type "${t.token_type}" (want Bearer)`,n.status,ie(t),r);return t}const Zn=2e3,Ul=new Set(["error","error_description","error_uri"]);function ie(n){if(n==null)return n;if(typeof n=="string"){let r;try{r=JSON.parse(n)}catch{return n.length<=Zn?n:n.slice(0,Zn)+`... <${n.length-Zn} more chars>`}return JSON.stringify(ie(r))}if(typeof n=="object"&&!Array.isArray(n)){const r={};for(const[e,t]of Object.entries(n))Ul.has(e)&&(r[e]=t);return r}return null}async function fc(n,r=e=>console.warn(`anthropic-sdk: ${e}`)){if(typeof process>"u"||process.platform==="win32")return;const{fs:e}=await ce(async()=>{const{fs:a}=await import("./node.browser-C_s9kvmM.js");return{fs:a}},__vite__mapDeps([0,1,2]));let t=n,s;try{t=await e.promises.realpath(n),s=await e.promises.stat(t)}catch{return}const i=s.mode&511;if(i&18)throw new B(`Credentials file at ${t} is group/world-writable (mode 0o${i.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${t}\`.`);if(i&36)throw new B(`Credentials file at ${t} is group/world-readable (mode 0o${i.toString(8)}); run \`chmod 600 ${t}\` before retrying.`);typeof process.getuid=="function"&&s.uid!==process.getuid()&&r(`credentials file at ${t} is owned by uid ${s.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function pc(n,r){const{fs:e,path:t}=await ce(async()=>{const{fs:a,path:c}=await import("./node.browser-C_s9kvmM.js");return{fs:a,path:c}},__vite__mapDeps([0,1,2])),s=t.dirname(n);await e.promises.mkdir(s,{recursive:!0,mode:448});const i=`${n}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{const a=await e.promises.open(i,"w",384);try{await a.writeFile(JSON.stringify(r,null,2)),await a.sync()}finally{await a.close()}await e.promises.rename(i,n)}catch(a){throw await e.promises.unlink(i).catch(()=>{}),a}try{const a=await e.promises.open(s,"r");try{await a.sync()}finally{await a.close()}}catch{}}async function Hl(n){if(!n.body)return"";const r=n.body.getReader(),e=[];let t=0;for(;;){const{done:i,value:a}=await r.read();if(i)break;if(t+a.length>Es){const c=Es-t;c>0&&e.push(a.subarray(0,c)),await r.cancel();break}e.push(a),t+=a.length}let s;if(e.length===1)s=e[0];else{s=new Uint8Array(e.reduce((a,c)=>a+c.length,0));let i=0;for(const a of e)s.set(a,i),i+=a.length}return new TextDecoder("utf-8").decode(s)}class B extends S{constructor(r,e=null,t=null,s=null){super(r),this.statusCode=e,this.body=t,this.requestId=s}}function Ue(){return Math.floor(Date.now()/1e3)}class Wl{constructor(r,e){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=r,this.onAdvisoryRefreshError=e}async getToken(){const r=this.nextForce;this.nextForce=!1;const e=this.cached;if(r||e==null)return(await this.refresh(r)).token;if(e.expiresAt==null)return e.token;const t=e.expiresAt-Ue();return t>Bl?e.token:t>ns?(this.backgroundRefresh(),e.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(r=!1){return this.pendingRefresh&&!r?this.pendingRefresh:this.doRefresh(r)}backgroundRefresh(){this.pendingRefresh||Ue()-this.lastAdvisoryError<Dl||this.doRefresh().catch(r=>{this.lastAdvisoryError=Ue(),this.onAdvisoryRefreshError?.(r)})}doRefresh(r=!1){return this.pendingRefresh=this.provider(r?{forceRefresh:!0}:void 0).then(e=>(this.cached=e,this.pendingRefresh=null,e),e=>{throw this.pendingRefresh=null,e}),this.pendingRefresh}}var zl={};const P=n=>{if(typeof globalThis.process<"u")return zl?.[n]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(n)?.trim()||void 0};function jl(n){let r=0;for(const s of n)r+=s.length;const e=new Uint8Array(r);let t=0;for(const s of n)e.set(s,t),t+=s.length;return e}let Ts;function _c(n){let r;return(Ts??(r=new globalThis.TextEncoder,Ts=r.encode.bind(r)))(n)}let $s;function Lr(n){let r;return($s??(r=new globalThis.TextDecoder,$s=r.decode.bind(r)))(n)}const Fl=n=>{if(typeof globalThis.Buffer<"u"){const r=globalThis.Buffer.from(n,"base64");return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}if(typeof atob<"u"){const r=atob(n),e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}throw new S("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")},Vn="warn",Jn={off:0,error:200,warn:300,info:400,debug:500},Nr=(n,r,e)=>{if(n){if(gl(Jn,n))return n;e.warn(`${r} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Jn))}`)}};function st(){}function Qt(n,r,e){return!r||Jn[n]>Jn[e]?st:r[n].bind(r)}const ql={error:st,warn:st,info:st,debug:st};let Is=new WeakMap;function Br(n,r){const e=Is.get(n);if(e&&e[0]===r)return e[1];const t={error:Qt("error",n,r),warn:Qt("warn",n,r),info:Qt("info",n,r),debug:Qt("debug",n,r)};return Is.set(n,[r,t]),t}function O(n){const r=n.logger,e=n.logLevel??"off";return r?Br(r,e):ql}let Ps,er;function Kl(){const n=P("ANTHROPIC_LOG");return(!er||n!==Ps)&&(Ps=n,er=Br(console,Nr(n,"process.env['ANTHROPIC_LOG']",Br(console,Vn))??Vn)),er}function Ae(n,r,e){n.debug!==st&&n.debug(r,Vl(e))}const Vl=n=>(n.options&&(n.options={...n.options},delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([r,e])=>[r,r.toLowerCase()==="authorization"||r.toLowerCase()==="api-key"||r.toLowerCase()==="x-api-key"||r.toLowerCase()==="cookie"||r.toLowerCase()==="set-cookie"?"***":e]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);let Dr=function(){const{crypto:n}=globalThis;if(n?.randomUUID)return Dr=n.randomUUID.bind(n),n.randomUUID();const r=new Uint8Array(1),e=n?()=>n.getRandomValues(r)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,t=>(+t^e()&15>>+t/4).toString(16))};const gc="1.0",Jl=/^[A-Za-z0-9_.-]+$/;function mc(n){if(!n)throw new Error("profile name is empty");if(n==="."||n==="..")throw new Error(`profile name "${n}" is not allowed`);if(n.includes("/")||n.includes("\\"))throw new Error(`profile name "${n}" must not contain path separators`);if(!Jl.test(n))throw new Error(`profile name "${n}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}const Xl=async n=>{var r,e;const t=await rs();if(t===null)return null;const s=n??await wc();if(s===null)return null;mc(s);const{fs:i,path:a}=await ce(async()=>{const{fs:d,path:g}=await import("./node.browser-C_s9kvmM.js");return{fs:d,path:g}},__vite__mapDeps([0,1,2])),c=a.join(t,"configs",`${s}.json`);let u;try{u=await i.promises.readFile(c,"utf-8")}catch(d){if(d?.code!=="ENOENT")throw new Error(`failed to read config file ${c}: ${d}`);u=null}if(u===null){const d=P("ANTHROPIC_ORGANIZATION_ID"),g=P("ANTHROPIC_IDENTITY_TOKEN_FILE"),_=P("ANTHROPIC_FEDERATION_RULE_ID");return _&&d?{fromFile:!1,config:{organization_id:d,workspace_id:P("ANTHROPIC_WORKSPACE_ID"),base_url:P("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:_,service_account_id:P("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:g?{source:"file",path:g}:void 0,scope:P("ANTHROPIC_SCOPE")}}}:null}let l;try{l=JSON.parse(u)}catch(d){throw new Error(`failed to parse config file ${c}: ${d}`)}if(!l.authentication)throw new Error(`config file ${c} is missing "authentication"`);const p=l.authentication.type;if(p!=="oidc_federation"&&p!=="user_oauth")throw new Error(`authentication.type "${p}" is not a known authentication type`);if(l.organization_id??(l.organization_id=P("ANTHROPIC_ORGANIZATION_ID")),l.workspace_id??(l.workspace_id=P("ANTHROPIC_WORKSPACE_ID")),l.base_url??(l.base_url=P("ANTHROPIC_BASE_URL")),(r=l.authentication).scope??(r.scope=P("ANTHROPIC_SCOPE")),l.authentication.type==="oidc_federation"){if(!l.authentication.identity_token){const d=P("ANTHROPIC_IDENTITY_TOKEN_FILE");d&&(l.authentication.identity_token={source:"file",path:d})}l.authentication.federation_rule_id||(l.authentication.federation_rule_id=P("ANTHROPIC_FEDERATION_RULE_ID")??""),(e=l.authentication).service_account_id??(e.service_account_id=P("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:l,fromFile:!0}},Gl=async(n,r)=>{if(n?.authentication.credentials_path)return n.authentication.credentials_path;const e=await rs();if(!e)return null;const t=r??await wc();if(!t)return null;mc(t);const{path:s}=await ce(async()=>{const{path:i}=await import("./node.browser-C_s9kvmM.js");return{path:i}},__vite__mapDeps([0,1,2]));return s.join(e,"credentials",`${t}.json`)},rs=async()=>{if(!Ql())return null;const{path:n}=await ce(async()=>{const{path:i}=await import("./node.browser-C_s9kvmM.js");return{path:i}},__vite__mapDeps([0,1,2])),r=P("ANTHROPIC_CONFIG_DIR");if(r)return r;if(es()["X-Stainless-OS"]==="Windows"){const i=P("APPDATA");if(i)return n.join(i,"Anthropic");const a=P("USERPROFILE");return a?n.join(a,"AppData","Roaming","Anthropic"):null}const t=P("XDG_CONFIG_HOME");if(t)return n.join(t,"anthropic");const s=P("HOME");return s?n.join(s,".config","anthropic"):null},Ql=()=>{const n=es()["X-Stainless-Runtime"];return n==="node"||n==="deno"},wc=async()=>{const n=await rs();if(!n)return null;const r=P("ANTHROPIC_PROFILE");if(r)return r;const{fs:e,path:t}=await ce(async()=>{const{fs:i,path:a}=await import("./node.browser-C_s9kvmM.js");return{fs:i,path:a}},__vite__mapDeps([0,1,2])),s=t.join(n,"active_config");try{return(await e.promises.readFile(s,"utf-8")).trim()||"default"}catch(i){if(i?.code!=="ENOENT")throw new Error(`failed to read ${s}: ${i}`);return"default"}};function Ms(n){if(!n)throw new S("Identity token file path is empty");return async()=>{const{fs:r}=await ce(async()=>{const{fs:s}=await import("./node.browser-C_s9kvmM.js");return{fs:s}},__vite__mapDeps([0,1,2]));let e;try{e=await r.promises.readFile(n,"utf-8")}catch(s){throw new S(`Failed to read identity token file at ${n}: ${s}`)}const t=e.trim();if(!t)throw new S(`Identity token file at ${n} is empty`);return t}}function Yl(n){if(!n)throw new S("Identity token value is empty");return()=>n}function Zl(n){return async()=>{dc(n.baseURL);const r=await n.identityTokenProvider();if(r.length>16*1024)throw new B(`Identity token is ${Math.ceil(r.length/1024)} KiB, exceeds the 16 KiB assertion limit`);const e={grant_type:Cl,assertion:r,federation_rule_id:n.federationRuleId,organization_id:n.organizationId};n.serviceAccountId&&(e.service_account_id=n.serviceAccountId),n.workspaceId&&(e.workspace_id=n.workspaceId);const t=`${n.baseURL}${uc}`;let s;try{s=await n.fetch(t,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${Kn},${Nl}`,"User-Agent":n.userAgent||`anthropic-sdk-typescript/${ge} oidcFederationProvider`},body:JSON.stringify(e)})}catch(u){throw new B(`Failed to reach token endpoint ${t}: ${u}`)}const i=s.headers.get("Request-Id");if(!s.ok){const u=await s.text().catch(()=>""),l=ie(u);let p="";throw s.status===401&&(p=` Ensure your federation rule matches your identity token. ${n.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new B(`Token exchange failed with status ${s.status}${i?` (request-id ${i})`:""}: ${l}${p}`,s.status,l,i)}const a=await hc(s,i),c=Number(a.expires_in);if(!Number.isFinite(c))throw new B(`Token endpoint response missing required fields: ${JSON.stringify(ie(a))}`,s.status,ie(a),i);return{token:a.access_token,expiresAt:Ue()+c}}}function eu(n){return async r=>{const{fs:e}=await ce(async()=>{const{fs:x}=await import("./node.browser-C_s9kvmM.js");return{fs:x}},__vite__mapDeps([0,1,2]));await fc(n.credentialsPath,n.onSafetyWarning);let t;try{t=await e.promises.readFile(n.credentialsPath,"utf-8")}catch(x){throw new B(`Credentials file not found at ${n.credentialsPath}: ${x}`)}let s;try{s=JSON.parse(t)}catch(x){throw new B(`Credentials file at ${n.credentialsPath} is not valid JSON: ${x}`)}const i=s.access_token;if(!i)throw new B(`Credentials file at ${n.credentialsPath} must include 'access_token'`);const a=s.expires_at;if(!r?.forceRefresh&&(a==null||Ue()<a-ns))return{token:i,expiresAt:a??null};const c=s.refresh_token;if(!n.clientId||!c)throw new B(`Access token at ${n.credentialsPath} has expired and no refresh is available (client_id ${n.clientId?"set":"empty"}, refresh_token ${c?"set":"empty"})`);dc(n.baseURL);const u={grant_type:Ll,refresh_token:c,client_id:n.clientId},l=`${n.baseURL}${uc}`;let p;try{p=await n.fetch(l,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":Kn,"User-Agent":n.userAgent||`anthropic-sdk-typescript/${ge} userOAuthProvider`},body:JSON.stringify(u)})}catch(x){throw new B(`User OAuth refresh failed to reach token endpoint: ${x}`)}const d=p.headers.get("Request-Id");if(!p.ok){const x=await p.text().catch(()=>"");throw new B(`User OAuth refresh failed (HTTP ${p.status}): ${ie(x)}`,p.status,ie(x),d)}const g=await hc(p,d),_=Number(g.expires_in);if(!Number.isFinite(_))throw new B(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(ie(g))}`,p.status,ie(g),d);const m=Ue()+_,y=g.refresh_token||c;return await pc(n.credentialsPath,{...s,version:gc,type:"oauth_token",access_token:g.access_token,expires_at:m,refresh_token:y}),{token:g.access_token,expiresAt:m}}}function yc(n,r){const e=n.authentication.credentials_path??null,t=(n.base_url||r.baseURL).replace(/\/+$/,""),s=nu(n,e,t,r),i={};return n.workspace_id&&n.authentication.type==="user_oauth"&&(i["anthropic-workspace-id"]=n.workspace_id),{provider:s,extraHeaders:i,baseURL:n.base_url||void 0}}async function tu(n,r){const e=await Xl(r);if(!e)return null;const{config:t,fromFile:s}=e,i=t.authentication.credentials_path||!s?t:{...t,authentication:{...t.authentication,credentials_path:await Gl(t,r)??void 0}};return yc(i,n)}function nu(n,r,e,t){switch(n.authentication.type){case"oidc_federation":{const s=n.authentication,i=ru(s);if(!i)throw new B("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)");if(!s.federation_rule_id)throw new B("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");if(!n.organization_id)throw new B("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");const a=Zl({identityTokenProvider:i,federationRuleId:s.federation_rule_id,organizationId:n.organization_id,serviceAccountId:s.service_account_id,workspaceId:n.workspace_id,baseURL:e,fetch:t.fetch,userAgent:t.userAgent});return r?su(a,r,t.onCacheWriteError,t.onSafetyWarning):a}case"user_oauth":{if(!r)throw new B("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return eu({credentialsPath:r,clientId:n.authentication.client_id,baseURL:e,fetch:t.fetch,userAgent:t.userAgent,onSafetyWarning:t.onSafetyWarning})}default:{const s=n.authentication.type;throw new B(`authentication.type "${s}" is not a known authentication type`)}}}function ru(n){if(n.identity_token){const t=n.identity_token.source;if(t!=="file")throw new B(`identity_token.source "${t}" is not supported by this SDK version (only "file")`);if(!n.identity_token.path)throw new B('identity_token.source "file" requires a non-empty path');return Ms(n.identity_token.path)}const r=P("ANTHROPIC_IDENTITY_TOKEN_FILE");if(r)return Ms(r);const e=P("ANTHROPIC_IDENTITY_TOKEN");return e?Yl(e):null}function su(n,r,e,t){return async s=>{const{fs:i}=await ce(async()=>{const{fs:u}=await import("./node.browser-C_s9kvmM.js");return{fs:u}},__vite__mapDeps([0,1,2]));await fc(r,t);let a;try{const u=await i.promises.readFile(r,"utf-8");a=JSON.parse(u);const l=a?.access_token;if(l&&!s?.forceRefresh){const p=a?.expires_at;if(p==null||Ue()<p-ns)return{token:l,expiresAt:p??null}}}catch(u){u?.code!=="ENOENT"&&!(u instanceof SyntaxError)&&e?.(u)}const c=await n(s);try{await pc(r,{...a??{},version:gc,type:"oauth_token",access_token:c.token,expires_at:c.expiresAt})}catch(u){e?.(u)}return c}}var G,Q,ss=(()=>{class n{constructor(){G.set(this,void 0),Q.set(this,void 0),w(this,G,new Uint8Array),w(this,Q,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?_c(e):e;w(this,G,jl([o(this,G,"f"),t]));const s=[];let i;for(;(i=iu(o(this,G,"f"),o(this,Q,"f")))!=null;){if(i.carriage&&o(this,Q,"f")==null){w(this,Q,i.index);continue}if(o(this,Q,"f")!=null&&(i.index!==o(this,Q,"f")+1||i.carriage)){s.push(Lr(o(this,G,"f").subarray(0,o(this,Q,"f")-1))),w(this,G,o(this,G,"f").subarray(o(this,Q,"f"))),w(this,Q,null);continue}const a=o(this,Q,"f")!==null?i.preceding-1:i.preceding,c=Lr(o(this,G,"f").subarray(0,a));s.push(c),w(this,G,o(this,G,"f").subarray(i.index)),w(this,Q,null)}return s}flush(){return o(this,G,"f").length?this.decode(`
|
|
3
|
+
`):[]}}return G=new WeakMap,Q=new WeakMap,n.NEWLINE_CHARS=new Set([`
|
|
4
|
+
`,"\r"]),n.NEWLINE_REGEXP=/\r\n|[\n\r]/g,n})();function iu(n,r){for(let s=r??0;s<n.length;s++){if(n[s]===10)return{preceding:s,index:s+1,carriage:!1};if(n[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}var ht,dt=(()=>{class n{constructor(e,t,s){this.iterator=e,ht.set(this,void 0),this.controller=t,w(this,ht,s)}static rawEvents(e,t=new AbortController){return Os(e,t)}static fromSSEResponse(e,t,s){let i=!1;const a=s?O(s):console;async function*c(){if(i)throw new S("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let u=!1;try{for await(const l of Os(e,t)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(p){throw a.error("Could not parse message into JSON:",l.data),a.error("From chunk:",l.raw),p}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop"||l.event==="message"||l.event==="user.message"||l.event==="user.interrupt"||l.event==="user.tool_confirmation"||l.event==="user.custom_tool_result"||l.event==="user.tool_result"||l.event==="agent.message"||l.event==="agent.thinking"||l.event==="agent.tool_use"||l.event==="agent.tool_result"||l.event==="agent.mcp_tool_use"||l.event==="agent.mcp_tool_result"||l.event==="agent.custom_tool_use"||l.event==="agent.thread_context_compacted"||l.event==="session.status_running"||l.event==="session.status_idle"||l.event==="session.status_rescheduled"||l.event==="session.status_terminated"||l.event==="session.error"||l.event==="session.deleted"||l.event==="session.updated"||l.event==="span.model_request_start"||l.event==="span.model_request_end"||l.event==="span.outcome_evaluation_start"||l.event==="span.outcome_evaluation_ongoing"||l.event==="span.outcome_evaluation_end"||l.event==="user.define_outcome"||l.event==="agent.thread_message_received"||l.event==="agent.thread_message_sent"||l.event==="agent.session_thread_message_received"||l.event==="agent.session_thread_message_sent"||l.event==="session.thread_created"||l.event==="session.thread_status_created"||l.event==="session.thread_status_running"||l.event==="session.thread_status_idle"||l.event==="session.thread_status_rescheduled"||l.event==="session.thread_status_terminated"||l.event==="event_start"||l.event==="event_delta"||l.event==="system.message")try{yield JSON.parse(l.data)}catch(p){throw a.error("Could not parse message into JSON:",l.data),a.error("From chunk:",l.raw),p}if(l.event!=="ping"&&l.event==="error"){const p=tc(l.data)??l.data,d=p?.error?.type;throw new z(void 0,p,void 0,e.headers,d)}}u=!0}catch(l){if(lt(l))return;throw l}finally{u||t.abort(),De(t)}}return new n(c,t,s)}static fromReadableStream(e,t,s){let i=!1;async function*a(){const u=new ss,l=ts(e);for await(const p of l)for(const d of u.decode(p))yield d;for(const p of u.flush())yield p}async function*c(){if(i)throw new S("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let u=!1;try{for await(const l of a())u||l&&(yield JSON.parse(l));u=!0}catch(l){if(lt(l))return;throw l}finally{u||t.abort(),De(t)}}return new n(c,t,s)}[(ht=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],s=this.iterator(),i=a=>({next:()=>{if(a.length===0){const c=s.next();e.push(c),t.push(c)}return a.shift()}});return[new n(()=>i(e),this.controller,o(this,ht,"f")),new n(()=>i(t),this.controller,o(this,ht,"f"))]}toReadableStream(){const e=this;let t;return rc({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{const{value:i,done:a}=await t.next();if(a)return s.close();const c=_c(JSON.stringify(i)+`
|
|
5
|
+
`);s.enqueue(c)}catch(i){s.error(i)}},async cancel(){await t.return?.()}})}}return n})();async function*Os(n,r){if(!n.body)throw r.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new S("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new S("Attempted to iterate over a response with no body");const e=new au,t=new ss,s=ts(n.body);for await(const i of s)for(const a of t.decode(i)){const c=e.decode(a);c&&(yield c)}for(const i of t.flush()){const a=e.decode(i);a&&(yield a)}}class au{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(r){if(r.endsWith("\r")&&(r=r.substring(0,r.length-1)),!r){if(!this.event&&!this.data.length)return null;const i={event:this.event,data:this.data.join(`
|
|
6
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(r),r.startsWith(":"))return null;let[e,t,s]=ou(r,":");return s.startsWith(" ")&&(s=s.substring(1)),e==="event"?this.event=s:e==="data"&&this.data.push(s),null}}function ou(n,r){const e=n.indexOf(r);return e!==-1?[n.substring(0,e),r,n.substring(e+r.length)]:[n,"",""]}async function bc(n,r){const{response:e,requestLogID:t,retryOfRequestLogID:s,startTime:i}=r,a=await(async()=>{if(r.options.stream)return O(n).debug("response",e.status,e.url,e.headers,e.body),dt.fromSSEResponse(e,r.controller,n);if(e.status===204)return null;if(r.options.__binaryResponse)return e;const u=e.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){if(e.headers.get("content-length")==="0")return;const g=await e.json();return is(g,e)}return await e.text()})().finally(()=>{!r.options.stream&&!r.options.__binaryResponse&&De(r.controller)});return Ae(O(n),`[${t}] response parsed`,{retryOfRequestLogID:s,url:e.url,status:e.status,body:a,durationMs:Date.now()-i}),a}function is(n,r){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperties(n,{_request_id:{value:r.headers.get("request-id"),enumerable:!1},_workspace_id:{value:r.headers.get("anthropic-workspace-id"),enumerable:!1}})}const vc=new WeakSet;function kc(n){return typeof n=="object"&&n!==null&&vc.has(n)}function cu(n){const r=new Set;for(;typeof n=="object"&&n!==null&&!r.has(n);){if(r.add(n),kc(n)||lt(n)||n instanceof ut||n instanceof ll)return!0;n=n.cause}return!1}function Cs(n,r,e,t){return async(s,i={})=>{if(r.length===0)return n.call(void 0,s,i);const a=i.headers instanceof Headers?i.headers:new Headers(i.headers),c=await uu(n,r,e,t)({...i,headers:a,url:typeof s=="string"?s:s instanceof URL?s.href:s.url});if(c.bodyUsed||c.body?.locked)throw new S("middleware consumed the response body; use response.clone() to inspect it, or return new Response(body, response) to consume and replace it");return c}}function lu(n,r){const e=new WeakMap;return{options:n,logger:r?O(r):Kl(),parse(t){if(n?.stream&&t.ok)return Ls(t,n,r);let s=e.get(t);return s||(s=Ls(t,n,r),e.set(t,s)),s}}}async function Ls(n,r,e){if(n.bodyUsed||n.body?.locked)throw new S("cannot ctx.parse() a response whose body was already consumed; call ctx.parse() instead of reading the body, or read via response.clone()");if(r?.stream&&n.ok)return dt.fromSSEResponse(n.clone(),new AbortController,e);if(n.status===204)return null;if(r?.__binaryResponse)return n;const s=n.headers.get("content-type")?.split(";")[0]?.trim();return s?.includes("application/json")||s?.endsWith("+json")?n.headers.get("content-length")==="0"?void 0:is(await n.clone().json(),n):await n.clone().text()}function uu(n,r,e,t){let s=async({url:a,...c})=>{try{return await n.call(void 0,a,c)}catch(u){const l=jn(u);throw vc.add(l),l}};const i=lu(e,t);for(let a=r.length-1;a>=0;a--){const c=r[a],u=s;s=async l=>c(l,u,i)}return s}var ft,Sc=(()=>{class n extends Promise{constructor(e,t,s=bc){super(i=>{i(null)}),this.responsePromise=t,this.parseResponse=s,ft.set(this,void 0),w(this,ft,e)}_thenUnwrap(e){return new n(o(this,ft,"f"),this.responsePromise,async(t,s)=>is(e(await this.parseResponse(t,s),s),s.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"),workspace_id:t.headers.get("anthropic-workspace-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(o(this,ft,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}return ft=new WeakMap,n})(),Yt,as=(()=>{class n{constructor(e,t,s,i){Yt.set(this,void 0),w(this,Yt,e),this.options=i,this.response=t,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new S("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await o(this,Yt,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Yt=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}return n})(),du=(()=>{class n extends Sc{constructor(e,t,s){super(e,t,async(i,a)=>new s(i,a.response,await bc(i,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}return n})();class X extends as{constructor(r,e,t,s){super(r,e,t,s),this.data=t.data||[],this.has_more=t.has_more||!1,this.first_id=t.first_id||null,this.last_id=t.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){const e=this.first_id;return e?{...this.options,query:{...Fn(this.options.query),before_id:e}}:null}const r=this.last_id;return r?{...this.options,query:{...Fn(this.options.query),after_id:r}}:null}}class A extends as{constructor(r,e,t,s){super(r,e,t,s),this.data=t.data||[],this.next_page=t.next_page||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.nextPageRequestOptions()!=null}nextPageRequestOptions(){const r=this.next_page;return r?{...this.options,query:{...Fn(this.options.query),page:r}}:null}}class hu extends as{constructor(r,e,t,s){super(r,e,t,s),this.data=t.data||[],this.next_page=t.next_page||null,this.prev_page=t.prev_page||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.nextPageRequestOptions()!=null}nextPageRequestOptions(){const r=this.next_page;return r?{...this.options,query:{...Fn(this.options.query),page:r}}:null}}const xc=()=>{if(typeof File>"u"){const{process:n}=globalThis,r=typeof n?.versions?.node=="string"&&parseInt(n.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(r?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function at(n,r,e){return xc(),new File(n,r??"",e)}function Hn(n,r){const e=typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"";return r?e.split(/[\\/]/).pop()||void 0:e}const Rc=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",me=async(n,r,e=!0)=>({...n,body:await pu(n.body,r,e)}),Ns=new WeakMap;function fu(n){const r=typeof n=="function"?n:n.fetch,e=Ns.get(r);if(e)return e;const t=(async()=>{try{const s="Response"in r?r.Response:(await r("data:,")).constructor,i=new FormData;return i.toString()!==await new s(i).text()}catch{return!0}})();return Ns.set(r,t),t}const pu=async(n,r,e=!0)=>{if(!await fu(r))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(n||{}).map(([s,i])=>Ur(t,s,i,e))),t},Ur=async(n,r,e,t)=>{if(e!==void 0){if(e==null)throw new TypeError(`Received null for "${r}"; to pass null in FormData, you must use the string 'null'`);if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")n.append(r,String(e));else if(e instanceof Response){let s={};const i=e.headers.get("Content-Type");i&&(s={type:i}),n.append(r,at([await e.blob()],Hn(e,t),s))}else if(Rc(e))n.append(r,at([await new Response(sc(e)).blob()],Hn(e,t)));else if(e instanceof Blob){const i=typeof File<"u"&&e instanceof File?e.name:Hn(e,t);n.append(r,at([e],i,{type:e.type}))}else if(Array.isArray(e))await Promise.all(e.map(s=>Ur(n,r+"[]",s,t)));else{if(typeof e.then=="function")throw new TypeError(`Received a Promise for "${r}"; await it first, e.g. \`await toFile(...)\``);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))throw new TypeError(`Received ${e.constructor.name} for "${r}"; to upload raw bytes, wrap them with \`await toFile(bytes, 'filename')\``);if(typeof e=="object")await Promise.all(Object.entries(e).map(([s,i])=>Ur(n,`${r}[${s}]`,i,t)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${e} instead`)}}},Ac=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",_u=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&Ac(n),gu=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function mu(n,r,e){if(xc(),n=await n,r||(r=n instanceof File?n.name:Hn(n,!0)),_u(n))return n instanceof File&&r==null&&e==null?n:at([await n.arrayBuffer()],r??n.name,{type:n.type,lastModified:n.lastModified,...e});if(gu(n)){const s=await n.blob();return r||(r=new URL(n.url).pathname.split(/[\\/]/).pop()),at(await Hr(s),r,e)}const t=await Hr(n);if(!e?.type){const s=t.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof s=="string"&&(e={...e,type:s})}return at(t,r,e)}async function Hr(n){let r=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)r.push(n);else if(Ac(n))r.push(n instanceof Blob?n:await n.arrayBuffer());else if(Rc(n))for await(const e of n)r.push(...await Hr(e));else{const e=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${e?`; constructor: ${e}`:""}${wu(n)}`)}return r}function wu(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(e=>`"${e}"`).join(", ")}]`}class v{constructor(r){this._client=r}}const Ec=Symbol.for("brand.privateNullableHeaders");function*yu(n){if(!n)return;if(Ec in n){const{values:t,nulls:s}=n;yield*t.entries();for(const i of s)yield[i,null];return}let r=!1,e;n instanceof Headers?e=n.entries():ws(n)?e=n:(r=!0,e=Object.entries(n??{}));for(let t of e){const s=t[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const i=ws(t[1])?t[1]:[t[1]];let a=!1;for(const c of i)c!==void 0&&(r&&!a&&(a=!0,yield[s,Wn]),yield[s,c])}}const Wn=Symbol("clear"),bu=new Set(["x-stainless-helper"]),vu=(n,r)=>{const e=n?n.split(",").map(t=>t.trim()).filter(Boolean):[];for(const t of r.split(",").map(s=>s.trim()))t&&!e.includes(t)&&e.push(t);return e.join(", ")},f=n=>{const r=new Headers,e=new Set;for(const t of n){const s=new Set;for(const[i,a]of yu(t)){const c=i.toLowerCase();if(bu.has(c)){if(a===Wn)continue;a===null?(r.delete(i),e.add(c)):(r.set(i,vu(r.get(i),a)),e.delete(c));continue}(a===Wn||!s.has(c))&&(r.delete(i),s.add(c),a===Wn)||(a===null?(r.delete(i),e.add(c)):(r.append(i,a),e.delete(c)))}}return{[Ec]:!0,values:r,nulls:e}};function Tc(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Bs=Object.freeze(Object.create(null)),ku=(n=Tc)=>function(e,...t){if(e.length===1)return e[0];let s=!1;const i=[],a=e.reduce((p,d,g)=>{/[?#]/.test(d)&&(s=!0);const _=t[g];let m=(s?encodeURIComponent:n)(""+_);return g!==t.length&&(_==null||typeof _=="object"&&_.toString===Object.getPrototypeOf(Object.getPrototypeOf(_.hasOwnProperty??Bs)??Bs)?.toString)&&(m=_+"",i.push({start:p.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(_).slice(8,-1)} is not a valid path parameter`})),p+d+(g===t.length?"":m)},""),c=a.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let l;for(;(l=u.exec(c))!==null;)i.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(i.sort((p,d)=>p.start-d.start),i.length>0){let p=0;const d=i.reduce((g,_)=>{const m=" ".repeat(_.start-p),y="^".repeat(_.length);return p=_.start+_.length,g+m+y},"");throw new S(`Path parameters result in path with invalid segments:
|
|
7
|
+
${i.map(g=>g.error).join(`
|
|
8
|
+
`)}
|
|
9
|
+
${a}
|
|
10
|
+
${d}`)}return a},h=ku(Tc);class Ds extends v{retrieve(r,e={},t){const{betas:s,workspace_id:i}=e??{};return this._client.get(h`/v1/deployment_runs/${r}?beta=true`,{...t,headers:f([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}list(r={},e){const{betas:t,workspace_id:s,...i}=r??{};return this._client.getAPIList("/v1/deployment_runs?beta=true",A,{query:i,...e,headers:f([{"anthropic-beta":[...t??[],"managed-agents-2026-04-01"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},e?.headers])})}}class Us extends v{create(r,e){const{betas:t,workspace_id:s,...i}=r;return this._client.post("/v1/deployments?beta=true",{body:i,...e,headers:f([{"anthropic-beta":[...t??[],"managed-agents-2026-04-01"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},e?.headers])})}retrieve(r,e={},t){const{betas:s,workspace_id:i}=e??{};return this._client.get(h`/v1/deployments/${r}?beta=true`,{...t,headers:f([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}update(r,e,t){const{betas:s,workspace_id:i,...a}=e;return this._client.post(h`/v1/deployments/${r}?beta=true`,{body:a,...t,headers:f([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}list(r={},e){const{betas:t,workspace_id:s,...i}=r??{};return this._client.getAPIList("/v1/deployments?beta=true",A,{query:i,...e,headers:f([{"anthropic-beta":[...t??[],"managed-agents-2026-04-01"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},e?.headers])})}archive(r,e={},t){const{betas:s,workspace_id:i}=e??{};return this._client.post(h`/v1/deployments/${r}/archive?beta=true`,{...t,headers:f([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}pause(r,e={},t){const{betas:s,workspace_id:i}=e??{};return this._client.post(h`/v1/deployments/${r}/pause?beta=true`,{...t,headers:f([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}run(r,e={},t){const{betas:s,workspace_id:i}=e??{};return this._client.post(h`/v1/deployments/${r}/run?beta=true`,{...t,headers:f([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}unpause(r,e={},t){const{betas:s,workspace_id:i}=e??{};return this._client.post(h`/v1/deployments/${r}/unpause?beta=true`,{...t,headers:f([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}}class Hs extends v{create(r,e){const{betas:t,workspace_id:s,...i}=r;return this._client.post("/v1/dreams?beta=true",{body:i,...e,headers:f([{"anthropic-beta":[...t??[],"dreaming-2026-04-21"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},e?.headers])})}retrieve(r,e={},t){const{betas:s,workspace_id:i}=e??{};return this._client.get(h`/v1/dreams/${r}?beta=true`,{...t,headers:f([{"anthropic-beta":[...s??[],"dreaming-2026-04-21"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}list(r={},e){const{betas:t,workspace_id:s,...i}=r??{};return this._client.getAPIList("/v1/dreams?beta=true",A,{query:i,...e,headers:f([{"anthropic-beta":[...t??[],"dreaming-2026-04-21"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},e?.headers])})}archive(r,e={},t){const{betas:s,workspace_id:i}=e??{};return this._client.post(h`/v1/dreams/${r}/archive?beta=true`,{...t,headers:f([{"anthropic-beta":[...s??[],"dreaming-2026-04-21"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}cancel(r,e={},t){const{betas:s,workspace_id:i}=e??{};return this._client.post(h`/v1/dreams/${r}/cancel?beta=true`,{...t,headers:f([{"anthropic-beta":[...s??[],"dreaming-2026-04-21"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}}const Xt="x-stainless-helper",os="x-stainless-helper-method";function $c(n){return{[Xt]:n}}const Ee=Symbol("anthropic.sdk.stainlessHelper");function it(n){return typeof n=="object"&&n!==null&&Ee in n}function Ic(n,r){const e=new Set;if(n)for(const t of n)it(t)&&e.add(t[Ee]);if(r)for(const t of r){it(t)&&e.add(t[Ee]);const s=t.content;if(Array.isArray(s))for(const i of s){it(i)&&e.add(i[Ee]);const a=i?.tool?.definition;it(a)&&e.add(a[Ee])}}return Array.from(e)}function Pc(n,r){const e=Ic(n,r);return e.length===0?{}:{[Xt]:e.join(", ")}}function Mc(n){return it(n)?{[Xt]:n[Ee]}:{}}let Ws=class extends v{list(r={},e){const{betas:t,workspace_id:s,...i}=r??{};return this._client.getAPIList("/v1/files?beta=true",A,{query:i,...e,headers:f([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0,...s!=null?{"anthropic-workspace-id":s}:void 0},e?.headers])})}delete(r,e={},t){const{betas:s,workspace_id:i}=e??{};return this._client.delete(h`/v1/files/${r}?beta=true`,{...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}download(r,e={},t){const{betas:s,workspace_id:i}=e??{};return this._client.get(h`/v1/files/${r}/content?beta=true`,{...t,headers:f([{Accept:"application/binary",...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers]),__binaryResponse:!0})}retrieveMetadata(r,e={},t){const{betas:s,workspace_id:i}=e??{};return this._client.get(h`/v1/files/${r}?beta=true`,{...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}upload(r,e){const{betas:t,workspace_id:s,...i}=r;return this._client.post("/v1/files?beta=true",me({body:i,...e,headers:f([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0,...s!=null?{"anthropic-workspace-id":s}:void 0},Mc(i.file),e?.headers])},this._client))}},zs=class extends v{retrieve(r,e={},t){const{betas:s,workspace_id:i}=e??{};return this._client.get(h`/v1/models/${r}?beta=true`,{...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}list(r={},e){const{betas:t,workspace_id:s,...i}=r??{};return this._client.getAPIList("/v1/models?beta=true",X,{query:i,...e,headers:f([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0,...s!=null?{"anthropic-workspace-id":s}:void 0},e?.headers])})}};class js extends v{create(r,e){const{betas:t,workspace_id:s,...i}=r;return this._client.post("/v1/user_profiles?beta=true",{body:i,...e,headers:f([{"anthropic-beta":[...t??[],"user-profiles-2026-08-18"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},e?.headers])})}retrieve(r,e={},t){const{betas:s,workspace_id:i}=e??{};return this._client.get(h`/v1/user_profiles/${r}?beta=true`,{...t,headers:f([{"anthropic-beta":[...s??[],"user-profiles-2026-08-18"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}update(r,e,t){const{betas:s,workspace_id:i,...a}=e;return this._client.post(h`/v1/user_profiles/${r}?beta=true`,{body:a,...t,headers:f([{"anthropic-beta":[...s??[],"user-profiles-2026-08-18"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}list(r={},e){const{betas:t,workspace_id:s,...i}=r??{};return this._client.getAPIList("/v1/user_profiles?beta=true",A,{query:i,...e,headers:f([{"anthropic-beta":[...t??[],"user-profiles-2026-08-18"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},e?.headers])})}createEnrollmentURL(r,e={},t){const{betas:s,workspace_id:i}=e??{};return this._client.post(h`/v1/user_profiles/${r}/enrollment_url?beta=true`,{...t,headers:f([{"anthropic-beta":[...s??[],"user-profiles-2026-08-18"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}}var Te={},F={},Fs;function Su(){if(Fs)return F;Fs=1;var n=F&&F.__extends||(function(){var p=function(d,g){return p=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(_,m){_.__proto__=m}||function(_,m){for(var y in m)m.hasOwnProperty(y)&&(_[y]=m[y])},p(d,g)};return function(d,g){p(d,g);function _(){this.constructor=d}d.prototype=g===null?Object.create(g):(_.prototype=g.prototype,new _)}})();Object.defineProperty(F,"__esModule",{value:!0});var r=256,e=(function(){function p(d){d===void 0&&(d="="),this._paddingCharacter=d}return p.prototype.encodedLength=function(d){return this._paddingCharacter?(d+2)/3*4|0:(d*8+5)/6|0},p.prototype.encode=function(d){for(var g="",_=0;_<d.length-2;_+=3){var m=d[_]<<16|d[_+1]<<8|d[_+2];g+=this._encodeByte(m>>>18&63),g+=this._encodeByte(m>>>12&63),g+=this._encodeByte(m>>>6&63),g+=this._encodeByte(m>>>0&63)}var y=d.length-_;if(y>0){var m=d[_]<<16|(y===2?d[_+1]<<8:0);g+=this._encodeByte(m>>>18&63),g+=this._encodeByte(m>>>12&63),y===2?g+=this._encodeByte(m>>>6&63):g+=this._paddingCharacter||"",g+=this._paddingCharacter||""}return g},p.prototype.maxDecodedLength=function(d){return this._paddingCharacter?d/4*3|0:(d*6+7)/8|0},p.prototype.decodedLength=function(d){return this.maxDecodedLength(d.length-this._getPaddingLength(d))},p.prototype.decode=function(d){if(d.length===0)return new Uint8Array(0);for(var g=this._getPaddingLength(d),_=d.length-g,m=new Uint8Array(this.maxDecodedLength(_)),y=0,x=0,E=0,b=0,k=0,R=0,T=0;x<_-4;x+=4)b=this._decodeChar(d.charCodeAt(x+0)),k=this._decodeChar(d.charCodeAt(x+1)),R=this._decodeChar(d.charCodeAt(x+2)),T=this._decodeChar(d.charCodeAt(x+3)),m[y++]=b<<2|k>>>4,m[y++]=k<<4|R>>>2,m[y++]=R<<6|T,E|=b&r,E|=k&r,E|=R&r,E|=T&r;if(x<_-1&&(b=this._decodeChar(d.charCodeAt(x)),k=this._decodeChar(d.charCodeAt(x+1)),m[y++]=b<<2|k>>>4,E|=b&r,E|=k&r),x<_-2&&(R=this._decodeChar(d.charCodeAt(x+2)),m[y++]=k<<4|R>>>2,E|=R&r),x<_-3&&(T=this._decodeChar(d.charCodeAt(x+3)),m[y++]=R<<6|T,E|=T&r),E!==0)throw new Error("Base64Coder: incorrect characters for decoding");return m},p.prototype._encodeByte=function(d){var g=d;return g+=65,g+=25-d>>>8&6,g+=51-d>>>8&-75,g+=61-d>>>8&-15,g+=62-d>>>8&3,String.fromCharCode(g)},p.prototype._decodeChar=function(d){var g=r;return g+=(42-d&d-44)>>>8&-r+d-43+62,g+=(46-d&d-48)>>>8&-r+d-47+63,g+=(47-d&d-58)>>>8&-r+d-48+52,g+=(64-d&d-91)>>>8&-r+d-65+0,g+=(96-d&d-123)>>>8&-r+d-97+26,g},p.prototype._getPaddingLength=function(d){var g=0;if(this._paddingCharacter){for(var _=d.length-1;_>=0&&d[_]===this._paddingCharacter;_--)g++;if(d.length<4||g>2)throw new Error("Base64Coder: incorrect padding")}return g},p})();F.Coder=e;var t=new e;function s(p){return t.encode(p)}F.encode=s;function i(p){return t.decode(p)}F.decode=i;var a=(function(p){n(d,p);function d(){return p!==null&&p.apply(this,arguments)||this}return d.prototype._encodeByte=function(g){var _=g;return _+=65,_+=25-g>>>8&6,_+=51-g>>>8&-75,_+=61-g>>>8&-13,_+=62-g>>>8&49,String.fromCharCode(_)},d.prototype._decodeChar=function(g){var _=r;return _+=(44-g&g-46)>>>8&-r+g-45+62,_+=(94-g&g-96)>>>8&-r+g-95+63,_+=(47-g&g-58)>>>8&-r+g-48+52,_+=(64-g&g-91)>>>8&-r+g-65+0,_+=(96-g&g-123)>>>8&-r+g-97+26,_},d})(e);F.URLSafeCoder=a;var c=new a;function u(p){return c.encode(p)}F.encodeURLSafe=u;function l(p){return c.decode(p)}return F.decodeURLSafe=l,F.encodedLength=function(p){return t.encodedLength(p)},F.maxDecodedLength=function(p){return t.maxDecodedLength(p)},F.decodedLength=function(p){return t.decodedLength(p)},F}var zn={exports:{}},xu=zn.exports,qs;function Ru(){return qs||(qs=1,(function(n){(function(r,e){var t={};e(t);var s=t.default;for(var i in t)s[i]=t[i];n.exports=s})(xu,function(r){r.__esModule=!0,r.digestLength=32,r.blockSize=64;var e=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function t(g,_,m,y,x){for(var E,b,k,R,T,$,C,M,L,I,ne,we,ye;x>=64;){for(E=_[0],b=_[1],k=_[2],R=_[3],T=_[4],$=_[5],C=_[6],M=_[7],I=0;I<16;I++)ne=y+I*4,g[I]=(m[ne]&255)<<24|(m[ne+1]&255)<<16|(m[ne+2]&255)<<8|m[ne+3]&255;for(I=16;I<64;I++)L=g[I-2],we=(L>>>17|L<<15)^(L>>>19|L<<13)^L>>>10,L=g[I-15],ye=(L>>>7|L<<25)^(L>>>18|L<<14)^L>>>3,g[I]=(we+g[I-7]|0)+(ye+g[I-16]|0);for(I=0;I<64;I++)we=(((T>>>6|T<<26)^(T>>>11|T<<21)^(T>>>25|T<<7))+(T&$^~T&C)|0)+(M+(e[I]+g[I]|0)|0)|0,ye=((E>>>2|E<<30)^(E>>>13|E<<19)^(E>>>22|E<<10))+(E&b^E&k^b&k)|0,M=C,C=$,$=T,T=R+we|0,R=k,k=b,b=E,E=we+ye|0;_[0]+=E,_[1]+=b,_[2]+=k,_[3]+=R,_[4]+=T,_[5]+=$,_[6]+=C,_[7]+=M,y+=64,x-=64}return y}var s=(function(){function g(){this.digestLength=r.digestLength,this.blockSize=r.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return g.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this},g.prototype.clean=function(){for(var _=0;_<this.buffer.length;_++)this.buffer[_]=0;for(var _=0;_<this.temp.length;_++)this.temp[_]=0;this.reset()},g.prototype.update=function(_,m){if(m===void 0&&(m=_.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");var y=0;if(this.bytesHashed+=m,this.bufferLength>0){for(;this.bufferLength<64&&m>0;)this.buffer[this.bufferLength++]=_[y++],m--;this.bufferLength===64&&(t(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(m>=64&&(y=t(this.temp,this.state,_,y,m),m%=64);m>0;)this.buffer[this.bufferLength++]=_[y++],m--;return this},g.prototype.finish=function(_){if(!this.finished){var m=this.bytesHashed,y=this.bufferLength,x=m/536870912|0,E=m<<3,b=m%64<56?64:128;this.buffer[y]=128;for(var k=y+1;k<b-8;k++)this.buffer[k]=0;this.buffer[b-8]=x>>>24&255,this.buffer[b-7]=x>>>16&255,this.buffer[b-6]=x>>>8&255,this.buffer[b-5]=x>>>0&255,this.buffer[b-4]=E>>>24&255,this.buffer[b-3]=E>>>16&255,this.buffer[b-2]=E>>>8&255,this.buffer[b-1]=E>>>0&255,t(this.temp,this.state,this.buffer,0,b),this.finished=!0}for(var k=0;k<8;k++)_[k*4+0]=this.state[k]>>>24&255,_[k*4+1]=this.state[k]>>>16&255,_[k*4+2]=this.state[k]>>>8&255,_[k*4+3]=this.state[k]>>>0&255;return this},g.prototype.digest=function(){var _=new Uint8Array(this.digestLength);return this.finish(_),_},g.prototype._saveState=function(_){for(var m=0;m<this.state.length;m++)_[m]=this.state[m]},g.prototype._restoreState=function(_,m){for(var y=0;y<this.state.length;y++)this.state[y]=_[y];this.bytesHashed=m,this.finished=!1,this.bufferLength=0},g})();r.Hash=s;var i=(function(){function g(_){this.inner=new s,this.outer=new s,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var m=new Uint8Array(this.blockSize);if(_.length>this.blockSize)new s().update(_).finish(m).clean();else for(var y=0;y<_.length;y++)m[y]=_[y];for(var y=0;y<m.length;y++)m[y]^=54;this.inner.update(m);for(var y=0;y<m.length;y++)m[y]^=106;this.outer.update(m),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate);for(var y=0;y<m.length;y++)m[y]=0}return g.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},g.prototype.clean=function(){for(var _=0;_<this.istate.length;_++)this.ostate[_]=this.istate[_]=0;this.inner.clean(),this.outer.clean()},g.prototype.update=function(_){return this.inner.update(_),this},g.prototype.finish=function(_){return this.outer.finished?this.outer.finish(_):(this.inner.finish(_),this.outer.update(_,this.digestLength).finish(_)),this},g.prototype.digest=function(){var _=new Uint8Array(this.digestLength);return this.finish(_),_},g})();r.HMAC=i;function a(g){var _=new s().update(g),m=_.digest();return _.clean(),m}r.hash=a,r.default=a;function c(g,_){var m=new i(g).update(_),y=m.digest();return m.clean(),y}r.hmac=c;function u(g,_,m,y){var x=y[0];if(x===0)throw new Error("hkdf: cannot expand more");_.reset(),x>1&&_.update(g),m&&_.update(m),_.update(y),_.finish(g),y[0]++}var l=new Uint8Array(r.digestLength);function p(g,_,m,y){_===void 0&&(_=l),y===void 0&&(y=32);for(var x=new Uint8Array([1]),E=c(_,g),b=new i(E),k=new Uint8Array(b.digestLength),R=k.length,T=new Uint8Array(y),$=0;$<y;$++)R===k.length&&(u(k,b,m,x),R=0),T[$]=k[R++];return b.clean(),k.fill(0),x.fill(0),T}r.hkdf=p;function d(g,_,m,y){for(var x=new i(g),E=x.digestLength,b=new Uint8Array(4),k=new Uint8Array(E),R=new Uint8Array(E),T=new Uint8Array(y),$=0;$*E<y;$++){var C=$+1;b[0]=C>>>24&255,b[1]=C>>>16&255,b[2]=C>>>8&255,b[3]=C>>>0&255,x.reset(),x.update(_),x.update(b),x.finish(R);for(var M=0;M<E;M++)k[M]=R[M];for(var M=2;M<=m;M++){x.reset(),x.update(R).finish(R);for(var L=0;L<E;L++)k[L]^=R[L]}for(var M=0;M<E&&$*E+M<y;M++)T[$*E+M]=k[M]}for(var $=0;$<E;$++)k[$]=R[$]=0;for(var $=0;$<4;$++)b[$]=0;return x.clean(),T}r.pbkdf2=d})})(zn)),zn.exports}var Zt={},Ks;function Au(){if(Ks)return Zt;Ks=1,Object.defineProperty(Zt,"__esModule",{value:!0}),Zt.timingSafeEqual=r;function n(e,t=""){if(!e)throw new Error(t)}function r(e,t){if(e.byteLength!==t.byteLength)return!1;e instanceof DataView||(e=new DataView(ArrayBuffer.isView(e)?e.buffer:e)),t instanceof DataView||(t=new DataView(ArrayBuffer.isView(t)?t.buffer:t)),n(e instanceof DataView),n(t instanceof DataView);const s=e.byteLength;let i=0,a=-1;for(;++a<s;)i|=e.getUint8(a)^t.getUint8(a);return i===0}return Zt}var Vs;function Eu(){if(Vs)return Te;Vs=1,Object.defineProperty(Te,"__esModule",{value:!0}),Te.Webhook=Te.WebhookVerificationError=void 0;const n=Su(),r=Ru(),e=Au(),t=300;class s extends Error{constructor(u){super(u),Object.setPrototypeOf(this,s.prototype),this.name="ExtendableError",this.stack=new Error(u).stack}}class i extends s{constructor(u){super(u),Object.setPrototypeOf(this,i.prototype),this.name="WebhookVerificationError"}}Te.WebhookVerificationError=i;class a{constructor(u,l){if(l?.format==="raw")u instanceof Uint8Array?this.key=u:this.key=Uint8Array.from(u,p=>p.charCodeAt(0));else{if(typeof u!="string")throw new Error("Expected secret to be of type string");u.startsWith(a.prefix)&&(u=u.substring(a.prefix.length)),this.key=n.decode(u)}if(this.key.length===0)throw new Error("Secret can't be empty.")}verify(u,l,p){var d;const g=(d=p?.jsonParse)!==null&&d!==void 0?d:!0,_={};for(const $ of Object.keys(l))_[$.toLowerCase()]=l[$];const m=_["webhook-id"],y=_["webhook-signature"],x=_["webhook-timestamp"];if(!y||!m||!x)throw new i("Missing required headers");const E=this.verifyTimestamp(x),k=this.sign(m,E,u).split(",")[1],R=y.split(" "),T=new globalThis.TextEncoder;for(const $ of R){const[C,M]=$.split(",");if(C==="v1"&&(0,e.timingSafeEqual)(T.encode(M),T.encode(k))){const L=u.toString();return L===""?void 0:g?JSON.parse(L):void 0}}throw new i("No matching signature found")}sign(u,l,p){if(typeof p!="string")if(p.constructor.name==="Buffer")p=p.toString();else throw new Error("Expected payload to be of type string or Buffer.");const d=new TextEncoder,g=Math.floor(l.getTime()/1e3),_=d.encode(`${u}.${g}.${p}`);return`v1,${n.encode(r.hmac(this.key,_))}`}verifyTimestamp(u){const l=Math.floor(Date.now()/1e3),p=parseInt(u,10);if(Number.isNaN(p))throw new i("Invalid Signature Headers");if(l-p>t)throw new i("Message timestamp too old");if(p>l+t)throw new i("Message timestamp too new");return new Date(p*1e3)}}return Te.Webhook=a,a.prefix="whsec_",Te}var Tu=Eu();class Js extends v{parseUnverified(r){return JSON.parse(r)}unwrap(r,e){const t=e?.headers;if(t==null)throw new Error("Webhook headers are required in order to verify the signature");const s=e.key===void 0?this._client.webhookKey:e.key;if(!s)throw new Error("Webhook key must not be null or empty in order to unwrap");return new Tu.Webhook(s).verify(r,t),JSON.parse(r)}}let Xs=class extends v{list(r,e={},t){const{betas:s,workspace_id:i,...a}=e??{};return this._client.getAPIList(h`/v1/agents/${r}/versions?beta=true`,A,{query:a,...t,headers:f([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}};var Gs=(()=>{class n extends v{constructor(){super(...arguments),this.versions=new Xs(this._client)}create(e,t){const{betas:s,workspace_id:i,...a}=e;return this._client.post("/v1/agents?beta=true",{body:a,...t,headers:f([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:i,workspace_id:a,...c}=t??{};return this._client.get(h`/v1/agents/${e}?beta=true`,{query:c,...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}update(e,t,s){const{betas:i,workspace_id:a,...c}=t;return this._client.post(h`/v1/agents/${e}?beta=true`,{body:c,...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:i,...a}=e??{};return this._client.getAPIList("/v1/agents?beta=true",A,{query:a,...t,headers:f([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}archive(e,t={},s){const{betas:i,workspace_id:a}=t??{};return this._client.post(h`/v1/agents/${e}/archive?beta=true`,{...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}}return n.Versions=Xs,n})();function Vt(n,r){if(!n)return()=>{};if(n.aborted)return r.abort(),()=>{};const e=()=>r.abort();return n.addEventListener("abort",e),()=>n.removeEventListener("abort",e)}function ot(n,r){return n instanceof z&&n.status===r}function $u(n){return n instanceof z&&typeof n.status=="number"&&n.status>=400&&n.status<500}function Xn(n){return $u(n)&&!ot(n,408)&&!ot(n,409)&&!ot(n,429)}function Oc(n,r,e){return Math.min(r*2**n,e)}function Iu(n,r){return n+Math.random()*(r-n)}function Cc(n){return n*(1-Math.random()*.25)}function Lc(n,{authToken:r,helper:e}){if(!r)throw new S(`copyClientForHelper: expected a non-empty authToken but received ${JSON.stringify(r)}`);const t=n,s=t._options.defaultHeaders,i=t._authState?.extraHeaders,a=i?Object.fromEntries(Object.entries(i).filter(([u])=>{const l=u.toLowerCase();return l!=="authorization"&&l!=="x-api-key"})):void 0,c=f([a,s,{[Xt]:e}]);return n.withOptions({apiKey:null,authToken:r,baseURL:n.baseURL,credentials:void 0,defaultHeaders:c})}var He,en,re,tn,nn,rn,pt,_t,We,ze,sn,je,gt;const Pu=999,Mu=1e3,Ou=6e4,Cu=3e5;var Wr=(()=>{class n{constructor(e){He.set(this,void 0),en.set(this,!1),re.set(this,void 0),tn.set(this,void 0),nn.set(this,void 0),rn.set(this,void 0),pt.set(this,void 0),_t.set(this,void 0),We.set(this,void 0),this.client=e.client,this.environmentId=e.environmentId,this.environmentKey=e.environmentKey,this.workerId=e.workerId??Bu(),w(this,He,Lc(e.client,{authToken:e.environmentKey,helper:"environments-work-poller"})),w(this,nn,e.autoStop??!0),w(this,rn,e.drain??!1),w(this,pt,e.blockMs===void 0?Pu:e.blockMs),w(this,_t,e.reclaimOlderThanMs??null),w(this,We,e.requestOptions),w(this,re,new AbortController),w(this,tn,Vt(e.signal,o(this,re,"f")))}get signal(){return o(this,re,"f").signal}abort(){o(this,re,"f").abort()}async*[(He=new WeakMap,en=new WeakMap,re=new WeakMap,tn=new WeakMap,nn=new WeakMap,rn=new WeakMap,pt=new WeakMap,_t=new WeakMap,We=new WeakMap,Symbol.asyncIterator)](){if(o(this,en,"f"))throw new S("Cannot iterate over a consumed WorkPoller");w(this,en,!0);const e=O(this.client);e.info("poller starting",{component:"work-poller",environment_id:this.environmentId});const t=new Nu(e,this.environmentId);try{let s=0;for(;!o(this,re,"f").signal.aborted;){let i;try{i=await o(this,He,"f").beta.environments.work.poll(this.environmentId,{"Anthropic-Worker-ID":this.workerId,...o(this,pt,"f")!==null?{block_ms:o(this,pt,"f")}:{},...o(this,_t,"f")!==null?{reclaim_older_than_ms:o(this,_t,"f")}:{}},{headers:f([o(this,We,"f")?.headers]),signal:o(this,re,"f").signal})}catch(a){if(o(this,re,"f").signal.aborted)return;if(Xn(a))throw e.error("poll failed permanently, stopping poller",{error:String(a)}),a;const c=Cc(Lu(s));e.warn("poll failed, backing off",{error:String(a),backoff_ms:c}),s++,await Be(c,o(this,re,"f").signal);continue}if(s=0,i==null){if(o(this,rn,"f"))return;t.onEmptyPoll(),await Be(Iu(1e3,3e3),o(this,re,"f").signal);continue}t.onClaim(),e.info("claimed work",{component:"work-poller",environment_id:this.environmentId,work_id:i.id,work_type:i.data.type});try{await o(this,He,"f").beta.environments.work.ack(i.id,{environment_id:i.environment_id},{headers:f([o(this,We,"f")?.headers]),signal:o(this,re,"f").signal})}catch(a){e.error("ack failed",{work_id:i.id,error:String(a)});continue}try{yield i}finally{if(o(this,nn,"f"))try{await o(this,He,"f").beta.environments.work.stop(i.id,{environment_id:i.environment_id},{headers:f([o(this,We,"f")?.headers])})}catch(a){ot(a,409)||e.warn("stop failed",{work_id:i.id,error:String(a)})}}}}finally{o(this,tn,"f").call(this)}}}return n})();function Lu(n){return Oc(n,Mu,Ou)}var Nu=(()=>{class n{constructor(e,t){ze.set(this,void 0),sn.set(this,void 0),je.set(this,void 0),gt.set(this,0),w(this,ze,e),w(this,sn,t)}onEmptyPoll(){const e=Date.now(),t={component:"work-poller",environment_id:o(this,sn,"f")};o(this,je,"f")===void 0?(w(this,je,w(this,gt,e,"f")),o(this,ze,"f").info("idle; polling for work",t)):e-o(this,gt,"f")>=Cu?(w(this,gt,e),o(this,ze,"f").info(`still polling; idle for ${Math.round((e-o(this,je,"f"))/1e3)}s`,t)):o(this,ze,"f").debug("poll returned no work",t)}onClaim(){w(this,je,void 0)}}return ze=new WeakMap,sn=new WeakMap,je=new WeakMap,gt=new WeakMap,n})();function Bu(){const r=globalThis.process?.env?.HOSTNAME;return r?`${r}-${Dr()}`:Dr()}var Fe,be,qe,Du=(()=>{class n{constructor(){Fe.set(this,[]),be.set(this,[]),qe.set(this,!1)}push(e){if(o(this,qe,"f"))return!1;const t=o(this,be,"f").shift();return t?t({done:!1,value:e}):o(this,Fe,"f").push(e),!0}close(){if(!o(this,qe,"f"))for(w(this,qe,!0);o(this,be,"f").length>0;)o(this,be,"f").shift()({done:!0,value:void 0})}next(e){return o(this,Fe,"f").length>0?Promise.resolve({done:!1,value:o(this,Fe,"f").shift()}):o(this,qe,"f")||e?.aborted?Promise.resolve({done:!0,value:void 0}):new Promise(t=>{const s=a=>{e?.removeEventListener("abort",i),t(a)},i=()=>{const a=o(this,be,"f").indexOf(s);a>=0&&o(this,be,"f").splice(a,1),t({done:!0,value:void 0})};o(this,be,"f").push(s),e?.addEventListener("abort",i,{once:!0})})}tryShift(){return o(this,Fe,"f").shift()}}return Fe=new WeakMap,be=new WeakMap,qe=new WeakMap,n})(),cs=(()=>{class n extends Error{constructor(e){const t=typeof e=="string"?e:e.map(s=>s.type==="text"?s.text:`[${s.type}]`).join(" ");super(t),this.name="ToolError",this.content=e}}return n})();function Qs(n){return"name"in n?n.name:"mcp_server_name"in n?n.mcp_server_name:n.type}function Uu(n){return n instanceof cs?n.content:`Error: ${n instanceof Error?n.message:String(n)}`}async function Hu(n,r,e){try{const t=n.parse?n.parse(r):r;return{content:await n.run(t,e),isError:!1}}catch(t){return{content:Uu(t),isError:!0}}}var mt,an,Ke,$e,ae,U,on,j,cn,wt,ln,H,Ve,Y,Je,ve,Xe,pe,un,yt,Z,dn,Ys,Zs,ei,ti,tr,ni,hn,fn,nr,ri,si;const ii=500,Wu=1e4,zu=12e4,ju=3e4,Fu=1e3,qu=3e4,Ku=5*6e4,Vu=6e4;function Nc(n){return n.type!=="session.status_idle"?!1:n.stop_reason?.type!=="requires_action"}var Ju=(()=>{class n{constructor(e,t){mt.set(this,void 0),an.set(this,void 0),Ke.set(this,new Set),$e.set(this,!1),ae.set(this,void 0),w(this,mt,e),w(this,an,t)}noteEvent(e){e.type!=="user.tool_confirmation"&&(Nc(e)?this.arm():this.disarm())}block(e){o(this,Ke,"f").add(e),o(this,ae,"f")!==void 0&&(w(this,$e,!0),clearTimeout(o(this,ae,"f")),w(this,ae,void 0))}unblock(e){o(this,Ke,"f").delete(e),o(this,Ke,"f").size===0&&o(this,$e,"f")&&this.arm()}arm(){if(!(o(this,mt,"f")<=0)){if(o(this,Ke,"f").size>0){w(this,$e,!0);return}w(this,$e,!1),o(this,ae,"f")!==void 0&&clearTimeout(o(this,ae,"f")),w(this,ae,setTimeout(o(this,an,"f"),o(this,mt,"f")))}}disarm(){w(this,$e,!1),o(this,ae,"f")!==void 0&&(clearTimeout(o(this,ae,"f")),w(this,ae,void 0))}}return mt=new WeakMap,an=new WeakMap,Ke=new WeakMap,$e=new WeakMap,ae=new WeakMap,n})(),zr=(()=>{class n{constructor(e,t){U.add(this),on.set(this,!1),j.set(this,void 0),cn.set(this,void 0),wt.set(this,void 0),ln.set(this,void 0),H.set(this,void 0),Ve.set(this,new Set),Y.set(this,new Set),Je.set(this,new Map),ve.set(this,new Map),Xe.set(this,new Du),pe.set(this,0),un.set(this,Ku),yt.set(this,null),Z.set(this,void 0),this.client=t.client,this.sessionId=e,this.tools=t.tools,this.maxIdleMs=t.maxIdleMs??Vu,w(this,H,O(t.client)),w(this,ln,new Map(t.tools.map(s=>[Qs(s),s]))),w(this,j,new AbortController),w(this,cn,Vt(t.signal,o(this,j,"f"))),w(this,wt,t.requestOptions),w(this,Z,new Ju(this.maxIdleMs,()=>{o(this,H,"f").info("session idle after its turn ended; stopping",{component:"session-tool-runner",session_id:this.sessionId,max_idle_ms:this.maxIdleMs}),o(this,j,"f").abort()}))}get signal(){return o(this,j,"f").signal}abort(){o(this,j,"f").abort()}_setSendRetryWindow(e){w(this,un,e)}async*[(on=new WeakMap,j=new WeakMap,cn=new WeakMap,wt=new WeakMap,ln=new WeakMap,H=new WeakMap,Ve=new WeakMap,Y=new WeakMap,Je=new WeakMap,ve=new WeakMap,Xe=new WeakMap,pe=new WeakMap,un=new WeakMap,yt=new WeakMap,Z=new WeakMap,U=new WeakSet,Symbol.asyncIterator)](){if(o(this,on,"f"))throw new S("Cannot iterate over a consumed SessionToolRunner");w(this,on,!0),o(this,H,"f").info("session tool runner starting",{component:"session-tool-runner",session_id:this.sessionId});const e=o(this,U,"m",Ys).call(this).catch(t=>{o(this,j,"f").signal.aborted||o(this,H,"f").error("stream loop failed",{error:String(t)}),o(this,j,"f").abort()});try{for(;;){const s=await o(this,Xe,"f").next(o(this,j,"f").signal);if(s.done)break;yield s.value}await e;let t;for(;(t=o(this,Xe,"f").tryShift())!==void 0;)yield t}finally{o(this,j,"f").abort(),o(this,Z,"f").disarm(),await e;try{await o(this,U,"m",si).call(this)}catch(t){o(this,H,"f").warn("drain failed",{error:String(t)})}o(this,Xe,"f").close();for(const t of this.tools)try{await t.close?.()}catch(s){o(this,H,"f").warn("tool.close failed",{tool:Qs(t),error:String(s)})}o(this,cn,"f").call(this)}}}return dn=function(){return{...o(this,wt,"f"),headers:f([$c("session-tool-runner"),o(this,wt,"f")?.headers]),signal:o(this,j,"f").signal}},Ys=async function(){const e=o(this,j,"f");let t=ii;for(;!e.signal.aborted;){try{const s=await this.client.beta.sessions.events.stream(this.sessionId,{},o(this,U,"m",dn).call(this));await o(this,U,"m",Zs).call(this);for await(const i of s)if(t=ii,await o(this,U,"m",ti).call(this,i))return}catch(s){if(e.signal.throwIfAborted(),Xn(s))throw o(this,H,"f").error("permanent stream failure, shutting down",{error:String(s)}),e.abort(),s;o(this,H,"f").warn("stream disconnected, reconnecting",{error:String(s),backoff_ms:t})}e.signal.throwIfAborted(),await Be(t,e.signal),t=Math.min(t*2,Wu)}},Zs=async function(){const e=o(this,j,"f"),t=[];let s=!1;try{for await(const c of this.client.beta.sessions.events.list(this.sessionId,{limit:1e3},o(this,U,"m",dn).call(this)))o(this,U,"m",ei).call(this,c,t),c.type!=="user.tool_confirmation"&&(s=Nc(c))}catch(c){e.signal.throwIfAborted(),o(this,H,"f").warn("reconcile list failed",{error:String(c)});for(const u of t)o(this,Ve,"f").delete(u.id);return}const i=t.filter(c=>!o(this,Y,"f").has(c.id));o(this,Z,"f").disarm();for(const c of i)await o(this,U,"m",tr).call(this,c);for(const c of[...o(this,ve,"f").values()]){const u=o(this,Je,"f").get(c.id);u!==void 0&&await o(this,U,"m",hn).call(this,c,u)}const a=i.filter(c=>!o(this,Y,"f").has(c.id)&&!o(this,ve,"f").has(c.id));s&&a.length===0?o(this,Z,"f").arm():o(this,Z,"f").disarm()},ei=function(e,t){e.type==="agent.tool_use"||e.type==="agent.custom_tool_use"?(o(this,Ve,"f").add(e.id),o(this,Y,"f").has(e.id)||t.push(e)):e.type==="user.tool_result"?o(this,Y,"f").add(e.tool_use_id):e.type==="user.custom_tool_result"?o(this,Y,"f").add(e.custom_tool_use_id):e.type==="user.tool_confirmation"&&(o(this,Y,"f").has(e.tool_use_id)||o(this,Je,"f").set(e.tool_use_id,e.result))},ti=async function(e){switch(o(this,Z,"f").noteEvent(e),e.type){case"agent.tool_use":case"agent.custom_tool_use":return o(this,Ve,"f").has(e.id)||(o(this,Ve,"f").add(e.id),await o(this,U,"m",tr).call(this,e)),!1;case"user.tool_confirmation":return await o(this,U,"m",ni).call(this,e),!1;case"user.tool_result":return o(this,Y,"f").add(e.tool_use_id),!1;case"user.custom_tool_result":return o(this,Y,"f").add(e.custom_tool_use_id),!1;case"session.status_terminated":case"session.deleted":return o(this,H,"f").info("session terminated",{component:"session-tool-runner",session_id:this.sessionId}),o(this,j,"f").abort(),!0;default:return!1}},tr=async function(e){const t=e.evaluated_permission,s=t==="deny"?"deny":o(this,Je,"f").get(e.id);if(s===void 0){t===void 0||t==="allow"?await o(this,U,"m",nr).call(this,e,void 0):o(this,ve,"f").has(e.id)||(o(this,H,"f").info("tool call awaiting confirmation; holding",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),o(this,ve,"f").set(e.id,e),o(this,Z,"f").block(e.id));return}await o(this,U,"m",hn).call(this,e,s)},ni=async function(e){o(this,Je,"f").set(e.tool_use_id,e.result);const t=o(this,ve,"f").get(e.tool_use_id);t!==void 0&&await o(this,U,"m",hn).call(this,t,e.result)},hn=async function(e,t){const s=o(this,ve,"f").delete(e.id);if(t==="allow"){o(this,H,"f").info("tool call confirmed",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),s||o(this,Z,"f").block(e.id);try{await o(this,U,"m",nr).call(this,e,"allow")}finally{o(this,Z,"f").unblock(e.id)}return}s&&o(this,Z,"f").unblock(e.id),o(this,Y,"f").add(e.id),o(this,H,"f").info("tool call denied; not executing",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),o(this,U,"m",fn).call(this,{event:e,toolUseId:e.id,name:e.name,isError:!1,posted:!1,confirmation:"deny"})},fn=function(e){o(this,Xe,"f").push(e)},nr=async function(e,t){var s,i;if(!o(this,Y,"f").has(e.id)){o(this,H,"f").info("executing tool",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),w(this,pe,(s=o(this,pe,"f"),s++,s));try{const a=o(this,ln,"f").get(e.name);if(!a){o(this,H,"f").info("tool not owned by this runner; leaving the tool_use_id pending for its owner",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),t==="allow"&&o(this,Z,"f").disarm(),o(this,U,"m",fn).call(this,{event:e,toolUseId:e.id,name:e.name,isError:!1,posted:!1,confirmation:t});return}let c,u;const l=new AbortController,p=Vt(o(this,j,"f").signal,l),d=setTimeout(()=>l.abort(),zu);try{const m=await Hu(a,e.input,{toolUse:e,toolUseBlock:e,signal:l.signal});c=m.content,u=m.isError}finally{clearTimeout(d),p()}const g=Xu(e,u,Gu(c)),_=await o(this,U,"m",ri).call(this,g,e.id);o(this,U,"m",fn).call(this,{event:e,result:g,toolUseId:e.id,name:e.name,isError:u,posted:_,confirmation:t})}finally{w(this,pe,(i=o(this,pe,"f"),i--,i)),o(this,pe,"f")===0&&o(this,yt,"f")?.call(this)}}},ri=async function(e,t){const s=o(this,j,"f"),i=Date.now();let a,c=0;for(;;){c++,s.signal.throwIfAborted();try{return await this.client.beta.sessions.events.send(this.sessionId,{events:[e]},o(this,U,"m",dn).call(this)),o(this,Y,"f").add(t),!0}catch(u){if(a=u,Xn(u))break;const l=o(this,un,"f")-(Date.now()-i);if(l<=0)break;const p=Math.min(Cc(Oc(c-1,Fu,qu)),l);o(this,H,"f").warn("tool result send failed; retrying",{tool_use_id:t,attempt:c,backoff_ms:p,error:String(u)}),await Be(p,s.signal)}}return o(this,H,"f").error("failed to send tool result",{tool_use_id:t,attempts:c,error:String(a)}),!1},si=async function(){o(this,pe,"f")!==0&&(await Promise.race([new Promise(e=>w(this,yt,e)),Be(ju)]),w(this,yt,null),o(this,pe,"f")>0&&o(this,H,"f").warn("drain timeout exceeded"))},n})();function Xu(n,r,e){return n.type==="agent.custom_tool_use"?{type:"user.custom_tool_result",custom_tool_use_id:n.id,is_error:r,content:e}:{type:"user.tool_result",tool_use_id:n.id,is_error:r,content:e}}function Gu(n){if(typeof n=="string")return[{type:"text",text:n||"(no output)"}];const r=n.map(e=>e.type==="text"?{type:"text",text:e.text||"(no output)"}:e.type==="image"||e.type==="document"?e:e.type==="search_result"?{type:"search_result",source:e.source,title:e.title,content:e.content.map(t=>({type:"text",text:t.text})),citations:{enabled:e.citations?.enabled??!1}}:{type:"text",text:JSON.stringify(e)});return r.length>0?r:[{type:"text",text:"(no output)"}]}const af=15e3,ai=5e3;function Qu(n,r){if(!(n>=ai))throw new S(`${r} must be at least ${ai}ms (got ${n}); to run without memory sync, pass \`memorySyncIntervalMs: null\` to the worker instead`)}var pn,bt,rr,vt,Ge;const oi=3e4,Yu=9e4,Zu="NO_HEARTBEAT";function ed(n){return n.resources.some(r=>r.type==="memory_store")}function td(n){if(!n)return null;let r;try{const t=n.replace(/-/g,"+").replace(/_/g,"/"),s=t.padEnd(Math.ceil(t.length/4)*4,"=");r=JSON.parse(Lr(Fl(s)))}catch{return null}if(r===null||typeof r!="object"||Array.isArray(r))return null;const e=r.sessions_token;return typeof e=="string"&&e!==""?e:null}var ci=(()=>{class n{constructor(e){if(pn.add(this),bt.set(this,void 0),e.unrestrictedPaths!==void 0)throw new S("The `unrestrictedPaths` option you passed to EnvironmentWorker (or client.beta.environments.work.worker()) is no longer supported. The worker's file tools (read, write, edit, glob, grep) are now always confined to `workdir` plus the session's memory folders. Remove `unrestrictedPaths` from your options; to let the file tools reach any other directory, add it to `AgentToolContext.allowedRoots` from a `tools` factory.");this.client=e.client,this.environmentId=e.environmentId,this.environmentKey=e.environmentKey,this.tools=e.tools,this.workdir=e.workdir??process.cwd(),this.maxFileBytes=e.maxFileBytes,this.maxIdleMs=e.maxIdleMs,e.memorySyncIntervalMs!=null&&Qu(e.memorySyncIntervalMs,"memorySyncIntervalMs"),this.memorySyncIntervalMs=e.memorySyncIntervalMs,this.memorySyncDeletions=e.memorySyncDeletions??"enabled",this.workerId=e.workerId,this.requestOptions=e.requestOptions,w(this,bt,e.signal)}async run(e){const{environmentId:t,environmentKey:s}=this;if(t===void 0||s===void 0)throw new S("EnvironmentWorker.run: environmentId and environmentKey are required to poll for work");const i=e??o(this,bt,"f"),a=new Wr({client:this.client,environmentId:t,environmentKey:s,...this.workerId!==void 0?{workerId:this.workerId}:{},...i?{signal:i}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},autoStop:!1});for await(const c of a)try{await o(this,pn,"m",rr).call(this,c,s,a.signal)}catch(u){if(a.signal?.aborted)throw u;O(this.client).error("work item failed",{work_id:c.id,error:String(u)})}}async handleItem(e){const t=e?.workId??P("ANTHROPIC_WORK_ID"),s=e?.environmentId??P("ANTHROPIC_ENVIRONMENT_ID"),i=e?.sessionId??P("ANTHROPIC_SESSION_ID"),a=(e?.environmentKey??this.environmentKey??P("ANTHROPIC_ENVIRONMENT_KEY"))||void 0,c=e?.workSecret||P("ANTHROPIC_WORK_SECRET")||null;if(!t)throw new S("handleItem: workId is required — pass it or set ANTHROPIC_WORK_ID");if(!s)throw new S("handleItem: environmentId is required — pass it or set ANTHROPIC_ENVIRONMENT_ID");if(!i)throw new S("handleItem: sessionId is required — pass it or set ANTHROPIC_SESSION_ID");if(!a&&!c)throw new S("handleItem: environmentKey is required when there is no work secret — pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY");const u={id:t,environment_id:s,secret:c,data:{type:"session",id:i}};await o(this,pn,"m",rr).call(this,u,a,e?.signal??o(this,bt,"f"))}}return bt=new WeakMap,pn=new WeakSet,rr=async function(e,t,s){const i=O(this.client),a=td(e.secret),c=a??t;if(c===void 0)throw new S("handleItem: the work item carried a secret payload but no sessions token could be extracted, and there is no environment key to fall back to; the poller must issue a secret whose payload carries `sessions_token`, or provide the environment key (pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY)");e.secret&&a===null&&i.warn("work item carried a secret payload but no sessions token could be extracted; falling back to the environment key",{work_id:e.id});const u=Lc(this.client,{authToken:c,helper:"environments-worker"}),l=e.data.id,p=new AbortController,d=Vt(s,p),g=new rd(p),_=await ce(()=>import("./node.browser-DWucOsQl.js"),__vite__mapDeps([3,1,2]));let m,y;const x=id(u,e,g,i,this.requestOptions,R=>{m=R,y?._setSendRetryWindow(R)}).catch(R=>{p.signal.aborted||i.error("heartbeat loop failed",{work_id:e.id,error:String(R)}),p.abort()});let E=async()=>{},b,k=!1;try{if(e.data.type!=="session"){i.debug("skipping non-session work item",{work_id:e.id,type:e.data.type});return}const R=await u.beta.sessions.retrieve(l);if(a===null&&this.memorySyncIntervalMs!==null&&ed(R))throw new _.SessionMemoryError(`cannot mount the session's memories: the work item carried no sessions token (work_id=${e.id}, session_id=${l}); the memory endpoints reject the environment key, so the poller must issue a per-item \`secret\` carrying \`sessions_token\`, or set \`memorySyncIntervalMs: null\` to run without memory`);const T={workdir:this.workdir,client:u,session:R,...this.maxFileBytes!==void 0?{maxFileBytes:this.maxFileBytes}:{}};try{E=await _.setupSkills(T)}catch(C){i.warn("skill setup failed",{session_id:l,work_id:e.id,error:String(C)})}a!==null&&this.memorySyncIntervalMs!==null?(b=new _.SessionMemoryStores(u,{workdir:this.workdir,...this.memorySyncIntervalMs!==void 0?{syncIntervalMs:this.memorySyncIntervalMs}:{},syncDeletions:this.memorySyncDeletions}),await b.download(R),T.allowedRoots=b.roots,T.readOnlyRoots=b.readOnlyRoots):i.debug("memory stores disabled for this item",{work_id:e.id});const $=typeof this.tools=="function"?this.tools(T):this.tools??_.betaAgentToolset20260401(T);y=new zr(l,{client:u,tools:$,...this.maxIdleMs!==void 0?{maxIdleMs:this.maxIdleMs}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},signal:p.signal}),m!==void 0&&y._setSendRetryWindow(m);for await(const C of y)b&&await b.syncIfDue();k=!p.signal.aborted}finally{try{await E().catch(R=>{i.warn("skill cleanup failed",{session_id:l,work_id:e.id,error:String(R)})})}finally{if(b){const R=_.MEMORY_FLUSH_TIMEOUT_MS;k&&await li(b.finish(),R)&&i.warn(`final memory sync cut off after ${R}ms; the flush that follows still uploads changed files`,{session_id:l,work_id:e.id});const T=new AbortController;await li(b.flushWrites(T.signal),R)&&(T.abort(),i.warn(`memory flush cut off after ${R}ms; changed files it had not uploaded yet are not saved`,{session_id:l,work_id:e.id})),await b.dispose().catch(C=>{i.warn("memory store cleanup failed",{session_id:l,work_id:e.id,error:String(C)})})}}g.finish("runner_done"),d(),await x,g.lost?i.info("lease lost; released without stopping it",{session_id:l,work_id:e.id}):await nd(u,e,i,this.requestOptions)}},n})();async function li(n,r){let e;try{return await Promise.race([n.then(()=>!1,()=>!1),new Promise(t=>{e=setTimeout(()=>t(!0),r)})])}finally{e!==void 0&&clearTimeout(e)}}async function nd(n,r,e,t){try{await n.beta.environments.work.stop(r.id,{environment_id:r.environment_id,force:!0},{...t,headers:f([t?.headers])})}catch(s){ot(s,409)||e.error("force-stop on exit failed",{work_id:r.id,error:String(s)})}}var rd=(()=>{class n{constructor(e){vt.set(this,void 0),Ge.set(this,void 0),w(this,vt,e)}get signal(){return o(this,vt,"f").signal}finish(e){w(this,Ge,o(this,Ge,"f")??e),o(this,vt,"f").abort()}get lost(){return o(this,Ge,"f")==="lease_lost"||o(this,Ge,"f")==="assumed_lost"}}return vt=new WeakMap,Ge=new WeakMap,n})();function sd(n){let r=n instanceof z?n.error:void 0;for(const e of["error","details","current_state"]){if(!bs(r))return{};r=r[e]}return bs(r)?r:{}}async function id(n,r,e,t,s,i){let a=oi,c=Yu,u=Date.now(),l=Zu;const p=async()=>{const d=new AbortController,g=Vt(e.signal,d),_=setTimeout(()=>d.abort(),a);try{const m=await n.beta.environments.work.heartbeat(r.id,{environment_id:r.environment_id,expected_last_heartbeat:l},{...s,headers:f([s?.headers]),signal:d.signal});u=Date.now(),l=m.last_heartbeat,m.ttl_seconds>0&&(c=m.ttl_seconds*1e3,a=Math.max(1e3,Math.min(c/2,oi)),i?.(c)),(m.state==="stopping"||m.state==="stopped")&&(t.info("heartbeat signals shutdown",{work_id:r.id,state:m.state}),e.finish("control_plane_stop")),m.lease_extended||(t.warn("lease not extended, shutting down",{work_id:r.id}),e.finish("control_plane_stop"))}catch(m){if(e.signal.throwIfAborted(),ot(m,412)){const y=sd(m);t.error("lease lost: heartbeat precondition failed",{work_id:r.id,server_state:y.state,server_ttl_seconds:y.ttl_seconds,server_last_heartbeat:y.last_heartbeat}),e.finish("lease_lost");return}if(Xn(m))throw t.error("permanent heartbeat failure",{work_id:r.id,error:String(m)}),e.finish("heartbeat_rejected"),m;if(Date.now()-u>c){t.error("lease assumed lost: no successful heartbeat in ttl",{work_id:r.id,ttl_ms:c,error:String(m)}),e.finish("assumed_lost");return}t.warn("transient heartbeat failure",{work_id:r.id,error:String(m)})}finally{clearTimeout(_),g()}};for(await p();!e.signal.aborted;)await Be(a,e.signal),e.signal.throwIfAborted(),await p()}var ui=(()=>{class n extends v{retrieve(e,t,s){const{environment_id:i,betas:a,workspace_id:c}=t;return this._client.get(h`/v1/environments/${i}/work/${e}?beta=true`,{...s,headers:f([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers])})}update(e,t,s){const{environment_id:i,betas:a,workspace_id:c,...u}=t;return this._client.post(h`/v1/environments/${i}/work/${e}?beta=true`,{body:u,...s,headers:f([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers])})}list(e,t={},s){const{betas:i,...a}=t??{};return this._client.getAPIList(h`/v1/environments/${e}/work?beta=true`,A,{query:a,...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}ack(e,t,s){const{environment_id:i,betas:a}=t;return this._client.post(h`/v1/environments/${i}/work/${e}/ack?beta=true`,{...s,headers:f([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}heartbeat(e,t,s){const{environment_id:i,desired_ttl_seconds:a,expected_last_heartbeat:c,betas:u}=t;return this._client.post(h`/v1/environments/${i}/work/${e}/heartbeat?beta=true`,{query:{desired_ttl_seconds:a,expected_last_heartbeat:c},...s,headers:f([{"anthropic-beta":[...u??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}poll(e,t={},s){const{betas:i,"Anthropic-Worker-ID":a,...c}=t??{};return this._client.get(h`/v1/environments/${e}/work/poll?beta=true`,{query:c,...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"Anthropic-Worker-ID":a}:void 0},s?.headers])})}stats(e,t={},s){const{betas:i,workspace_id:a}=t??{};return this._client.get(h`/v1/environments/${e}/work/stats?beta=true`,{...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}stop(e,t,s){const{environment_id:i,betas:a,workspace_id:c,...u}=t;return this._client.post(h`/v1/environments/${i}/work/${e}/stop?beta=true`,{body:u,...s,headers:f([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers])})}poller(e){return new Wr({...e,client:this._client})}worker(e){return new ci({...e,client:this._client})}}return n.WorkPoller=Wr,n.EnvironmentWorker=ci,n})(),di=(()=>{class n extends v{constructor(){super(...arguments),this.work=new ui(this._client)}create(e,t){const{betas:s,workspace_id:i,...a}=e;return this._client.post("/v1/environments?beta=true",{body:a,...t,headers:f([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:i,workspace_id:a}=t??{};return this._client.get(h`/v1/environments/${e}?beta=true`,{...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}update(e,t,s){const{betas:i,workspace_id:a,...c}=t;return this._client.post(h`/v1/environments/${e}?beta=true`,{body:c,...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:i,...a}=e??{};return this._client.getAPIList("/v1/environments?beta=true",A,{query:a,...t,headers:f([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}delete(e,t={},s){const{betas:i,workspace_id:a}=t??{};return this._client.delete(h`/v1/environments/${e}?beta=true`,{...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}archive(e,t={},s){const{betas:i,workspace_id:a}=t??{};return this._client.post(h`/v1/environments/${e}/archive?beta=true`,{...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}}return n.Work=ui,n})();class hi extends v{create(r,e,t){const{view:s,betas:i,workspace_id:a,...c}=e;return this._client.post(h`/v1/memory_stores/${r}/memories?beta=true`,{query:{view:s},body:c,...t,headers:f([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}retrieve(r,e,t){const{memory_store_id:s,betas:i,workspace_id:a,...c}=e;return this._client.get(h`/v1/memory_stores/${s}/memories/${r}?beta=true`,{query:c,...t,headers:f([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}update(r,e,t){const{memory_store_id:s,view:i,betas:a,workspace_id:c,...u}=e;return this._client.post(h`/v1/memory_stores/${s}/memories/${r}?beta=true`,{query:{view:i},body:u,...t,headers:f([{"anthropic-beta":[...a??[],"agent-memory-2026-07-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}list(r,e={},t){const{betas:s,workspace_id:i,...a}=e??{};return this._client.getAPIList(h`/v1/memory_stores/${r}/memories?beta=true`,A,{query:a,...t,headers:f([{"anthropic-beta":[...s??[],"agent-memory-2026-07-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}delete(r,e,t){const{memory_store_id:s,expected_content_sha256:i,betas:a,workspace_id:c}=e;return this._client.delete(h`/v1/memory_stores/${s}/memories/${r}?beta=true`,{query:{expected_content_sha256:i},...t,headers:f([{"anthropic-beta":[...a??[],"agent-memory-2026-07-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}}class fi extends v{retrieve(r,e,t){const{memory_store_id:s,betas:i,workspace_id:a,...c}=e;return this._client.get(h`/v1/memory_stores/${s}/memory_versions/${r}?beta=true`,{query:c,...t,headers:f([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}list(r,e={},t){const{betas:s,workspace_id:i,...a}=e??{};return this._client.getAPIList(h`/v1/memory_stores/${r}/memory_versions?beta=true`,A,{query:a,...t,headers:f([{"anthropic-beta":[...s??[],"agent-memory-2026-07-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}redact(r,e,t){const{memory_store_id:s,betas:i,workspace_id:a}=e;return this._client.post(h`/v1/memory_stores/${s}/memory_versions/${r}/redact?beta=true`,{...t,headers:f([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}}var pi=(()=>{class n extends v{constructor(){super(...arguments),this.memories=new hi(this._client),this.memoryVersions=new fi(this._client)}create(e,t){const{betas:s,workspace_id:i,...a}=e;return this._client.post("/v1/memory_stores?beta=true",{body:a,...t,headers:f([{"anthropic-beta":[...s??[],"agent-memory-2026-07-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:i,workspace_id:a}=t??{};return this._client.get(h`/v1/memory_stores/${e}?beta=true`,{...s,headers:f([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}update(e,t,s){const{betas:i,workspace_id:a,...c}=t;return this._client.post(h`/v1/memory_stores/${e}?beta=true`,{body:c,...s,headers:f([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:i,...a}=e??{};return this._client.getAPIList("/v1/memory_stores?beta=true",A,{query:a,...t,headers:f([{"anthropic-beta":[...s??[],"agent-memory-2026-07-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}delete(e,t={},s){const{betas:i,workspace_id:a}=t??{};return this._client.delete(h`/v1/memory_stores/${e}?beta=true`,{...s,headers:f([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}archive(e,t={},s){const{betas:i,workspace_id:a}=t??{};return this._client.post(h`/v1/memory_stores/${e}/archive?beta=true`,{...s,headers:f([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}}return n.Memories=hi,n.MemoryVersions=fi,n})(),Bc=(()=>{class n{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new ss;for await(const t of this.iterator)for(const s of e.decode(t))yield JSON.parse(s);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(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new S("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new S("Attempted to iterate over a response with no body");return new n(ts(e.body),t)}}return n})();let _i=class extends v{create(r,e){const{betas:t,user_profile_id:s,workspace_id:i,...a}=r;return this._client.post("/v1/messages/batches?beta=true",{body:a,...e,headers:f([{"anthropic-beta":[...t??[],"message-batches-2024-09-24"].toString(),...s!=null?{"anthropic-user-profile-id":s}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},e?.headers])})}retrieve(r,e={},t){const{betas:s,workspace_id:i}=e??{};return this._client.get(h`/v1/messages/batches/${r}?beta=true`,{...t,headers:f([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}list(r={},e){const{betas:t,workspace_id:s,...i}=r??{};return this._client.getAPIList("/v1/messages/batches?beta=true",X,{query:i,...e,headers:f([{"anthropic-beta":[...t??[],"message-batches-2024-09-24"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},e?.headers])})}delete(r,e={},t){const{betas:s,workspace_id:i}=e??{};return this._client.delete(h`/v1/messages/batches/${r}?beta=true`,{...t,headers:f([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}cancel(r,e={},t){const{betas:s,workspace_id:i}=e??{};return this._client.post(h`/v1/messages/batches/${r}/cancel?beta=true`,{...t,headers:f([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}async results(r,e={},t){const s=await this.retrieve(r,e,t);if(!s.results_url)throw new S(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);const{betas:i,workspace_id:a}=e??{};return this._client.get(s.results_url,{...t,headers:f([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((c,u)=>Bc.fromResponse(u.response,u.controller))}};const Dc={"claude-opus-4@20250514":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function Uc(n){return n?.output_format??n?.output_config?.format}function gi(n,r,e){const t=Uc(r);return!r||!("parse"in(t??{}))?{...n,content:n.content.map(s=>{if(s.type==="text"){const i=Object.defineProperty({...s},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(i,"parsed",{get(){return e.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return s}),parsed_output:null}:Hc(n,r,e)}function Hc(n,r,e){let t=null;const s=n.content.map(i=>{if(i.type==="text"){const a=ad(r,i.text);t===null&&(t=a);const c=Object.defineProperty({...i},"parsed_output",{value:a,enumerable:!1});return Object.defineProperty(c,"parsed",{get(){return e.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),a},enumerable:!1})}return i});return{...n,content:s,parsed_output:t}}function ad(n,r){const e=Uc(n);if(e?.type!=="json_schema")return null;try{return"parse"in e?e.parse(r):JSON.parse(r)}catch(t){throw new S(`Failed to parse structured output: ${t}`)}}const od=n=>{let r=0,e=[];for(;r<n.length;){let t=n[r];if(t==="\\"){r++;continue}if(t==="{"){e.push({type:"brace",value:"{"}),r++;continue}if(t==="}"){e.push({type:"brace",value:"}"}),r++;continue}if(t==="["){e.push({type:"paren",value:"["}),r++;continue}if(t==="]"){e.push({type:"paren",value:"]"}),r++;continue}if(t===":"){e.push({type:"separator",value:":"}),r++;continue}if(t===","){e.push({type:"delimiter",value:","}),r++;continue}if(t==='"'){const c=r+1;let u=c,l=!1;for(;;){if(u=n.indexOf('"',u),u===-1){l=!0;break}let p=0,d=u-1;for(;d>=c&&n[d]==="\\";)p++,d--;if(p%2===0)break;u++}l?r=n.length:(e.push({type:"string",value:n.slice(c,u)}),r=u+1);continue}if(t&&/\s/.test(t)){r++;continue}let i=/[0-9]/;if(t&&i.test(t)||t==="-"||t==="."){let c="";for(t==="-"&&(c+=t,t=n[++r]);t&&(i.test(t)||t==="."||t==="e"||t==="E"||(t==="-"||t==="+")&&(c[c.length-1]==="e"||c[c.length-1]==="E"));)c+=t,t=n[++r];e.push({type:"number",value:c,unterminated:r===n.length});continue}let a=/[a-z]/i;if(t&&a.test(t)){let c="";for(;t&&a.test(t)&&r!==n.length;)c+=t,t=n[++r];if(c=="true"||c=="false"||c==="null")e.push({type:"name",value:c});else{r++;continue}continue}r++}return e},cd=n=>{let r=[];for(const i of n)(i.type==="brace"||i.type==="paren")&&(i.value==="{"||i.value==="["?r.push(i.value):r.pop());let e=r[r.length-1],t=n.length,s=/^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?$/;for(;t>0;){let i=n[t-1];switch(i.type){case"separator":t--;continue;case"number":if(i.unterminated||!s.test(i.value)){t--;continue}break;case"string":let a=n[t-2];if(e==="{"&&(a?.type==="delimiter"||a?.type==="brace"&&a.value==="{")){t--;continue}break;case"delimiter":t--;break}break}return n.slice(0,t)},ld=n=>{let r=[];return n.map(e=>{e.type==="brace"&&(e.value==="{"?r.push("}"):r.splice(r.lastIndexOf("}"),1)),e.type==="paren"&&(e.value==="["?r.push("]"):r.splice(r.lastIndexOf("]"),1))}),r.length>0&&r.reverse().map(e=>{e==="}"?n.push({type:"brace",value:"}"}):e==="]"&&n.push({type:"paren",value:"]"})}),n},ud=n=>{let r="";return n.map(e=>{e.type==="string"?r+='"'+e.value+'"':r+=e.value}),r},dd=n=>JSON.parse(ud(ld(cd(od(n))))),ct="__json_buf";function Wc(n,r){const e={};for(const i of Object.keys(n))i!=="input"&&(e[i]=n[i]);Object.defineProperty(e,ct,{value:r,enumerable:!1,writable:!0});let t,s=!1;return Object.defineProperty(e,"input",{enumerable:!0,configurable:!0,get(){return s||(t=r?dd(r):{},s=!0),t}}),e}var q,ke,Qe,kt,_n,St,xt,gn,Rt,ue,At,mn,wn,Ie,yn,bn,vn,Et,sr,mi,Tt,ir,ar,or,wi,cr;function lr(n){return n.type==="tool_use"||n.type==="server_tool_use"||n.type==="mcp_tool_use"}var zc=(()=>{class n{constructor(e,t){q.add(this),this.messages=[],this.receivedMessages=[],ke.set(this,void 0),Qe.set(this,null),this.controller=new AbortController,kt.set(this,void 0),_n.set(this,()=>{}),St.set(this,()=>{}),xt.set(this,void 0),gn.set(this,()=>{}),Rt.set(this,()=>{}),ue.set(this,{}),At.set(this,!1),mn.set(this,!1),wn.set(this,!1),Ie.set(this,!1),yn.set(this,void 0),bn.set(this,void 0),vn.set(this,void 0),Et.set(this,void 0),Tt.set(this,s=>{if(w(this,mn,!0),lt(s)&&(s=new oe),s instanceof oe)return w(this,wn,!0),this._emit("abort",s);if(s instanceof S)return this._emit("error",s);if(s instanceof Error){const i=new S(s.message);return i.cause=s,this._emit("error",i)}return this._emit("error",new S(String(s)))}),w(this,kt,new Promise((s,i)=>{w(this,_n,s,"f"),w(this,St,i,"f")})),w(this,xt,new Promise((s,i)=>{w(this,gn,s,"f"),w(this,Rt,i,"f")})),o(this,kt,"f").catch(()=>{}),o(this,xt,"f").catch(()=>{}),w(this,Qe,e),w(this,Et,t?.logger??console)}get response(){return o(this,yn,"f")}get request_id(){return o(this,bn,"f")}get workspace_id(){return o(this,vn,"f")}async withResponse(){w(this,Ie,!0);const e=await o(this,kt,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id"),workspace_id:e.headers.get("anthropic-workspace-id")}}static fromReadableStream(e){const t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,s,{logger:i}={}){const a=new n(t,{logger:i});for(const c of t.messages)a._addMessageParam(c);return w(a,Qe,{...t,stream:!0}),a._run(()=>a._createMessage(e,{...t,stream:!0},{...s,headers:{...s?.headers,[os]:"stream"}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},o(this,Tt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,s){const i=s?.signal;let a;i&&(i.aborted&&this.controller.abort(),a=this.controller.abort.bind(this.controller),i.addEventListener("abort",a));try{o(this,q,"m",ir).call(this);const{response:c,data:u}=await e.create({...t,stream:!0},{...s,signal:this.controller.signal}).withResponse();this._connected(c);for await(const l of u)o(this,q,"m",ar).call(this,l);if(u.controller.signal?.aborted)throw new oe;o(this,q,"m",or).call(this)}finally{i&&a&&i.removeEventListener("abort",a)}}_connected(e){this.ended||(w(this,yn,e),w(this,bn,e?.headers.get("request-id")),w(this,vn,e?.headers.get("anthropic-workspace-id")),o(this,_n,"f").call(this,e),this._emit("connect"))}get ended(){return o(this,At,"f")}get errored(){return o(this,mn,"f")}get aborted(){return o(this,wn,"f")}abort(){this.controller.abort()}on(e,t){return(o(this,ue,"f")[e]||(o(this,ue,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=o(this,ue,"f")[e];if(!s)return this;const i=s.findIndex(a=>a.listener===t);return i>=0&&s.splice(i,1),this}once(e,t){return(o(this,ue,"f")[e]||(o(this,ue,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{w(this,Ie,!0),e!=="error"&&this.once("error",s),this.once(e,t)})}async done(){w(this,Ie,!0),await o(this,xt,"f")}get currentMessage(){return o(this,ke,"f")}async finalMessage(){return await this.done(),o(this,q,"m",sr).call(this)}async finalText(){return await this.done(),o(this,q,"m",mi).call(this)}_emit(e,...t){if(o(this,At,"f"))return;e==="end"&&(w(this,At,!0),o(this,gn,"f").call(this));const s=o(this,ue,"f")[e];if(s&&(o(this,ue,"f")[e]=s.filter(i=>!i.once),s.forEach(({listener:i})=>i(...t))),e==="abort"){const i=t[0];!o(this,Ie,"f")&&!s?.length&&Promise.reject(i),o(this,St,"f").call(this,i),o(this,Rt,"f").call(this,i),this._emit("end");return}if(e==="error"){const i=t[0];!o(this,Ie,"f")&&!s?.length&&Promise.reject(i),o(this,St,"f").call(this,i),o(this,Rt,"f").call(this,i),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",o(this,q,"m",sr).call(this))}async _fromReadableStream(e,t){const s=t?.signal;let i;s&&(s.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),s.addEventListener("abort",i));try{o(this,q,"m",ir).call(this),this._connected(null);const a=dt.fromReadableStream(e,this.controller);for await(const c of a)o(this,q,"m",ar).call(this,c);if(a.controller.signal?.aborted)throw new oe;o(this,q,"m",or).call(this)}finally{s&&i&&s.removeEventListener("abort",i)}}[(ke=new WeakMap,Qe=new WeakMap,kt=new WeakMap,_n=new WeakMap,St=new WeakMap,xt=new WeakMap,gn=new WeakMap,Rt=new WeakMap,ue=new WeakMap,At=new WeakMap,mn=new WeakMap,wn=new WeakMap,Ie=new WeakMap,yn=new WeakMap,bn=new WeakMap,vn=new WeakMap,Et=new WeakMap,Tt=new WeakMap,q=new WeakSet,sr=function(){if(this.receivedMessages.length===0)throw new S("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},mi=function(){if(this.receivedMessages.length===0)throw new S("stream ended without producing a Message with role=assistant");const t=this.receivedMessages.at(-1).content.filter(s=>s.type==="text").map(s=>s.text);if(t.length===0)throw new S("stream ended without producing a content block with type=text");return t.join(" ")},ir=function(){this.ended||w(this,ke,void 0)},ar=function(t){if(this.ended)return;const s=o(this,q,"m",wi).call(this,t);switch(this._emit("streamEvent",t,s),t.type){case"content_block_delta":{const i=s.content.at(-1);switch(t.delta.type){case"text_delta":{i.type==="text"&&this._emit("text",t.delta.text,i.text||"");break}case"citations_delta":{i.type==="text"&&this._emit("citation",t.delta.citation,i.citations??[]);break}case"input_json_delta":{if(lr(i)&&o(this,ue,"f").inputJson?.length){let a;try{a=i.input}catch(c){o(this,Tt,"f").call(this,o(this,q,"m",cr).call(this,i,c));break}this._emit("inputJson",t.delta.partial_json,a)}break}case"thinking_delta":{i.type==="thinking"&&this._emit("thinking",t.delta.thinking,i.thinking);break}case"signature_delta":{i.type==="thinking"&&this._emit("signature",i.signature);break}case"compaction_delta":{i.type==="compaction"&&i.content&&this._emit("compaction",i.content);break}default:t.delta}break}case"message_stop":{this._addMessageParam(s),this._addMessage(gi(s,o(this,Qe,"f"),{logger:o(this,Et,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",s.content.at(-1));break}case"message_start":{w(this,ke,s);break}}},or=function(){if(this.ended)throw new S("stream has ended, this shouldn't happen");const t=o(this,ke,"f");if(!t)throw new S("request ended without sending any chunks");return w(this,ke,void 0),gi(t,o(this,Qe,"f"),{logger:o(this,Et,"f")})},wi=function(t){let s=o(this,ke,"f");if(t.type==="message_start"){if(s)throw new S(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!s)throw new S(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return s;case"message_delta":return s.stop_reason=t.delta.stop_reason,s.stop_sequence=t.delta.stop_sequence,s.stop_details=t.delta.stop_details,s.usage.output_tokens=t.usage.output_tokens,t.delta.container!=null&&(s.container=t.delta.container),t.context_management!=null&&(s.context_management=t.context_management),t.input_transformations!=null&&(s.input_transformations=t.input_transformations),t.usage.input_tokens!=null&&(s.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(s.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(s.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(s.usage.server_tool_use=t.usage.server_tool_use),t.usage.iterations!=null&&(s.usage.iterations=t.usage.iterations),t.usage.fallback_credit!=null&&(s.usage.fallback_credit=t.usage.fallback_credit),t.usage.output_tokens_details!=null&&(s.usage.output_tokens_details=t.usage.output_tokens_details),s;case"content_block_start":return s.content.push(t.content_block),t.content_block.type==="fallback"&&(s.model=t.content_block.to.model),s;case"content_block_delta":{const i=s.content.at(t.index);switch(t.delta.type){case"text_delta":{i?.type==="text"&&(s.content[t.index]={...i,text:(i.text||"")+t.delta.text});break}case"citations_delta":{i?.type==="text"&&(s.content[t.index]={...i,citations:[...i.citations??[],t.delta.citation]});break}case"input_json_delta":{if(i&&lr(i)){const a=(i[ct]||"")+t.delta.partial_json;s.content[t.index]=Wc(i,a)}break}case"thinking_delta":{i?.type==="thinking"&&(s.content[t.index]={...i,thinking:i.thinking+t.delta.thinking});break}case"signature_delta":{i?.type==="thinking"&&(s.content[t.index]={...i,signature:t.delta.signature});break}case"compaction_delta":{if(i?.type==="compaction"){const a={...i,content:t.delta.content};"encrypted_content"in t.delta&&(a.encrypted_content=t.delta.encrypted_content),s.content[t.index]=a}break}default:t.delta}return s}case"content_block_stop":{const i=s.content.at(t.index);if(i&&lr(i)&&ct in i){let a;try{a=i.input}catch(c){a={},o(this,Tt,"f").call(this,o(this,q,"m",cr).call(this,i,c))}Object.defineProperty(i,"input",{value:a,enumerable:!0,configurable:!0,writable:!0})}return s}}},cr=function(t,s){const i=t[ct];return new S(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${s}. JSON: ${i}`)},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("streamEvent",i=>{const a=t.shift();a?a.resolve(i):e.push(i)}),this.on("end",()=>{s=!0;for(const i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{s=!0;for(const a of t)a.reject(i);t.length=0}),this.on("error",i=>{s=!0;for(const a of t)a.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((a,c)=>t.push({resolve:a,reject:c})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new dt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}return n})();let yi=class extends v{retrieve(r,e){return this._client.get(h`/v1/organizations/api_keys/${r}?beta=true`,e)}update(r,e,t){return this._client.post(h`/v1/organizations/api_keys/${r}?beta=true`,{body:e,...t})}list(r={},e){return this._client.getAPIList("/v1/organizations/api_keys?beta=true",X,{query:r,...e})}};class bi extends v{list(r,e){return this._client.getAPIList("/v1/organizations/analytics/artifacts?beta=true",A,{query:r,...e})}}class vi extends v{list(r={},e){return this._client.getAPIList("/v1/organizations/analytics/connectors?beta=true",A,{query:r,...e})}}class ki extends v{list(r,e){return this._client.getAPIList("/v1/organizations/analytics/cost_report?beta=true",A,{query:r,...e})}}let Si=class extends v{list(r={},e){return this._client.getAPIList("/v1/organizations/analytics/plugins?beta=true",A,{query:r,...e})}},xi=class extends v{list(r={},e){return this._client.getAPIList("/v1/organizations/analytics/skills?beta=true",A,{query:r,...e})}};class Ri extends v{list(r,e){return this._client.getAPIList("/v1/organizations/analytics/summaries?beta=true",A,{query:r,...e})}}class Ai extends v{list(r,e){return this._client.getAPIList("/v1/organizations/analytics/usage_report?beta=true",A,{query:r,...e})}}class Ei extends v{list(r,e){return this._client.getAPIList("/v1/organizations/analytics/user_cost_report?beta=true",A,{query:r,...e})}}class Ti extends v{list(r,e){return this._client.getAPIList("/v1/organizations/analytics/user_usage_report?beta=true",A,{query:r,...e})}}let $i=class extends v{list(r={},e){return this._client.getAPIList("/v1/organizations/analytics/users?beta=true",A,{query:r,...e})}};class Ii extends v{list(r={},e){return this._client.getAPIList("/v1/organizations/analytics/apps/chat/projects?beta=true",A,{query:r,...e})}}var Pi=(()=>{class n extends v{constructor(){super(...arguments),this.projects=new Ii(this._client)}}return n.Projects=Ii,n})(),Mi=(()=>{class n extends v{constructor(){super(...arguments),this.chat=new Pi(this._client)}}return n.Chat=Pi,n})(),Oi=(()=>{class n extends v{constructor(){super(...arguments),this.summaries=new Ri(this._client),this.users=new $i(this._client),this.apps=new Mi(this._client),this.connectors=new vi(this._client),this.plugins=new Si(this._client),this.skills=new xi(this._client),this.artifacts=new bi(this._client),this.usageReport=new Ai(this._client),this.userUsageReport=new Ti(this._client),this.costReport=new ki(this._client),this.userCostReport=new Ei(this._client)}}return n.Summaries=Ri,n.Users=$i,n.Apps=Mi,n.Connectors=vi,n.Plugins=Si,n.Skills=xi,n.Artifacts=bi,n.UsageReport=Ai,n.UserUsageReport=Ti,n.CostReport=ki,n.UserCostReport=Ei,n})();let Ci=class extends v{retrieve(r){return this._client.get("/v1/organizations/compliance_settings?beta=true",r)}update(r,e){return this._client.post("/v1/organizations/compliance_settings?beta=true",{body:r,...e})}},Li=class extends v{create(r,e){return this._client.post("/v1/organizations/external_keys?beta=true",{body:r,...e})}retrieve(r,e){return this._client.get(h`/v1/organizations/external_keys/${r}?beta=true`,e)}update(r,e,t){return this._client.post(h`/v1/organizations/external_keys/${r}?beta=true`,{body:e,...t})}list(r={},e){return this._client.getAPIList("/v1/organizations/external_keys?beta=true",A,{query:r,...e})}delete(r,e){return this._client.delete(h`/v1/organizations/external_keys/${r}?beta=true`,e)}validate(r,e){return this._client.post(h`/v1/organizations/external_keys/${r}/validate?beta=true`,e)}},Ni=class extends v{create(r,e){const{betas:t,...s}=r;return this._client.post("/v1/organizations/federation_issuers?beta=true",{body:s,...e,headers:f([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0},e?.headers])})}retrieve(r,e={},t){const{betas:s}=e??{};return this._client.get(h`/v1/organizations/federation_issuers/${r}?beta=true`,{...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}update(r,e,t){const{betas:s,...i}=e;return this._client.post(h`/v1/organizations/federation_issuers/${r}?beta=true`,{body:i,...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}list(r={},e){const{betas:t,...s}=r??{};return this._client.getAPIList("/v1/organizations/federation_issuers?beta=true",A,{query:s,...e,headers:f([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0},e?.headers])})}archive(r,e={},t){const{betas:s}=e??{};return this._client.post(h`/v1/organizations/federation_issuers/${r}/archive?beta=true`,{...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}},Bi=class extends v{list(r,e={},t){const{betas:s,...i}=e??{};return this._client.getAPIList(h`/v1/organizations/federation_rules/${r}/workspaces?beta=true`,A,{query:i,...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}add(r,e,t){const{betas:s,...i}=e;return this._client.post(h`/v1/organizations/federation_rules/${r}/workspaces?beta=true`,{body:i,...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}remove(r,e,t){const{federation_rule_id:s,betas:i}=e;return this._client.delete(h`/v1/organizations/federation_rules/${s}/workspaces/${r}?beta=true`,{...t,headers:f([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},t?.headers])})}};var Di=(()=>{class n extends v{constructor(){super(...arguments),this.workspaces=new Bi(this._client)}create(e,t){const{betas:s,...i}=e;return this._client.post("/v1/organizations/federation_rules?beta=true",{body:i,...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:i}=t??{};return this._client.get(h`/v1/organizations/federation_rules/${e}?beta=true`,{...s,headers:f([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers])})}update(e,t,s){const{betas:i,...a}=t;return this._client.post(h`/v1/organizations/federation_rules/${e}?beta=true`,{body:a,...s,headers:f([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers])})}list(e={},t){const{betas:s,...i}=e??{};return this._client.getAPIList("/v1/organizations/federation_rules?beta=true",A,{query:i,...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}archive(e,t={},s){const{betas:i}=t??{};return this._client.post(h`/v1/organizations/federation_rules/${e}/archive?beta=true`,{...s,headers:f([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers])})}}return n.Workspaces=Bi,n})(),Ui=(()=>{class n extends v{constructor(){super(...arguments),this.issuers=new Ni(this._client),this.rules=new Di(this._client)}}return n.Issuers=Ni,n.Rules=Di,n})();let Hi=class extends v{create(r,e){return this._client.post("/v1/organizations/invites?beta=true",{body:r,...e})}retrieve(r,e){return this._client.get(h`/v1/organizations/invites/${r}?beta=true`,e)}list(r={},e){return this._client.getAPIList("/v1/organizations/invites?beta=true",X,{query:r,...e})}delete(r,e){return this._client.delete(h`/v1/organizations/invites/${r}?beta=true`,e)}};class Wi extends v{retrieve(r,e={},t){const{betas:s,...i}=e??{};return this._client.get(h`/v1/organizations/plugin_marketplaces/${r}?beta=true`,{query:i,...t,headers:f([{"anthropic-beta":[...s??[],"ce-plugins-2026-09-01"].toString()},t?.headers])})}update(r,e,t){const{betas:s,...i}=e;return this._client.post(h`/v1/organizations/plugin_marketplaces/${r}?beta=true`,{body:i,...t,headers:f([{"anthropic-beta":[...s??[],"ce-plugins-2026-09-01"].toString()},t?.headers])})}list(r={},e){const{betas:t,...s}=r??{};return this._client.getAPIList("/v1/organizations/plugin_marketplaces?beta=true",A,{query:s,...e,headers:f([{"anthropic-beta":[...t??[],"ce-plugins-2026-09-01"].toString()},e?.headers])})}validateArchive(r,e){const{betas:t,...s}=r;return this._client.post("/v1/organizations/plugin_marketplaces/validate_archive?beta=true",me({body:s,...e,headers:f([{"anthropic-beta":[...t??[],"ce-plugins-2026-09-01"].toString()},e?.headers])},this._client))}validateRepository(r,e){const{betas:t,...s}=r;return this._client.post("/v1/organizations/plugin_marketplaces/validate_repository?beta=true",{body:s,...e,headers:f([{"anthropic-beta":[...t??[],"ce-plugins-2026-09-01"].toString()},e?.headers])})}}let zi=class extends v{list(r={},e){return this._client.getAPIList("/v1/organizations/rate_limits?beta=true",A,{query:r,...e})}},ji=class extends v{retrieve(r,e){return this._client.get(h`/v1/organizations/users/${r}?beta=true`,e)}update(r,e,t){return this._client.post(h`/v1/organizations/users/${r}?beta=true`,{body:e,...t})}list(r={},e){return this._client.getAPIList("/v1/organizations/users?beta=true",X,{query:r,...e})}remove(r,e){return this._client.delete(h`/v1/organizations/users/${r}?beta=true`,e)}};class Fi extends v{list(r,e={},t){const{betas:s,...i}=e??{};return this._client.getAPIList(h`/v1/organizations/plugins/${r}/installation_settings?beta=true`,A,{query:i,...t,headers:f([{"anthropic-beta":[...s??[],"ce-plugins-2026-09-01"].toString()},t?.headers])})}remove(r,e,t){const{plugin_id:s,betas:i}=e;return this._client.delete(h`/v1/organizations/plugins/${s}/installation_settings/${r}?beta=true`,{...t,headers:f([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},t?.headers])})}set(r,e,t){const{plugin_id:s,betas:i,...a}=e;return this._client.post(h`/v1/organizations/plugins/${s}/installation_settings/${r}?beta=true`,{body:a,...t,headers:f([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},t?.headers])})}}class qi extends v{list(r,e={},t){const{betas:s,...i}=e??{};return this._client.getAPIList(h`/v1/organizations/plugins/${r}/shares?beta=true`,A,{query:i,...t,headers:f([{"anthropic-beta":[...s??[],"ce-plugins-2026-09-01"].toString()},t?.headers])})}}let Ki=class extends v{create(r,e,t){const{betas:s,...i}=e;return this._client.post(h`/v1/organizations/plugins/${r}/versions?beta=true`,me({body:i,...t,headers:f([{"anthropic-beta":[...s??[],"ce-plugins-2026-09-01"].toString()},t?.headers])},this._client))}retrieve(r,e,t){const{plugin_id:s,betas:i,...a}=e;return this._client.get(h`/v1/organizations/plugins/${s}/versions/${r}?beta=true`,{query:a,...t,headers:f([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},t?.headers])})}list(r,e={},t){const{betas:s,...i}=e??{};return this._client.getAPIList(h`/v1/organizations/plugins/${r}/versions?beta=true`,A,{query:i,...t,headers:f([{"anthropic-beta":[...s??[],"ce-plugins-2026-09-01"].toString()},t?.headers])})}download(r,e,t){const{plugin_id:s,betas:i,...a}=e;return this._client.get(h`/v1/organizations/plugins/${s}/versions/${r}/content?beta=true`,{query:a,...t,headers:f([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString(),Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}};var Vi=(()=>{class n extends v{constructor(){super(...arguments),this.versions=new Ki(this._client),this.installationSettings=new Fi(this._client),this.shares=new qi(this._client)}create(e,t){const{betas:s,...i}=e;return this._client.post("/v1/organizations/plugins?beta=true",me({body:i,...t,headers:f([{"anthropic-beta":[...s??[],"ce-plugins-2026-09-01"].toString()},t?.headers])},this._client))}retrieve(e,t={},s){const{betas:i,...a}=t??{};return this._client.get(h`/v1/organizations/plugins/${e}?beta=true`,{query:a,...s,headers:f([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},s?.headers])})}update(e,t,s){const{betas:i,...a}=t;return this._client.post(h`/v1/organizations/plugins/${e}?beta=true`,{body:a,...s,headers:f([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},s?.headers])})}list(e={},t){const{betas:s,...i}=e??{};return this._client.getAPIList("/v1/organizations/plugins?beta=true",A,{query:i,...t,headers:f([{"anthropic-beta":[...s??[],"ce-plugins-2026-09-01"].toString()},t?.headers])})}delete(e,t={},s){const{betas:i}=t??{};return this._client.delete(h`/v1/organizations/plugins/${e}?beta=true`,{...s,headers:f([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},s?.headers])})}}return n.Versions=Ki,n.InstallationSettings=Fi,n.Shares=qi,n})();let Ji=class extends v{list(r,e={},t){return this._client.getAPIList(h`/v1/organizations/rbac_groups/${r}/members?beta=true`,A,{query:e,...t})}add(r,e,t){return this._client.post(h`/v1/organizations/rbac_groups/${r}/members?beta=true`,{body:e,...t})}remove(r,e,t){const{rbac_group_id:s}=e;return this._client.delete(h`/v1/organizations/rbac_groups/${s}/members/${r}?beta=true`,t)}};var Xi=(()=>{class n extends v{constructor(){super(...arguments),this.members=new Ji(this._client)}create(e,t){return this._client.post("/v1/organizations/rbac_groups?beta=true",{body:e,...t})}retrieve(e,t){return this._client.get(h`/v1/organizations/rbac_groups/${e}?beta=true`,t)}update(e,t,s){return this._client.post(h`/v1/organizations/rbac_groups/${e}?beta=true`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/rbac_groups?beta=true",A,{query:e,...t})}delete(e,t){return this._client.delete(h`/v1/organizations/rbac_groups/${e}?beta=true`,t)}}return n.Members=Ji,n})();class Gi extends v{list(r,e={},t){return this._client.getAPIList(h`/v1/organizations/rbac_roles/${r}/permissions?beta=true`,A,{query:e,...t})}}var Qi=(()=>{class n extends v{constructor(){super(...arguments),this.permissions=new Gi(this._client)}retrieve(e,t){return this._client.get(h`/v1/organizations/rbac_roles/${e}?beta=true`,t)}list(e={},t){return this._client.getAPIList("/v1/organizations/rbac_roles?beta=true",A,{query:e,...t})}}return n.Permissions=Gi,n})();let Yi=class extends v{list(r,e={},t){const{betas:s,...i}=e??{};return this._client.getAPIList(h`/v1/organizations/service_accounts/${r}/workspaces?beta=true`,A,{query:i,...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}add(r,e,t){const{betas:s,...i}=e;return this._client.post(h`/v1/organizations/service_accounts/${r}/workspaces?beta=true`,{body:i,...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}remove(r,e,t){const{service_account_id:s,betas:i}=e;return this._client.delete(h`/v1/organizations/service_accounts/${s}/workspaces/${r}?beta=true`,{...t,headers:f([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},t?.headers])})}};var Zi=(()=>{class n extends v{constructor(){super(...arguments),this.workspaces=new Yi(this._client)}create(e,t){const{betas:s,...i}=e;return this._client.post("/v1/organizations/service_accounts?beta=true",{body:i,...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:i}=t??{};return this._client.get(h`/v1/organizations/service_accounts/${e}?beta=true`,{...s,headers:f([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers])})}update(e,t,s){const{betas:i,...a}=t;return this._client.post(h`/v1/organizations/service_accounts/${e}?beta=true`,{body:a,...s,headers:f([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers])})}list(e={},t){const{betas:s,...i}=e??{};return this._client.getAPIList("/v1/organizations/service_accounts?beta=true",A,{query:i,...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}archive(e,t={},s){const{betas:i}=t??{};return this._client.post(h`/v1/organizations/service_accounts/${e}/archive?beta=true`,{...s,headers:f([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers])})}}return n.Workspaces=Yi,n})();class ea extends v{list(r={},e){return this._client.getAPIList("/v1/organizations/spend_limits/effective?beta=true",A,{query:r,...e})}}class ta extends v{retrieve(r,e){return this._client.get(h`/v1/organizations/spend_limit_increase_requests/${r}?beta=true`,e)}list(r={},e){return this._client.getAPIList("/v1/organizations/spend_limit_increase_requests?beta=true",A,{query:r,...e})}approve(r,e,t){return this._client.post(h`/v1/organizations/spend_limit_increase_requests/${r}/approve?beta=true`,{body:e,...t})}deny(r,e,t){return this._client.post(h`/v1/organizations/spend_limit_increase_requests/${r}/deny?beta=true`,{body:e,...t})}}var na=(()=>{class n extends v{constructor(){super(...arguments),this.effective=new ea(this._client),this.increaseRequests=new ta(this._client)}retrieve(e,t){return this._client.get(h`/v1/organizations/spend_limits/${e}?beta=true`,t)}list(e={},t){const{betas:s,...i}=e??{};return this._client.getAPIList("/v1/organizations/spend_limits?beta=true",A,{query:i,...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}delete(e,t){return this._client.delete(h`/v1/organizations/spend_limits/${e}?beta=true`,t)}set(e,t){return this._client.post("/v1/organizations/spend_limits?beta=true",{body:e,...t})}}return n.Effective=ea,n.IncreaseRequests=ta,n})();let ra=class extends v{retrieve(r,e,t){const{workspace_id:s}=e;return this._client.get(h`/v1/organizations/workspaces/${s}/members/${r}?beta=true`,t)}update(r,e,t){const{workspace_id:s,...i}=e;return this._client.post(h`/v1/organizations/workspaces/${s}/members/${r}?beta=true`,{body:i,...t})}list(r,e={},t){return this._client.getAPIList(h`/v1/organizations/workspaces/${r}/members?beta=true`,X,{query:e,...t})}add(r,e,t){return this._client.post(h`/v1/organizations/workspaces/${r}/members?beta=true`,{body:e,...t})}remove(r,e,t){const{workspace_id:s}=e;return this._client.delete(h`/v1/organizations/workspaces/${s}/members/${r}?beta=true`,t)}},sa=class extends v{list(r,e={},t){return this._client.getAPIList(h`/v1/organizations/workspaces/${r}/rate_limits?beta=true`,A,{query:e,...t})}},ia=class extends v{retrieve(r,e,t){const{workspace_id:s,betas:i}=e;return this._client.get(h`/v1/organizations/workspaces/${s}/service_accounts/${r}?beta=true`,{...t,headers:f([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},t?.headers])})}update(r,e,t){const{workspace_id:s,betas:i,...a}=e;return this._client.post(h`/v1/organizations/workspaces/${s}/service_accounts/${r}?beta=true`,{body:a,...t,headers:f([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},t?.headers])})}list(r,e={},t){const{betas:s,...i}=e??{};return this._client.getAPIList(h`/v1/organizations/workspaces/${r}/service_accounts?beta=true`,A,{query:i,...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}add(r,e,t){const{betas:s,...i}=e;return this._client.post(h`/v1/organizations/workspaces/${r}/service_accounts?beta=true`,{body:i,...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}remove(r,e,t){const{workspace_id:s,betas:i}=e;return this._client.delete(h`/v1/organizations/workspaces/${s}/service_accounts/${r}?beta=true`,{...t,headers:f([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},t?.headers])})}};var aa=(()=>{class n extends v{constructor(){super(...arguments),this.rateLimits=new sa(this._client),this.members=new ra(this._client),this.serviceAccounts=new ia(this._client)}create(e,t){const{betas:s,...i}=e;return this._client.post("/v1/organizations/workspaces?beta=true",{body:i,...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}retrieve(e,t){return this._client.get(h`/v1/organizations/workspaces/${e}?beta=true`,t)}update(e,t,s){return this._client.post(h`/v1/organizations/workspaces/${e}?beta=true`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/workspaces?beta=true",X,{query:e,...t})}archive(e,t){return this._client.post(h`/v1/organizations/workspaces/${e}/archive?beta=true`,t)}}return n.RateLimits=sa,n.Members=ra,n.ServiceAccounts=ia,n})(),oa=(()=>{class n extends v{constructor(){super(...arguments),this.apiKeys=new yi(this._client),this.externalKeys=new Li(this._client),this.federation=new Ui(this._client),this.invites=new Hi(this._client),this.serviceAccounts=new Zi(this._client),this.users=new ji(this._client),this.workspaces=new aa(this._client),this.rateLimits=new zi(this._client),this.complianceSettings=new Ci(this._client),this.analytics=new Oi(this._client),this.spendLimits=new na(this._client),this.rbacGroups=new Xi(this._client),this.rbacRoles=new Qi(this._client),this.plugins=new Vi(this._client),this.pluginMarketplaces=new Wi(this._client)}retrieve(e){return this._client.get("/v1/organizations/me?beta=true",e)}}return n.APIKeys=yi,n.ExternalKeys=Li,n.Federation=Ui,n.Invites=Hi,n.ServiceAccounts=Zi,n.Users=ji,n.Workspaces=aa,n.RateLimits=zi,n.ComplianceSettings=Ci,n.Analytics=Oi,n.SpendLimits=na,n.RBACGroups=Xi,n.RBACRoles=Qi,n.Plugins=Vi,n.PluginMarketplaces=Wi,n})(),ca=(()=>{class n extends v{list(e,t={},s){const{betas:i,workspace_id:a,...c}=t??{};return this._client.getAPIList(h`/v1/sessions/${e}/events?beta=true`,A,{query:c,...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}send(e,t,s){const{betas:i,workspace_id:a,...c}=t;return this._client.post(h`/v1/sessions/${e}/events?beta=true`,{body:c,...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}stream(e,t={},s){const{betas:i,workspace_id:a,...c}=t??{};return this._client.get(h`/v1/sessions/${e}/events/stream?beta=true`,{query:c,...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers]),stream:!0})}toolRunner(e,t){return new zr(e,{...t,client:this._client})}}return n.SessionToolRunner=zr,n})();class la extends v{retrieve(r,e,t){const{session_id:s,betas:i,workspace_id:a}=e;return this._client.get(h`/v1/sessions/${s}/resources/${r}?beta=true`,{...t,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}update(r,e,t){const{session_id:s,betas:i,workspace_id:a,...c}=e;return this._client.post(h`/v1/sessions/${s}/resources/${r}?beta=true`,{body:c,...t,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}list(r,e={},t){const{betas:s,workspace_id:i,...a}=e??{};return this._client.getAPIList(h`/v1/sessions/${r}/resources?beta=true`,A,{query:a,...t,headers:f([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}delete(r,e,t){const{session_id:s,betas:i,workspace_id:a}=e;return this._client.delete(h`/v1/sessions/${s}/resources/${r}?beta=true`,{...t,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}add(r,e,t){const{betas:s,workspace_id:i,...a}=e;return this._client.post(h`/v1/sessions/${r}/resources?beta=true`,{body:a,...t,headers:f([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}}class ua extends v{list(r,e,t){const{session_id:s,betas:i,workspace_id:a,...c}=e;return this._client.getAPIList(h`/v1/sessions/${s}/threads/${r}/events?beta=true`,A,{query:c,...t,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}stream(r,e,t){const{session_id:s,betas:i,workspace_id:a,...c}=e;return this._client.get(h`/v1/sessions/${s}/threads/${r}/stream?beta=true`,{query:c,...t,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers]),stream:!0})}}var da=(()=>{class n extends v{constructor(){super(...arguments),this.events=new ua(this._client)}retrieve(e,t,s){const{session_id:i,betas:a,workspace_id:c}=t;return this._client.get(h`/v1/sessions/${i}/threads/${e}?beta=true`,{...s,headers:f([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers])})}list(e,t={},s){const{betas:i,workspace_id:a,...c}=t??{};return this._client.getAPIList(h`/v1/sessions/${e}/threads?beta=true`,A,{query:c,...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}archive(e,t,s){const{session_id:i,betas:a,workspace_id:c}=t;return this._client.post(h`/v1/sessions/${i}/threads/${e}/archive?beta=true`,{...s,headers:f([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers])})}}return n.Events=ua,n})(),ha=(()=>{class n extends v{constructor(){super(...arguments),this.events=new ca(this._client),this.resources=new la(this._client),this.threads=new da(this._client)}create(e,t){const{betas:s,workspace_id:i,...a}=e;return this._client.post("/v1/sessions?beta=true",{body:a,...t,headers:f([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:i,workspace_id:a}=t??{};return this._client.get(h`/v1/sessions/${e}?beta=true`,{...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}update(e,t,s){const{betas:i,workspace_id:a,...c}=t;return this._client.post(h`/v1/sessions/${e}?beta=true`,{body:c,...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:i,...a}=e??{};return this._client.getAPIList("/v1/sessions?beta=true",hu,{query:a,...t,headers:f([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}delete(e,t={},s){const{betas:i,workspace_id:a}=t??{};return this._client.delete(h`/v1/sessions/${e}?beta=true`,{...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}archive(e,t={},s){const{betas:i,workspace_id:a}=t??{};return this._client.post(h`/v1/sessions/${e}/archive?beta=true`,{...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}}return n.Events=ca,n.Resources=la,n.Threads=da,n})();let fa=class extends v{create(r,e,t){const{betas:s,workspace_id:i,...a}=e;return this._client.post(h`/v1/skills/${r}/versions?beta=true`,me({body:a,...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])},this._client,!1))}retrieve(r,e,t){const{skill_id:s,betas:i,workspace_id:a}=e;return this._client.get(h`/v1/skills/${s}/versions/${r}?beta=true`,{...t,headers:f([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}list(r,e={},t){const{betas:s,workspace_id:i,...a}=e??{};return this._client.getAPIList(h`/v1/skills/${r}/versions?beta=true`,A,{query:a,...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}delete(r,e,t){const{skill_id:s,betas:i,workspace_id:a}=e;return this._client.delete(h`/v1/skills/${s}/versions/${r}?beta=true`,{...t,headers:f([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}download(r,e,t){const{skill_id:s,betas:i,workspace_id:a}=e;return this._client.get(h`/v1/skills/${s}/versions/${r}/content?beta=true`,{...t,headers:f([{Accept:"application/binary",...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers]),__binaryResponse:!0})}};var pa=(()=>{class n extends v{constructor(){super(...arguments),this.versions=new fa(this._client)}create(e,t){const{betas:s,workspace_id:i,...a}=e;return this._client.post("/v1/skills?beta=true",me({body:a,...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])},this._client,!1))}retrieve(e,t={},s){const{betas:i,workspace_id:a}=t??{};return this._client.get(h`/v1/skills/${e}?beta=true`,{...s,headers:f([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:i,...a}=e??{};return this._client.getAPIList("/v1/skills?beta=true",A,{query:a,...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}delete(e,t={},s){const{betas:i,workspace_id:a}=t??{};return this._client.delete(h`/v1/skills/${e}?beta=true`,{...s,headers:f([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}}return n.Versions=fa,n})();class _a extends v{create(r,e,t){const{betas:s,workspace_id:i,...a}=e;return this._client.post(h`/v1/tunnels/${r}/certificates?beta=true`,{body:a,...t,headers:f([{"anthropic-beta":[...s??[],"mcp-tunnels-2026-06-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}retrieve(r,e,t){const{tunnel_id:s,betas:i,workspace_id:a}=e;return this._client.get(h`/v1/tunnels/${s}/certificates/${r}?beta=true`,{...t,headers:f([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}list(r,e={},t){const{betas:s,workspace_id:i,...a}=e??{};return this._client.getAPIList(h`/v1/tunnels/${r}/certificates?beta=true`,A,{query:a,...t,headers:f([{"anthropic-beta":[...s??[],"mcp-tunnels-2026-06-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}archive(r,e,t){const{tunnel_id:s,betas:i,workspace_id:a}=e;return this._client.post(h`/v1/tunnels/${s}/certificates/${r}/archive?beta=true`,{...t,headers:f([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}}var ga=(()=>{class n extends v{constructor(){super(...arguments),this.certificates=new _a(this._client)}create(e,t){const{betas:s,workspace_id:i,...a}=e;return this._client.post("/v1/tunnels?beta=true",{body:a,...t,headers:f([{"anthropic-beta":[...s??[],"mcp-tunnels-2026-06-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:i,workspace_id:a}=t??{};return this._client.get(h`/v1/tunnels/${e}?beta=true`,{...s,headers:f([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:i,...a}=e??{};return this._client.getAPIList("/v1/tunnels?beta=true",A,{query:a,...t,headers:f([{"anthropic-beta":[...s??[],"mcp-tunnels-2026-06-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}archive(e,t={},s){const{betas:i,workspace_id:a}=t??{};return this._client.post(h`/v1/tunnels/${e}/archive?beta=true`,{...s,headers:f([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}revealToken(e,t={},s){const{betas:i,workspace_id:a}=t??{};return this._client.post(h`/v1/tunnels/${e}/reveal_token?beta=true`,{...s,headers:f([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}rotateToken(e,t,s){const{betas:i,workspace_id:a,...c}=t;return this._client.post(h`/v1/tunnels/${e}/rotate_token?beta=true`,{body:c,...s,headers:f([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}}return n.Certificates=_a,n})();class ma extends v{create(r,e,t){const{betas:s,workspace_id:i,...a}=e;return this._client.post(h`/v1/vaults/${r}/credentials?beta=true`,{body:a,...t,headers:f([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}retrieve(r,e,t){const{vault_id:s,betas:i,workspace_id:a}=e;return this._client.get(h`/v1/vaults/${s}/credentials/${r}?beta=true`,{...t,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}update(r,e,t){const{vault_id:s,betas:i,workspace_id:a,...c}=e;return this._client.post(h`/v1/vaults/${s}/credentials/${r}?beta=true`,{body:c,...t,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}list(r,e={},t){const{betas:s,workspace_id:i,...a}=e??{};return this._client.getAPIList(h`/v1/vaults/${r}/credentials?beta=true`,A,{query:a,...t,headers:f([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}delete(r,e,t){const{vault_id:s,betas:i,workspace_id:a}=e;return this._client.delete(h`/v1/vaults/${s}/credentials/${r}?beta=true`,{...t,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}archive(r,e,t){const{vault_id:s,betas:i,workspace_id:a}=e;return this._client.post(h`/v1/vaults/${s}/credentials/${r}/archive?beta=true`,{...t,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}mcpOAuthValidate(r,e,t){const{vault_id:s,betas:i,workspace_id:a}=e;return this._client.post(h`/v1/vaults/${s}/credentials/${r}/mcp_oauth_validate?beta=true`,{...t,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}}var wa=(()=>{class n extends v{constructor(){super(...arguments),this.credentials=new ma(this._client)}create(e,t){const{betas:s,workspace_id:i,...a}=e;return this._client.post("/v1/vaults?beta=true",{body:a,...t,headers:f([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:i,workspace_id:a}=t??{};return this._client.get(h`/v1/vaults/${e}?beta=true`,{...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}update(e,t,s){const{betas:i,workspace_id:a,...c}=t;return this._client.post(h`/v1/vaults/${e}?beta=true`,{body:c,...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:i,...a}=e??{};return this._client.getAPIList("/v1/vaults?beta=true",A,{query:a,...t,headers:f([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}delete(e,t={},s){const{betas:i,workspace_id:a}=t??{};return this._client.delete(h`/v1/vaults/${e}?beta=true`,{...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}archive(e,t={},s){const{betas:i,workspace_id:a}=t??{};return this._client.post(h`/v1/vaults/${e}/archive?beta=true`,{...s,headers:f([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},s?.headers])})}}return n.Credentials=ma,n})(),_e,kn,Pe,Ye,Sn,Me,Ze,xn,ya,Rn,An,ba=(()=>{class n extends zc{constructor(e,t){super(e),_e.add(this),kn.set(this,void 0),Pe.set(this,0),Ye.set(this,[]),Sn.set(this,[]),Me.set(this,void 0),Ze.set(this,[]),xn.set(this,!1),w(this,kn,t)}get toolCalls(){return o(this,Sn,"f")}static start(e,t,s,i){const a=new n({...t,stream:!0},i);for(const c of t.messages)a._addMessageParam(c);return a._run(()=>a._createMessage(e,{...t,stream:!0},{...s,headers:{...s?.headers,[os]:"stream"}})),a}_emit(e,...t){var s;if(e!=="streamEvent"||this.ended){super._emit(e,...t);return}w(this,Pe,(s=o(this,Pe,"f"),s++,s));const[i,a]=t,c=i.type==="content_block_stop"?a.content[i.index]:void 0,u=c?.type==="tool_use"?c:void 0;u&&o(this,Sn,"f").push(u),super._emit(e,...t),o(this,_e,"m",ya).call(this,i,u),o(this,_e,"m",Rn).call(this)}[(kn=new WeakMap,Pe=new WeakMap,Ye=new WeakMap,Sn=new WeakMap,Me=new WeakMap,Ze=new WeakMap,xn=new WeakMap,_e=new WeakSet,Symbol.asyncIterator)](){const e=super[Symbol.asyncIterator](),t={handled:o(this,Pe,"f")};o(this,Ye,"f").push(t);let s=!1;return{next:async()=>{s&&(s=!1,t.handled++,o(this,_e,"m",Rn).call(this));try{const i=await e.next();return s=!i.done,i.done&&o(this,_e,"m",An).call(this,t),i}catch(i){throw o(this,_e,"m",An).call(this,t),i}},return:async()=>{const i=e.return?.();return o(this,_e,"m",An).call(this,t),await i??{value:void 0,done:!0}}}}}return ya=function(e,t){if(o(this,xn,"f"))return;if(e.type==="content_block_start"&&e.content_block.type==="fallback"){w(this,xn,!0),w(this,Me,void 0);return}const s=e.type==="content_block_start"||e.type==="message_delta"&&e.delta.stop_reason==="tool_use";o(this,Me,"f")&&s&&(o(this,Ze,"f").push({toolUse:o(this,Me,"f"),event:o(this,Pe,"f")}),w(this,Me,void 0)),t&&w(this,Me,t)},Rn=function(){if(this.errored||this.controller.signal.aborted)return;const e=Math.min(o(this,Pe,"f"),...o(this,Ye,"f").map(t=>t.handled));for(;o(this,Ze,"f")[0]&&o(this,Ze,"f")[0].event<=e;)o(this,kn,"f").call(this,o(this,Ze,"f").shift().toolUse)},An=function(e){const t=o(this,Ye,"f").indexOf(e);t>=0&&(o(this,Ye,"f").splice(t,1),o(this,_e,"m",Rn).call(this))},n})();function va(){let n,r;return{promise:new Promise((t,s)=>{n=t,r=s}),resolve:n,reject:r}}var D,et,Oe,N,K,V,Se,de,xe,$t,ee,he,tt,nt,Ce,ur,ka,dr,hr,It,En,Sa,fr,pr,xa,_r,Ra=(()=>{class n{constructor(e,t,s){D.add(this),this.client=e,et.set(this,!1),Oe.set(this,!1),N.set(this,void 0),K.set(this,void 0),V.set(this,void 0),Se.set(this,void 0),de.set(this,void 0),xe.set(this,void 0),$t.set(this,0),ee.set(this,{status:"idle"}),he.set(this,void 0),tt.set(this,null),nt.set(this,new Map),Ce.set(this,[]),Aa(t),hd(t),Ea(t),w(this,N,{params:{...t,messages:JSON.parse(JSON.stringify(Ta(t.messages)))}});const i=Ic(t.tools,t.messages);w(this,K,{...s,headers:f([$c("BetaToolRunner"),i.length?{[Xt]:i.join(", ")}:void 0,s?.headers])}),w(this,xe,va())}async*[(et=new WeakMap,Oe=new WeakMap,N=new WeakMap,K=new WeakMap,V=new WeakMap,Se=new WeakMap,de=new WeakMap,xe=new WeakMap,$t=new WeakMap,ee=new WeakMap,he=new WeakMap,tt=new WeakMap,nt=new WeakMap,Ce=new WeakMap,D=new WeakSet,Symbol.asyncIterator)](){var e;if(o(this,et,"f"))throw new S("Cannot iterate over a consumed stream");w(this,et,!0),w(this,Oe,!0),w(this,de,void 0);try{for(;;)try{if(o(this,N,"f").params.max_iterations&&o(this,$t,"f")>=o(this,N,"f").params.max_iterations)break;if(o(this,D,"m",xa).call(this),o(this,ee,"f").status==="scheduled"&&Ia(o(this,tt,"f"))!=="resume"){yield*o(this,D,"m",hr).call(this,o(this,ee,"f").config);continue}w(this,Oe,!1,"f"),w(this,de,void 0,"f"),w(this,$t,(e=o(this,$t,"f"),e++,e),"f"),w(this,V,void 0,"f");const{max_iterations:t,runToolsEagerly:s,...i}=o(this,N,"f").params;if(yield*o(this,D,"m",ur).call(this,i),o(this,Oe,"f"))w(this,tt,null,"f");else{const c=await o(this,V,"f"),u=Ia(c.stop_reason);w(this,tt,c.stop_reason,"f"),o(this,N,"f").params.messages.push({role:c.role,content:c.content});const{container:l}=o(this,N,"f").params;if(c.container&&(l==null?o(this,N,"f").params.container=c.container.id:typeof l=="object"&&l.id==null&&(o(this,N,"f").params.container={...l,id:c.container.id})),u==="stop"){yield*o(this,D,"m",fr).call(this);break}if(u==="resume")continue}const a=await o(this,D,"m",pr).call(this,o(this,N,"f").params.messages.at(-1));if(a)o(this,N,"f").params.messages.push(a);else if(!o(this,Oe,"f")){yield*o(this,D,"m",fr).call(this);break}}finally{o(this,Se,"f")?.abort(),w(this,Se,void 0,"f")}if(await o(this,D,"m",dr).call(this),!o(this,V,"f"))throw new S("ToolRunner concluded without a message from the server");o(this,xe,"f").resolve(await o(this,V,"f"))}catch(t){throw w(this,et,!1),o(this,xe,"f").promise.catch(()=>{}),o(this,xe,"f").reject(t),w(this,xe,va()),t}}setMessagesParams(e){const t=typeof e=="function"?e(o(this,N,"f").params):e;if(Aa(t),Ea(t),o(this,ee,"f").status!=="idle"&&gr(t),o(this,ee,"f").status==="in_flight"&&t.messages!==o(this,N,"f").params.messages)throw new S("Message params can't be changed while the conversation is being compacted, because the compaction response is about to replace them. Change them after this iteration instead.");o(this,N,"f").params=t,w(this,Oe,!0),w(this,de,void 0)}setRequestOptions(e){typeof e=="function"?w(this,K,e(o(this,K,"f"))):w(this,K,{...o(this,K,"f"),...e})}async generateToolResponse(e=o(this,K,"f").signal){const t=await o(this,V,"f")??this.params.messages.at(-1);return t?o(this,D,"m",pr).call(this,t,e):null}deferToolCall(e){const t=typeof e=="string"?e:e.id;o(this,he,"f")&&!o(this,he,"f").has(t)&&o(this,he,"f").set(t,{status:"held"})}get deferredToolCalls(){const e=o(this,Se,"f"),t=o(this,he,"f");return!(e instanceof ba)||!t?[]:e.toolCalls.filter(s=>t.get(s.id)?.status==="held")}done(){return o(this,xe,"f").promise}async runUntilDone(){if(!o(this,et,"f"))for await(const e of this);return this.done()}get params(){return o(this,N,"f").params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}compactBeforeNextTurn(e){o(this,ee,"f").status!=="in_flight"&&(gr(o(this,N,"f").params),w(this,ee,{status:"scheduled",config:e??{type:"summarize"}}))}addTools(...e){for(const t of e)"name"in t&&o(this,nt,"f").set(t.name,"run"in t?t:null),o(this,Ce,"f").push({type:"addition",tool:t})}removeTools(...e){for(const t of e){const s=typeof t=="string"?t:t.name;o(this,nt,"f").set(s,null),o(this,Ce,"f").push({type:"removal",name:s})}}then(e,t){return this.runUntilDone().then(e,t)}}return ur=async function*(e){await o(this,D,"m",dr).call(this),w(this,he,void 0),e={...e,...e.tools&&{tools:e.tools.map(jr)},messages:Ta(e.messages)},e.stream?(w(this,Se,o(this,N,"f").params.runToolsEagerly?o(this,D,"m",ka).call(this,e):this.client.beta.messages.stream({...e},o(this,K,"f"))),w(this,V,o(this,Se,"f").finalMessage()),o(this,V,"f").catch(()=>{}),yield o(this,Se,"f")):(w(this,V,this.client.beta.messages.create({...e,stream:!1},o(this,K,"f"))),yield o(this,V,"f"))},ka=function(e){const t=new Map;return w(this,he,t),ba.start(this.client.beta.messages,e,o(this,K,"f"),s=>{if(t.has(s.id))return;const i=jc(o(this,D,"m",It).call(this),o(this,D,"m",En).call(this),s,o(this,K,"f"));i.catch(()=>{}),t.set(s.id,{status:"started",result:i})})},dr=async function(){const e=[...o(this,he,"f")?.values()??[]].filter(t=>t.status==="started");await Promise.allSettled(e.map(t=>t.result))},hr=async function*(e){gr(o(this,N,"f").params);const{max_iterations:t,runToolsEagerly:s,...i}=o(this,N,"f").params,a=fd(i);w(this,ee,{status:"in_flight"}),w(this,de,void 0);const c=o(this,V,"f");try{yield*o(this,D,"m",ur).call(this,{...a,compaction:e});const u=await o(this,V,"f");u.content.some(l=>l.type==="compaction"&&l.content)?(o(this,D,"m",Sa).call(this),o(this,N,"f").params.messages=[{role:u.role,content:u.content}]):(O(this.client).warn("Compaction produced no summary; keeping the conversation as it is."),w(this,V,c,"f"))}finally{w(this,ee,{status:"idle"})}},It=function(){const e=new Map;for(const t of o(this,N,"f").params.tools)"run"in t&&e.set(t.name,t);for(const[t,s]of o(this,nt,"f"))s?e.set(t,s):e.delete(t);return e},En=function(){const e=new Set(o(this,D,"m",It).call(this).keys());for(const t of[...o(this,N,"f").params.messages,o(this,D,"m",_r).call(this)])if(typeof t.content!="string"){for(const s of t.content)if(t.role==="system")$a(s,e);else if(t.role==="assistant"&&s.type==="compaction")for(const i of s.tool_changes??[])$a(i,e)}return e},Sa=function(){const e=o(this,D,"m",En).call(this);for(const t of o(this,D,"m",It).call(this).keys())e.has(t)||o(this,nt,"f").set(t,null)},fr=async function*(){if(o(this,ee,"f").status!=="scheduled")return;const e=o(this,N,"f").params.messages.at(-1)?.content;if(Array.isArray(e)&&e.some(t=>t.type==="tool_use")){O(this.client).warn("The pending compaction was skipped because the last turn ended with tool calls that were not run. Call `compactBeforeNextTurn()` again if you continue the conversation."),w(this,ee,{status:"idle"});return}yield*o(this,D,"m",hr).call(this,o(this,ee,"f").config)},pr=async function(e,t=o(this,K,"f").signal){return o(this,de,"f")!==void 0?o(this,de,"f"):(w(this,de,pd(o(this,D,"m",It).call(this),o(this,D,"m",En).call(this),e,{...o(this,K,"f"),signal:t},o(this,he,"f"))),o(this,de,"f"))},xa=function(){o(this,tt,"f")==="pause_turn"||o(this,Ce,"f").length===0||(o(this,N,"f").params.messages.push(o(this,D,"m",_r).call(this)),w(this,Ce,[]))},_r=function(){const e=[];for(const t of o(this,Ce,"f")){if(t.type==="removal"){e.push({type:"tool_removal",tool:{type:"tool_reference",name:t.name}});continue}const s=jr(t.tool);e.push({type:"tool_addition",tool:{type:"tool_definition",definition:s}})}return{role:"system",content:e}},n})();function Aa(n){if("compaction"in n&&n.compaction!=null)throw new S("`compaction` cannot be set on a tool runner: every request in the loop would compact again. Call `runner.compactBeforeNextTurn()` when the conversation should be compacted instead.")}function hd(n){if("compactionControl"in n&&n.compactionControl!=null)throw new S("`compactionControl` has been removed from the tool runner. Use server-side compaction instead: call `runner.compactBeforeNextTurn()` when the conversation should be compacted.")}function Ea(n){if(n.runToolsEagerly&&!n.stream)throw new TypeError("`runToolsEagerly: true` needs `stream: true` in the tool runner's params, because a reply that isn't streamed arrives whole.")}function gr(n){if(n.context_management?.edits?.some(r=>r.type.startsWith("compact_")))throw new S("`compactBeforeNextTurn()` can't be used while `context_management` has a compaction edit, because the API doesn't accept a compaction block together with one. Remove the edit first.")}function fd(n){const{context_management:r,stop_sequences:e,output_format:t,...s}=n,i=({format:a,...c})=>c;return(s.tool_choice?.type==="any"||s.tool_choice?.type==="tool")&&delete s.tool_choice,s.output_config&&(s.output_config=i(s.output_config)),Array.isArray(s.fallbacks)&&(s.fallbacks=s.fallbacks.map(a=>a.output_config?{...a,output_config:i(a.output_config)}:a)),s}function jr(n){if(!("run"in n))return n;const r=yd;return{...Object.fromEntries(Object.entries(n).filter(([e])=>r.includes(e))),...it(n)&&{[Ee]:n[Ee]}}}function Ta(n){return n.map(r=>{if(r.role!=="system"||typeof r.content=="string")return r;const e=r.content.map(t=>t.type==="tool_addition"&&t.tool.type==="tool_definition"?{...t,tool:{...t.tool,definition:jr(t.tool.definition)}}:t);return{...r,content:e}})}async function pd(n,r,e,t,s){if(!e||e.role!=="assistant"||!e.content||typeof e.content=="string")return null;const i=e.content.filter(c=>c.type==="tool_use");return i.length===0?null:{role:"user",content:await Promise.all(i.map(c=>{const u=s?.get(c.id);if(u?.status==="started")return u.result;const l=jc(n,r,c,t);return s?.set(c.id,{status:"started",result:l}),l}))}}async function jc(n,r,e,t){const s=r.has(e.name)?n.get(e.name):void 0;if(!s)return _d(e);try{let i=e.input;"parse"in s&&s.parse&&(i=s.parse(i));const a=await s.run(i,{toolUse:e,toolUseBlock:e,signal:t?.signal});return{type:"tool_result",tool_use_id:e.id,content:a}}catch(i){return{type:"tool_result",tool_use_id:e.id,content:i instanceof cs?i.content:`Error: ${i instanceof Error?i.message:String(i)}`,is_error:!0}}}function _d(n){return{type:"tool_result",tool_use_id:n.id,content:`Error: Tool '${n.name}' not found`,is_error:!0}}function $a(n,r){switch(n.type){case"tool_removal":case"tool_addition":gd(n,r);break}}function gd(n,r){const e=md(n.tool);e!==void 0&&(n.type==="tool_removal"?r.delete(e):r.add(e))}function md(n){switch(n.type){case"tool_reference":return n.name;case"tool_definition":return"name"in n.definition?n.definition.name:void 0;default:return}}function Ia(n){if(n===null)return"stop";switch(n){case"tool_use":return"run_tools";case"pause_turn":case"compaction":return"resume";case"end_turn":case"stop_sequence":case"max_tokens":case"model_context_window_exceeded":case"refusal":return"stop";default:return"stop"}}const Pa={"claude-sonnet-4-5":"November 30th, 2026","claude-sonnet-4-5-20250929":"November 30th, 2026"},wd=["claude-mythos-preview","claude-opus-4-6"];var Ma=(()=>{class n extends v{constructor(){super(...arguments),this.batches=new _i(this._client)}create(e,t){const s=Oa(e),{betas:i,user_profile_id:a,workspace_id:c,...u}=s;u.model in Pa&&console.warn(`The model '${u.model}' is deprecated and will reach end-of-life on ${Pa[u.model]}
|
|
11
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),wd.includes(u.model)&&u.thinking&&u.thinking.type==="enabled"&&console.warn(`Using Claude with ${u.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let l=t?.timeout??this._client._options.timeout;if(!u.stream&&l==null){const d=Dc[u.model]??void 0;l=this._client.calculateNonstreamingTimeout(u.max_tokens,d)}const p=Pc(u.tools,u.messages);return this._client.post("/v1/messages?beta=true",{body:u,timeout:l??6e5,...t,headers:f([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...a!=null?{"anthropic-user-profile-id":a}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},p,t?.headers]),stream:s.stream??!1})}parse(e,t){return t={...t,headers:f([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},t?.headers])},this.create(e,t).then(s=>Hc(s,e,{logger:this._client.logger??console}))}stream(e,t){return zc.createMessage(this,e,t)}countTokens(e,t){const s=Oa(e),{betas:i,user_profile_id:a,workspace_id:c,...u}=s;return this._client.post("/v1/messages/count_tokens?beta=true",{body:u,...t,headers:f([{"anthropic-beta":[...i??[],"token-counting-2024-11-01"].toString(),...a!=null?{"anthropic-user-profile-id":a}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}toolRunner(e,t){return new Ra(this._client,e,t)}}return n.Batches=_i,n.BetaToolRunner=Ra,n.ToolError=cs,n})();function Oa(n){if(!n.output_format)return n;if(n.output_config?.format)throw new S("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");const{output_format:r,...e}=n;return{...e,output_config:{...n.output_config,format:r}}}const yd=["input_schema","name","allowed_callers","cache_control","defer_loading","description","eager_input_streaming","input_examples","strict","type","configs","display_height_px","display_width_px","display_number","enable_zoom","max_characters"];var Fr=(()=>{class n extends v{constructor(){super(...arguments),this.models=new zs(this._client),this.messages=new Ma(this._client),this.agents=new Gs(this._client),this.environments=new di(this._client),this.sessions=new ha(this._client),this.deployments=new Us(this._client),this.deploymentRuns=new Ds(this._client),this.vaults=new wa(this._client),this.memoryStores=new pi(this._client),this.files=new Ws(this._client),this.skills=new pa(this._client),this.webhooks=new Js(this._client),this.userProfiles=new js(this._client),this.dreams=new Hs(this._client),this.tunnels=new ga(this._client),this.organization=new oa(this._client)}}return n.Models=zs,n.Messages=Ma,n.Agents=Gs,n.Environments=di,n.Sessions=ha,n.Deployments=Us,n.DeploymentRuns=Ds,n.Vaults=wa,n.MemoryStores=pi,n.Files=Ws,n.Skills=pa,n.Webhooks=Js,n.UserProfiles=js,n.Dreams=Hs,n.Tunnels=ga,n.Organization=oa,n})();class Ca extends v{create(r,e){const{betas:t,workspace_id:s,...i}=r;return this._client.post("/v1/complete",{body:i,timeout:this._client._options.timeout??6e5,...e,headers:f([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0,...s!=null?{"anthropic-workspace-id":s}:void 0},e?.headers]),stream:r.stream??!1})}}class La extends v{list(r={},e){const{workspace_id:t,...s}=r??{};return this._client.getAPIList("/v1/files",A,{query:s,...e,headers:f([{...t!=null?{"anthropic-workspace-id":t}:void 0},e?.headers])})}delete(r,e={},t){const{workspace_id:s}=e??{};return this._client.delete(h`/v1/files/${r}`,{...t,headers:f([{...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}download(r,e={},t){const{workspace_id:s}=e??{};return this._client.get(h`/v1/files/${r}/content`,{...t,headers:f([{Accept:"application/binary",...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers]),__binaryResponse:!0})}retrieveMetadata(r,e={},t){const{workspace_id:s}=e??{};return this._client.get(h`/v1/files/${r}`,{...t,headers:f([{...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}upload(r,e){const{workspace_id:t,...s}=r;return this._client.post("/v1/files",me({body:s,...e,headers:f([{...t!=null?{"anthropic-workspace-id":t}:void 0},Mc(s.file),e?.headers])},this._client))}}function Fc(n){return n?.output_config?.format}function Na(n,r,e){const t=Fc(r);return!r||!("parse"in(t??{}))?{...n,content:n.content.map(s=>s.type==="text"?Object.defineProperty({...s},"parsed_output",{value:null,enumerable:!1}):s),parsed_output:null}:qc(n,r)}function qc(n,r,e){let t=null;const s=n.content.map(i=>{if(i.type==="text"){const a=bd(r,i.text);return t===null&&(t=a),Object.defineProperty({...i},"parsed_output",{value:a,enumerable:!1})}return i});return{...n,content:s,parsed_output:t}}function bd(n,r){const e=Fc(n);if(e?.type!=="json_schema")return null;try{return"parse"in e?e.parse(r):JSON.parse(r)}catch(t){throw new S(`Failed to parse structured output: ${t}`)}}var se,Re,rt,Pt,Tn,Mt,Ot,$n,Ct,fe,Lt,In,Pn,Le,Mn,On,Cn,Nt,mr,Ba,wr,yr,br,vr,Da;function kr(n){return n.type==="tool_use"||n.type==="server_tool_use"}var vd=(()=>{class n{constructor(e,t){se.add(this),this.messages=[],this.receivedMessages=[],Re.set(this,void 0),rt.set(this,null),this.controller=new AbortController,Pt.set(this,void 0),Tn.set(this,()=>{}),Mt.set(this,()=>{}),Ot.set(this,void 0),$n.set(this,()=>{}),Ct.set(this,()=>{}),fe.set(this,{}),Lt.set(this,!1),In.set(this,!1),Pn.set(this,!1),Le.set(this,!1),Mn.set(this,void 0),On.set(this,void 0),Cn.set(this,void 0),Nt.set(this,void 0),wr.set(this,s=>{if(w(this,In,!0),lt(s)&&(s=new oe),s instanceof oe)return w(this,Pn,!0),this._emit("abort",s);if(s instanceof S)return this._emit("error",s);if(s instanceof Error){const i=new S(s.message);return i.cause=s,this._emit("error",i)}return this._emit("error",new S(String(s)))}),w(this,Pt,new Promise((s,i)=>{w(this,Tn,s,"f"),w(this,Mt,i,"f")})),w(this,Ot,new Promise((s,i)=>{w(this,$n,s,"f"),w(this,Ct,i,"f")})),o(this,Pt,"f").catch(()=>{}),o(this,Ot,"f").catch(()=>{}),w(this,rt,e),w(this,Nt,t?.logger??console)}get response(){return o(this,Mn,"f")}get request_id(){return o(this,On,"f")}get workspace_id(){return o(this,Cn,"f")}async withResponse(){w(this,Le,!0);const e=await o(this,Pt,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id"),workspace_id:e.headers.get("anthropic-workspace-id")}}static fromReadableStream(e){const t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,s,{logger:i}={}){const a=new n(t,{logger:i});for(const c of t.messages)a._addMessageParam(c);return w(a,rt,{...t,stream:!0}),a._run(()=>a._createMessage(e,{...t,stream:!0},{...s,headers:{...s?.headers,[os]:"stream"}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},o(this,wr,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,s){const i=s?.signal;let a;i&&(i.aborted&&this.controller.abort(),a=this.controller.abort.bind(this.controller),i.addEventListener("abort",a));try{o(this,se,"m",yr).call(this);const{response:c,data:u}=await e.create({...t,stream:!0},{...s,signal:this.controller.signal}).withResponse();this._connected(c);for await(const l of u)o(this,se,"m",br).call(this,l);if(u.controller.signal?.aborted)throw new oe;o(this,se,"m",vr).call(this)}finally{i&&a&&i.removeEventListener("abort",a)}}_connected(e){this.ended||(w(this,Mn,e),w(this,On,e?.headers.get("request-id")),w(this,Cn,e?.headers.get("anthropic-workspace-id")),o(this,Tn,"f").call(this,e),this._emit("connect"))}get ended(){return o(this,Lt,"f")}get errored(){return o(this,In,"f")}get aborted(){return o(this,Pn,"f")}abort(){this.controller.abort()}on(e,t){return(o(this,fe,"f")[e]||(o(this,fe,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=o(this,fe,"f")[e];if(!s)return this;const i=s.findIndex(a=>a.listener===t);return i>=0&&s.splice(i,1),this}once(e,t){return(o(this,fe,"f")[e]||(o(this,fe,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{w(this,Le,!0),e!=="error"&&this.once("error",s),this.once(e,t)})}async done(){w(this,Le,!0),await o(this,Ot,"f")}get currentMessage(){return o(this,Re,"f")}async finalMessage(){return await this.done(),o(this,se,"m",mr).call(this)}async finalText(){return await this.done(),o(this,se,"m",Ba).call(this)}_emit(e,...t){if(o(this,Lt,"f"))return;e==="end"&&(w(this,Lt,!0),o(this,$n,"f").call(this));const s=o(this,fe,"f")[e];if(s&&(o(this,fe,"f")[e]=s.filter(i=>!i.once),s.forEach(({listener:i})=>i(...t))),e==="abort"){const i=t[0];!o(this,Le,"f")&&!s?.length&&Promise.reject(i),o(this,Mt,"f").call(this,i),o(this,Ct,"f").call(this,i),this._emit("end");return}if(e==="error"){const i=t[0];!o(this,Le,"f")&&!s?.length&&Promise.reject(i),o(this,Mt,"f").call(this,i),o(this,Ct,"f").call(this,i),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",o(this,se,"m",mr).call(this))}async _fromReadableStream(e,t){const s=t?.signal;let i;s&&(s.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),s.addEventListener("abort",i));try{o(this,se,"m",yr).call(this),this._connected(null);const a=dt.fromReadableStream(e,this.controller);for await(const c of a)o(this,se,"m",br).call(this,c);if(a.controller.signal?.aborted)throw new oe;o(this,se,"m",vr).call(this)}finally{s&&i&&s.removeEventListener("abort",i)}}[(Re=new WeakMap,rt=new WeakMap,Pt=new WeakMap,Tn=new WeakMap,Mt=new WeakMap,Ot=new WeakMap,$n=new WeakMap,Ct=new WeakMap,fe=new WeakMap,Lt=new WeakMap,In=new WeakMap,Pn=new WeakMap,Le=new WeakMap,Mn=new WeakMap,On=new WeakMap,Cn=new WeakMap,Nt=new WeakMap,wr=new WeakMap,se=new WeakSet,mr=function(){if(this.receivedMessages.length===0)throw new S("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Ba=function(){if(this.receivedMessages.length===0)throw new S("stream ended without producing a Message with role=assistant");const t=this.receivedMessages.at(-1).content.filter(s=>s.type==="text").map(s=>s.text);if(t.length===0)throw new S("stream ended without producing a content block with type=text");return t.join(" ")},yr=function(){this.ended||w(this,Re,void 0)},br=function(t){if(this.ended)return;const s=o(this,se,"m",Da).call(this,t);switch(this._emit("streamEvent",t,s),t.type){case"content_block_delta":{const i=s.content.at(-1);switch(t.delta.type){case"text_delta":{i.type==="text"&&this._emit("text",t.delta.text,i.text||"");break}case"citations_delta":{i.type==="text"&&this._emit("citation",t.delta.citation,i.citations??[]);break}case"input_json_delta":{kr(i)&&o(this,fe,"f").inputJson?.length&&this._emit("inputJson",t.delta.partial_json,i.input);break}case"thinking_delta":{i.type==="thinking"&&this._emit("thinking",t.delta.thinking,i.thinking);break}case"signature_delta":{i.type==="thinking"&&this._emit("signature",i.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(s),this._addMessage(Na(s,o(this,rt,"f"),{logger:o(this,Nt,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",s.content.at(-1));break}case"message_start":{w(this,Re,s);break}}},vr=function(){if(this.ended)throw new S("stream has ended, this shouldn't happen");const t=o(this,Re,"f");if(!t)throw new S("request ended without sending any chunks");return w(this,Re,void 0),Na(t,o(this,rt,"f"),{logger:o(this,Nt,"f")})},Da=function(t){let s=o(this,Re,"f");if(t.type==="message_start"){if(s)throw new S(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!s)throw new S(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return s;case"message_delta":return s.stop_reason=t.delta.stop_reason,s.stop_sequence=t.delta.stop_sequence,s.stop_details=t.delta.stop_details,s.usage.output_tokens=t.usage.output_tokens,t.delta.container!=null&&(s.container=t.delta.container),t.usage.input_tokens!=null&&(s.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(s.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(s.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(s.usage.server_tool_use=t.usage.server_tool_use),t.usage.output_tokens_details!=null&&(s.usage.output_tokens_details=t.usage.output_tokens_details),s;case"content_block_start":return s.content.push({...t.content_block}),s;case"content_block_delta":{const i=s.content.at(t.index);switch(t.delta.type){case"text_delta":{i?.type==="text"&&(s.content[t.index]={...i,text:(i.text||"")+t.delta.text});break}case"citations_delta":{i?.type==="text"&&(s.content[t.index]={...i,citations:[...i.citations??[],t.delta.citation]});break}case"input_json_delta":{if(i&&kr(i)){const a=(i[ct]||"")+t.delta.partial_json;s.content[t.index]=Wc(i,a)}break}case"thinking_delta":{i?.type==="thinking"&&(s.content[t.index]={...i,thinking:i.thinking+t.delta.thinking});break}case"signature_delta":{i?.type==="thinking"&&(s.content[t.index]={...i,signature:t.delta.signature});break}default:t.delta}return s}case"content_block_stop":{const i=s.content.at(t.index);return i&&kr(i)&&ct in i&&Object.defineProperty(i,"input",{value:i.input,enumerable:!0,configurable:!0,writable:!0}),s}}},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("streamEvent",i=>{const a=t.shift();a?a.resolve(i):e.push(i)}),this.on("end",()=>{s=!0;for(const i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{s=!0;for(const a of t)a.reject(i);t.length=0}),this.on("error",i=>{s=!0;for(const a of t)a.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((a,c)=>t.push({resolve:a,reject:c})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new dt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}return n})();class Ua extends v{create(r,e){const{user_profile_id:t,workspace_id:s,...i}=r;return this._client.post("/v1/messages/batches",{body:i,...e,headers:f([{...t!=null?{"anthropic-user-profile-id":t}:void 0,...s!=null?{"anthropic-workspace-id":s}:void 0},e?.headers])})}retrieve(r,e={},t){const{workspace_id:s}=e??{};return this._client.get(h`/v1/messages/batches/${r}`,{...t,headers:f([{...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}list(r={},e){const{workspace_id:t,...s}=r??{};return this._client.getAPIList("/v1/messages/batches",X,{query:s,...e,headers:f([{...t!=null?{"anthropic-workspace-id":t}:void 0},e?.headers])})}delete(r,e={},t){const{workspace_id:s}=e??{};return this._client.delete(h`/v1/messages/batches/${r}`,{...t,headers:f([{...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}cancel(r,e={},t){const{workspace_id:s}=e??{};return this._client.post(h`/v1/messages/batches/${r}/cancel`,{...t,headers:f([{...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}async results(r,e={},t){const s=await this.retrieve(r,e,t);if(!s.results_url)throw new S(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);const{workspace_id:i}=e??{};return this._client.get(s.results_url,{...t,headers:f([{Accept:"application/binary",...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((a,c)=>Bc.fromResponse(c.response,c.controller))}}var qr=(()=>{class n extends v{constructor(){super(...arguments),this.batches=new Ua(this._client)}create(e,t){const{user_profile_id:s,workspace_id:i,...a}=e;a.model in Ha&&console.warn(`The model '${a.model}' is deprecated and will reach end-of-life on ${Ha[a.model]}
|
|
12
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),kd.includes(a.model)&&a.thinking&&a.thinking.type==="enabled"&&console.warn(`Using Claude with ${a.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let c=t?.timeout??this._client._options.timeout;if(!a.stream&&c==null){const l=Dc[a.model]??void 0;c=this._client.calculateNonstreamingTimeout(a.max_tokens,l)}const u=Pc(a.tools,a.messages);return this._client.post("/v1/messages",{body:a,timeout:c??6e5,...t,headers:f([{...s!=null?{"anthropic-user-profile-id":s}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},u,t?.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then(s=>qc(s,e,{logger:this._client.logger??console}))}stream(e,t){return vd.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){const{user_profile_id:s,workspace_id:i,...a}=e;return this._client.post("/v1/messages/count_tokens",{body:a,...t,headers:f([{...s!=null?{"anthropic-user-profile-id":s}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}}return n.Batches=Ua,n})();const Ha={"claude-sonnet-4-5":"November 30th, 2026","claude-sonnet-4-5-20250929":"November 30th, 2026"},kd=["claude-mythos-preview","claude-opus-4-6"];class Wa extends v{retrieve(r,e={},t){const{betas:s,workspace_id:i}=e??{};return this._client.get(h`/v1/models/${r}`,{...t,headers:f([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}list(r={},e){const{betas:t,workspace_id:s,...i}=r??{};return this._client.getAPIList("/v1/models",X,{query:i,...e,headers:f([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0,...s!=null?{"anthropic-workspace-id":s}:void 0},e?.headers])})}}class za extends v{retrieve(r,e){return this._client.get(h`/v1/organizations/api_keys/${r}`,e)}update(r,e,t){return this._client.post(h`/v1/organizations/api_keys/${r}`,{body:e,...t})}list(r={},e){return this._client.getAPIList("/v1/organizations/api_keys",X,{query:r,...e})}}class ja extends v{retrieve(r){return this._client.get("/v1/organizations/compliance_settings",r)}update(r,e){return this._client.post("/v1/organizations/compliance_settings",{body:r,...e})}}class Fa extends v{create(r,e){return this._client.post("/v1/organizations/external_keys",{body:r,...e})}retrieve(r,e){return this._client.get(h`/v1/organizations/external_keys/${r}`,e)}update(r,e,t){return this._client.post(h`/v1/organizations/external_keys/${r}`,{body:e,...t})}list(r={},e){return this._client.getAPIList("/v1/organizations/external_keys",A,{query:r,...e})}delete(r,e){return this._client.delete(h`/v1/organizations/external_keys/${r}`,e)}validate(r,e){return this._client.post(h`/v1/organizations/external_keys/${r}/validate`,e)}}class qa extends v{create(r,e){return this._client.post("/v1/organizations/invites",{body:r,...e})}retrieve(r,e){return this._client.get(h`/v1/organizations/invites/${r}`,e)}list(r={},e){return this._client.getAPIList("/v1/organizations/invites",X,{query:r,...e})}delete(r,e){return this._client.delete(h`/v1/organizations/invites/${r}`,e)}}let Ka=class extends v{list(r={},e){return this._client.getAPIList("/v1/organizations/rate_limits",A,{query:r,...e})}};class Va extends v{retrieve(r,e){return this._client.get(h`/v1/organizations/users/${r}`,e)}update(r,e,t){return this._client.post(h`/v1/organizations/users/${r}`,{body:e,...t})}list(r={},e){return this._client.getAPIList("/v1/organizations/users",X,{query:r,...e})}remove(r,e){return this._client.delete(h`/v1/organizations/users/${r}`,e)}}class Ja extends v{create(r,e){return this._client.post("/v1/organizations/federation_issuers",{body:r,...e})}retrieve(r,e){return this._client.get(h`/v1/organizations/federation_issuers/${r}`,e)}update(r,e,t){return this._client.post(h`/v1/organizations/federation_issuers/${r}`,{body:e,...t})}list(r={},e){return this._client.getAPIList("/v1/organizations/federation_issuers",A,{query:r,...e})}archive(r,e){return this._client.post(h`/v1/organizations/federation_issuers/${r}/archive`,e)}}let Xa=class extends v{list(r,e={},t){return this._client.getAPIList(h`/v1/organizations/federation_rules/${r}/workspaces`,A,{query:e,...t})}add(r,e,t){return this._client.post(h`/v1/organizations/federation_rules/${r}/workspaces`,{body:e,...t})}remove(r,e,t){const{federation_rule_id:s}=e;return this._client.delete(h`/v1/organizations/federation_rules/${s}/workspaces/${r}`,t)}};var Ga=(()=>{class n extends v{constructor(){super(...arguments),this.workspaces=new Xa(this._client)}create(e,t){return this._client.post("/v1/organizations/federation_rules",{body:e,...t})}retrieve(e,t){return this._client.get(h`/v1/organizations/federation_rules/${e}`,t)}update(e,t,s){return this._client.post(h`/v1/organizations/federation_rules/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/federation_rules",A,{query:e,...t})}archive(e,t){return this._client.post(h`/v1/organizations/federation_rules/${e}/archive`,t)}}return n.Workspaces=Xa,n})(),Qa=(()=>{class n extends v{constructor(){super(...arguments),this.issuers=new Ja(this._client),this.rules=new Ga(this._client)}}return n.Issuers=Ja,n.Rules=Ga,n})();let Ya=class extends v{list(r,e={},t){return this._client.getAPIList(h`/v1/organizations/service_accounts/${r}/workspaces`,A,{query:e,...t})}add(r,e,t){return this._client.post(h`/v1/organizations/service_accounts/${r}/workspaces`,{body:e,...t})}remove(r,e,t){const{service_account_id:s}=e;return this._client.delete(h`/v1/organizations/service_accounts/${s}/workspaces/${r}`,t)}};var Za=(()=>{class n extends v{constructor(){super(...arguments),this.workspaces=new Ya(this._client)}create(e,t){return this._client.post("/v1/organizations/service_accounts",{body:e,...t})}retrieve(e,t){return this._client.get(h`/v1/organizations/service_accounts/${e}`,t)}update(e,t,s){return this._client.post(h`/v1/organizations/service_accounts/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/service_accounts",A,{query:e,...t})}archive(e,t){return this._client.post(h`/v1/organizations/service_accounts/${e}/archive`,t)}}return n.Workspaces=Ya,n})();class eo extends v{retrieve(r,e,t){const{workspace_id:s}=e;return this._client.get(h`/v1/organizations/workspaces/${s}/members/${r}`,t)}update(r,e,t){const{workspace_id:s,...i}=e;return this._client.post(h`/v1/organizations/workspaces/${s}/members/${r}`,{body:i,...t})}list(r,e={},t){return this._client.getAPIList(h`/v1/organizations/workspaces/${r}/members`,X,{query:e,...t})}add(r,e,t){return this._client.post(h`/v1/organizations/workspaces/${r}/members`,{body:e,...t})}remove(r,e,t){const{workspace_id:s}=e;return this._client.delete(h`/v1/organizations/workspaces/${s}/members/${r}`,t)}}class to extends v{list(r,e={},t){return this._client.getAPIList(h`/v1/organizations/workspaces/${r}/rate_limits`,A,{query:e,...t})}}class no extends v{retrieve(r,e,t){const{workspace_id:s}=e;return this._client.get(h`/v1/organizations/workspaces/${s}/service_accounts/${r}`,t)}update(r,e,t){const{workspace_id:s,...i}=e;return this._client.post(h`/v1/organizations/workspaces/${s}/service_accounts/${r}`,{body:i,...t})}list(r,e={},t){return this._client.getAPIList(h`/v1/organizations/workspaces/${r}/service_accounts`,A,{query:e,...t})}add(r,e,t){return this._client.post(h`/v1/organizations/workspaces/${r}/service_accounts`,{body:e,...t})}remove(r,e,t){const{workspace_id:s}=e;return this._client.delete(h`/v1/organizations/workspaces/${s}/service_accounts/${r}`,t)}}var ro=(()=>{class n extends v{constructor(){super(...arguments),this.rateLimits=new to(this._client),this.members=new eo(this._client),this.serviceAccounts=new no(this._client)}create(e,t){return this._client.post("/v1/organizations/workspaces",{body:e,...t})}retrieve(e,t){return this._client.get(h`/v1/organizations/workspaces/${e}`,t)}update(e,t,s){return this._client.post(h`/v1/organizations/workspaces/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/workspaces",X,{query:e,...t})}archive(e,t){return this._client.post(h`/v1/organizations/workspaces/${e}/archive`,t)}}return n.RateLimits=to,n.Members=eo,n.ServiceAccounts=no,n})(),so=(()=>{class n extends v{constructor(){super(...arguments),this.apiKeys=new za(this._client),this.externalKeys=new Fa(this._client),this.federation=new Qa(this._client),this.invites=new qa(this._client),this.serviceAccounts=new Za(this._client),this.users=new Va(this._client),this.workspaces=new ro(this._client),this.rateLimits=new Ka(this._client),this.complianceSettings=new ja(this._client)}retrieve(e){return this._client.get("/v1/organizations/me",e)}}return n.APIKeys=za,n.ExternalKeys=Fa,n.Federation=Qa,n.Invites=qa,n.ServiceAccounts=Za,n.Users=Va,n.Workspaces=ro,n.RateLimits=Ka,n.ComplianceSettings=ja,n})();class io extends v{create(r,e,t){const{workspace_id:s,...i}=e;return this._client.post(h`/v1/skills/${r}/versions`,me({body:i,...t,headers:f([{...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])},this._client,!1))}retrieve(r,e,t){const{skill_id:s,workspace_id:i}=e;return this._client.get(h`/v1/skills/${s}/versions/${r}`,{...t,headers:f([{...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}list(r,e={},t){const{workspace_id:s,...i}=e??{};return this._client.getAPIList(h`/v1/skills/${r}/versions`,A,{query:i,...t,headers:f([{...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(r,e,t){const{skill_id:s,workspace_id:i}=e;return this._client.delete(h`/v1/skills/${s}/versions/${r}`,{...t,headers:f([{...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}}var ao=(()=>{class n extends v{constructor(){super(...arguments),this.versions=new io(this._client)}create(e,t){const{workspace_id:s,...i}=e;return this._client.post("/v1/skills",me({body:i,...t,headers:f([{...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])},this._client,!1))}retrieve(e,t={},s){const{workspace_id:i}=t??{};return this._client.get(h`/v1/skills/${e}`,{...s,headers:f([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers])})}list(e={},t){const{workspace_id:s,...i}=e??{};return this._client.getAPIList("/v1/skills",A,{query:i,...t,headers:f([{...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(e,t={},s){const{workspace_id:i}=t??{};return this._client.delete(h`/v1/skills/${e}`,{...s,headers:f([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers])})}}return n.Versions=io,n})(),Sr,xr,Ln,oo;const Sd="\\n\\nHuman:",xd="\\n\\nAssistant:";var Kc=(()=>{class n{get credentials(){return this._authState.provider}constructor({baseURL:e=P("ANTHROPIC_BASE_URL"),apiKey:t,authToken:s,webhookKey:i=P("ANTHROPIC_WEBHOOK_SIGNING_KEY")??null,...a}={}){if(Sr.add(this),this._requestAuthFlags=new WeakMap,Ln.set(this,void 0),t===void 0&&(t=a.profile!=null?null:P("ANTHROPIC_API_KEY")??null),s===void 0&&(s=a.profile!=null?null:P("ANTHROPIC_AUTH_TOKEN")??null),a.profile!=null&&(a.credentials!=null||a.config!=null))throw new TypeError("Pass at most one of `profile`, `credentials`, or `config`.");const c={apiKey:t,authToken:s,webhookKey:i,...a,baseURL:e||"https://api.anthropic.com"};if(!c.dangerouslyAllowBrowser&&ml())throw new S(`It looks like you're running in a browser-like environment.
|
|
13
|
+
|
|
14
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
15
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
16
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
17
|
+
|
|
18
|
+
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
19
|
+
`);this.baseURL=c.baseURL,this._baseURLIsExplicit=a.__baseURLIsExplicit??!!e,this.timeout=c.timeout??xr.DEFAULT_TIMEOUT,this.logger=c.logger??console,this.logLevel=Vn,this.logLevel=Nr(c.logLevel,"ClientOptions.logLevel",O(this))??Nr(P("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",O(this))??Vn,this.fetchOptions=c.fetchOptions,this.maxRetries=Gn("maxRetries",c.maxRetries??2),this.fetch=c.fetch??xl(),w(this,Ln,Al),this.middleware=[...c.middleware??[]];const u=P("ANTHROPIC_CUSTOM_HEADERS");if(u){const p={};for(const d of u.split(`
|
|
20
|
+
`)){const g=d.indexOf(":");g>=0&&(p[d.substring(0,g).trim()]=d.substring(g+1).trim())}c.defaultHeaders={...p,...c.defaultHeaders}}const l=a.__auth;if(delete c.__auth,delete c.__baseURLIsExplicit,this._options=c,this.apiKey=typeof t=="string"?t:null,this.authToken=s,this.webhookKey=i,l)this._authState=l,!this._baseURLIsExplicit&&l.baseURL&&(this.baseURL=l.baseURL);else if(this._authState={provider:null,tokenCache:null,resolution:null,error:null,extraHeaders:{}},this.apiKey==null&&this.authToken==null){const p=c.credentials??null;if(p)this._authState.provider=p,this._authState.tokenCache=this._makeTokenCache(p);else if(c.config!=null){const d=yc(c.config,this._credentialResolverOptions());this._authState.provider=d.provider,this._authState.tokenCache=this._makeTokenCache(d.provider),this._authState.extraHeaders=d.extraHeaders,this._applyCredentialBaseURL(d.baseURL)}else c.profile!=null?this._authState.resolution=this._resolveDefaultCredentials(c.profile):this._shouldResolveDefaultCredentials()&&(this._authState.resolution=this._resolveDefaultCredentials())}}_shouldResolveDefaultCredentials(){return!0}_applyCredentialBaseURL(e){if(!e)return;const t=e.replace(/\/+$/,"");this._authState.baseURL=t,this._baseURLIsExplicit||(this.baseURL=t)}_credentialResolverOptions(){return{baseURL:this.baseURL,fetch:this._credentialsFetch(),userAgent:this.getUserAgent(),onCacheWriteError:e=>{O(this).debug("credential cache write failed (best-effort)",e)},onSafetyWarning:e=>{O(this).warn(e)}}}_credentialsFetch(){return Cs(this.fetch,this.middleware,void 0,this)}_makeTokenCache(e){return new Wl(e,t=>{O(this).debug("advisory token refresh failed; serving cached token",t)})}withOptions(e){const t="credentials"in e||"config"in e||"profile"in e,s="apiKey"in e||"authToken"in e||t,i={...this._options,...this._baseURLIsExplicit?{baseURL:this.baseURL}:{},maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,middleware:this.middleware,apiKey:this.apiKey,authToken:this.authToken,webhookKey:this.webhookKey,credentials:this.credentials,...t?{credentials:void 0,config:void 0,profile:void 0}:{},...e,__auth:s?void 0:this._authState,__baseURLIsExplicit:"baseURL"in e?!0:this._baseURLIsExplicit};return new this.constructor(i)}async _resolveDefaultCredentials(e){try{const t=await tu(this._credentialResolverOptions(),e);if(t)this._authState.provider=t.provider,this._authState.tokenCache=this._makeTokenCache(t.provider),this._authState.extraHeaders=t.extraHeaders,this._applyCredentialBaseURL(t.baseURL);else if(e!=null)throw new S(`Profile "${e}" could not be resolved (no <config_dir>/configs/${e}.json found).`)}catch(t){this._authState.error=t}finally{this._authState.resolution=null}}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.get("x-api-key")||e.get("authorization"))){if(this._authState.error)throw this._authState.error;if(!(this._authState.tokenCache||this._authState.resolution)&&!(this.apiKey&&e.get("x-api-key"))&&!t.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!t.has("authorization"))throw new Error('Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}}_authFlags(e){let t=this._requestAuthFlags.get(e);return t||(t={usedTokenCache:!1,didRefreshFor401:!1},this._requestAuthFlags.set(e,t)),t}async authHeaders(e){if(this._authState.resolution&&await this._authState.resolution,!this._authState.error){if(this._authState.tokenCache&&this.apiKey==null){const t=await this._authState.tokenCache.getToken();return this._authFlags(e).usedTokenCache=!0,f([{Authorization:`Bearer ${t}`}])}return f([await this.apiKeyAuth(e),await this.bearerAuth(e)])}}async apiKeyAuth(e){if(this.apiKey!=null)return f([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return f([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Ol(e)}getUserAgent(){return`Anthropic/JS ${ge}`}makeStatusError(e,t,s,i){return z.generate(e,t,s,i)}buildURL(e,t,s){const i=!o(this,Sr,"m",oo).call(this)&&s||this.baseURL,a=_l(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),c=this.defaultQuery(),u=Object.fromEntries(a.searchParams);return(!ys(c)||!ys(u))&&(t={...u,...c,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(a.search=this.stringifyQuery(t)),a.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new S("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:s}){if(this._authState.tokenCache&&this.apiKey==null){const i=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(const[c,u]of Object.entries(this._authState.extraHeaders))i.has(c)||i.set(c,u);const a=i.get("anthropic-beta")?.split(",").map(c=>c.trim());a?.includes(Kn)||i.set("anthropic-beta",[...a??[],Kn].join(",")),e.headers=i}}backendMiddleware(){return[]}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,s){return this.request(Promise.resolve(s).then(i=>({method:e,path:t,...i})))}request(e,t=null){return new Sc(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){const i=await e;let a=Gn("maxRetries",i.maxRetries??this.maxRetries);this.isStreamBody(i.body)&&(a=0),t==null&&(t=a,this._requestAuthFlags.delete(i)),await this.prepareOptions(i);const{req:c,url:u,timeout:l}=await this.buildRequest(i,{retryCount:a-t}),p="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=s===void 0?"":`, retryOf: ${s}`,g=Date.now();if(i.signal?.aborted)throw new oe;const _=new AbortController,m=await this.fetchWithTimeout(u,c,l,_,i,{requestLogID:p,retryOfRequestLogID:s}).catch(jn),y=Date.now();if(m instanceof globalThis.Error){De(_);const b=`retrying, ${t} attempts remaining`;if(i.signal?.aborted)throw new oe;const k=lt(m)||/timed? ?out/i.test(String(m)+("cause"in m?String(m.cause):"")),R=this.middleware.length>0||!!i.middleware?.length||this.backendMiddleware().length>0;if(R&&!k&&!cu(m))throw O(this).info(`[${p}] middleware error (not retryable)`),Ae(O(this),`[${p}] middleware error (not retryable)`,{retryOfRequestLogID:s,url:u,durationMs:y-g,message:m.message}),m;if(t)return O(this).info(`[${p}] connection ${k?"timed out":"failed"} - ${b}`),Ae(O(this),`[${p}] connection ${k?"timed out":"failed"} (${b})`,{retryOfRequestLogID:s,url:u,durationMs:y-g,message:m.message}),this.retryRequest(i,t,s??p);throw O(this).info(`[${p}] connection ${k?"timed out":"failed"} - error; no more retries left`),Ae(O(this),`[${p}] connection ${k?"timed out":"failed"} (error; no more retries left)`,{retryOfRequestLogID:s,url:u,durationMs:y-g,message:m.message}),k?new gs:R&&!kc(m)?m:new ut({cause:m})}const x=[...m.headers.entries()].filter(([b])=>b==="request-id"||b==="anthropic-workspace-id").map(([b,k])=>", "+b+": "+JSON.stringify(k)).join(""),E=`[${p}${d}${x}] ${c.method} ${u} ${m.ok?"succeeded":"failed"} with status ${m.status} in ${y-g}ms`;if(!m.ok){const b=await this.shouldRetry(m,i);if(t&&b){const M=`retrying, ${t} attempts remaining`;return await Rl(m.body),De(_),O(this).info(`${E} - ${M}`),Ae(O(this),`[${p}] response error (${M})`,{retryOfRequestLogID:s,url:m.url,status:m.status,headers:m.headers,durationMs:y-g}),this.retryRequest(i,t,s??p,m.headers)}const k=b?"error; no more retries left":"error; not retryable";O(this).info(`${E} - ${k}`);const R=await m.text().catch(M=>jn(M).message),T=tc(R),$=T?void 0:R;throw Ae(O(this),`[${p}] response error (${k})`,{retryOfRequestLogID:s,url:m.url,status:m.status,headers:m.headers,message:$,durationMs:Date.now()-g}),De(_),this.makeStatusError(m.status,T,$,m.headers)}return O(this).info(E),Ae(O(this),`[${p}] response start`,{retryOfRequestLogID:s,url:m.url,status:m.status,headers:m.headers,durationMs:y-g}),Sl(m.body??m,_),{response:m,options:i,controller:_,requestLogID:p,retryOfRequestLogID:s,startTime:g}}getAPIList(e,t,s){return this.requestAPIList(t,s&&"then"in s?s.then(i=>({method:"get",path:e,...i})):{method:"get",path:e,...s})}requestAPIList(e,t){const s=this.makeRequest(t,null,void 0);return new du(this,s,e)}async fetchWithTimeout(e,t,s,i,a,c){const{signal:u,method:l,...p}=t||{},d=this._makeAbort(i);u&&(u.addEventListener("abort",d,{once:!0}),kl(i,u,d));const g=globalThis.ReadableStream&&p.body instanceof globalThis.ReadableStream||typeof p.body=="object"&&p.body!==null&&Symbol.asyncIterator in p.body,_={signal:i.signal,...g?{duplex:"half"}:{},method:"GET",...p};l&&(_.method=l.toUpperCase());const m=this.fetch,y=async(R,T)=>{const $=setTimeout(d,s);try{return await m.call(void 0,R,T)}finally{clearTimeout($)}},x=a===void 0?y:(async(R,T={})=>{const $=typeof R=="string"?R:R instanceof URL?R.href:R.url;return T.headers=T.headers instanceof Headers?T.headers:new Headers(T.headers),await this.prepareRequest(T,{url:$,options:a}),c&&Ae(O(this),`[${c.requestLogID}] sending request`,{retryOfRequestLogID:c.retryOfRequestLogID,method:T.method,url:$,options:a,headers:T.headers}),y(R,T)}),E=a?.middleware,b=this.backendMiddleware(),k=E?.length||b.length?[...this.middleware,...E??[],...b]:this.middleware;return await Cs(x,k,a,this)(e,_)}async shouldRetry(e,t){const s=this._authFlags(t);if(e.status===401&&this._authState.tokenCache&&s.usedTokenCache&&!s.didRefreshFor401)return s.didRefreshFor401=!0,this._authState.tokenCache.invalidate(),!0;const i=e.headers.get("x-should-retry");return i==="true"?!0:i==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,s,i){let a;const c=i?.get("retry-after-ms");if(c){const l=parseFloat(c);Number.isNaN(l)||(a=l)}const u=i?.get("retry-after");if(u&&!a){const l=parseFloat(u);Number.isNaN(l)?a=Date.parse(u)-Date.now():a=l*1e3}if(a===void 0||!(a>0&&a<=2**31-1)){const l=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,l)}return await Be(a,e.signal??void 0),this.makeRequest(e,t-1,s)}calculateDefaultRetryTimeoutMillis(e,t){const a=t-e,c=Math.min(.5*Math.pow(2,a),8),u=1-Math.random()*.25;return c*u*1e3}calculateNonstreamingTimeout(e,t){if(36e5*e/128e3>6e5||t!=null&&e>t)throw new S("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:t=0}={}){const s={...e},{method:i,path:a,query:c,defaultBaseURL:u}=s;this._authState.resolution&&await this._authState.resolution,!this._baseURLIsExplicit&&this._authState.baseURL&&this.baseURL!==this._authState.baseURL&&(this.baseURL=this._authState.baseURL);const l=this.buildURL(a,c,u);"timeout"in s&&Gn("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:p,body:d}=this.buildBody({options:s}),g=await this.buildHeaders({options:e,method:i,bodyHeaders:p,retryCount:t,timeout:s.timeout});return{req:{method:i,headers:g,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...s.fetchOptions??{}},url:l,timeout:s.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:s,retryCount:i,timeout:a}){const c=f([{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),"X-Stainless-Timeout":String(Math.trunc(a/1e3)),...es(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(c),c.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=f([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:this.isStreamBody(e)?{bodyHeaders:void 0,body:sc(e)}:typeof e=="object"&&s.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:o(this,Ln,"f").call(this,{body:e,headers:s})}isStreamBody(e){return globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?!0:typeof e=="object"&&e!==null&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")}}return xr=n,Ln=new WeakMap,Sr=new WeakSet,oo=function(){return this.baseURL!=="https://api.anthropic.com"},n.Anthropic=xr,n.DEFAULT_TIMEOUT=6e5,n.AnthropicError=S,n.APIError=z,n.APIConnectionError=ut,n.APIConnectionTimeoutError=gs,n.APIUserAbortError=oe,n.NotFoundError=Jo,n.ConflictError=Xo,n.RateLimitError=Qo,n.BadRequestError=qo,n.AuthenticationError=Ko,n.InternalServerError=Yo,n.PermissionDeniedError=Vo,n.UnprocessableEntityError=Go,n.toFile=mu,n.HUMAN_PROMPT=Sd,n.AI_PROMPT=xd,n})(),Kr=(()=>{class n extends Kc{constructor(){super(...arguments),this.completions=new Ca(this),this.messages=new qr(this),this.models=new Wa(this),this.files=new La(this),this.skills=new ao(this),this.organization=new so(this),this.beta=new Fr(this)}}return n.Completions=Ca,n.Messages=qr,n.Models=Wa,n.Files=La,n.Skills=ao,n.Organization=so,n.Beta=Fr,n})(),Rr={};/*! *****************************************************************************
|
|
21
|
+
Copyright (c) Microsoft Corporation.
|
|
22
|
+
|
|
23
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
24
|
+
purpose with or without fee is hereby granted.
|
|
25
|
+
|
|
26
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
27
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
28
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
29
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
30
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
31
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
32
|
+
PERFORMANCE OF THIS SOFTWARE.
|
|
33
|
+
***************************************************************************** */var Vr=function(n,r){return Vr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var s in t)t.hasOwnProperty(s)&&(e[s]=t[s])},Vr(n,r)};function Rd(n,r){Vr(n,r);function e(){this.constructor=n}n.prototype=r===null?Object.create(r):(e.prototype=r.prototype,new e)}var Jr=function(){return Jr=Object.assign||function(r){for(var e,t=1,s=arguments.length;t<s;t++){e=arguments[t];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=e[i])}return r},Jr.apply(this,arguments)};function Ad(n,r){var e={};for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&r.indexOf(t)<0&&(e[t]=n[t]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,t=Object.getOwnPropertySymbols(n);s<t.length;s++)r.indexOf(t[s])<0&&Object.prototype.propertyIsEnumerable.call(n,t[s])&&(e[t[s]]=n[t[s]]);return e}function Ed(n,r,e,t){var s=arguments.length,i=s<3?r:t===null?t=Object.getOwnPropertyDescriptor(r,e):t,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,r,e,t);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(i=(s<3?a(i):s>3?a(r,e,i):a(r,e))||i);return s>3&&i&&Object.defineProperty(r,e,i),i}function Td(n,r){return function(e,t){r(e,t,n)}}function $d(n,r){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,r)}function Id(n,r,e,t){function s(i){return i instanceof e?i:new e(function(a){a(i)})}return new(e||(e=Promise))(function(i,a){function c(p){try{l(t.next(p))}catch(d){a(d)}}function u(p){try{l(t.throw(p))}catch(d){a(d)}}function l(p){p.done?i(p.value):s(p.value).then(c,u)}l((t=t.apply(n,r||[])).next())})}function Pd(n,r){var e={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},t,s,i,a;return a={next:c(0),throw:c(1),return:c(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function c(l){return function(p){return u([l,p])}}function u(l){if(t)throw new TypeError("Generator is already executing.");for(;e;)try{if(t=1,s&&(i=l[0]&2?s.return:l[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,l[1])).done)return i;switch(s=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return e.label++,{value:l[1],done:!1};case 5:e.label++,s=l[1],l=[0];continue;case 7:l=e.ops.pop(),e.trys.pop();continue;default:if(i=e.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){e=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){e.label=l[1];break}if(l[0]===6&&e.label<i[1]){e.label=i[1],i=l;break}if(i&&e.label<i[2]){e.label=i[2],e.ops.push(l);break}i[2]&&e.ops.pop(),e.trys.pop();continue}l=r.call(n,e)}catch(p){l=[6,p],s=0}finally{t=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function Md(n,r,e,t){t===void 0&&(t=e),n[t]=r[e]}function Od(n,r){for(var e in n)e!=="default"&&!r.hasOwnProperty(e)&&(r[e]=n[e])}function Xr(n){var r=typeof Symbol=="function"&&Symbol.iterator,e=r&&n[r],t=0;if(e)return e.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&t>=n.length&&(n=void 0),{value:n&&n[t++],done:!n}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")}function Vc(n,r){var e=typeof Symbol=="function"&&n[Symbol.iterator];if(!e)return n;var t=e.call(n),s,i=[],a;try{for(;(r===void 0||r-- >0)&&!(s=t.next()).done;)i.push(s.value)}catch(c){a={error:c}}finally{try{s&&!s.done&&(e=t.return)&&e.call(t)}finally{if(a)throw a.error}}return i}function Cd(){for(var n=[],r=0;r<arguments.length;r++)n=n.concat(Vc(arguments[r]));return n}function Ld(){for(var n=0,r=0,e=arguments.length;r<e;r++)n+=arguments[r].length;for(var t=Array(n),s=0,r=0;r<e;r++)for(var i=arguments[r],a=0,c=i.length;a<c;a++,s++)t[s]=i[a];return t}function Jt(n){return this instanceof Jt?(this.v=n,this):new Jt(n)}function Nd(n,r,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e.apply(n,r||[]),s,i=[];return s={},a("next"),a("throw"),a("return"),s[Symbol.asyncIterator]=function(){return this},s;function a(g){t[g]&&(s[g]=function(_){return new Promise(function(m,y){i.push([g,_,m,y])>1||c(g,_)})})}function c(g,_){try{u(t[g](_))}catch(m){d(i[0][3],m)}}function u(g){g.value instanceof Jt?Promise.resolve(g.value.v).then(l,p):d(i[0][2],g)}function l(g){c("next",g)}function p(g){c("throw",g)}function d(g,_){g(_),i.shift(),i.length&&c(i[0][0],i[0][1])}}function Bd(n){var r,e;return r={},t("next"),t("throw",function(s){throw s}),t("return"),r[Symbol.iterator]=function(){return this},r;function t(s,i){r[s]=n[s]?function(a){return(e=!e)?{value:Jt(n[s](a)),done:s==="return"}:i?i(a):a}:i}}function Dd(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n[Symbol.asyncIterator],e;return r?r.call(n):(n=typeof Xr=="function"?Xr(n):n[Symbol.iterator](),e={},t("next"),t("throw"),t("return"),e[Symbol.asyncIterator]=function(){return this},e);function t(i){e[i]=n[i]&&function(a){return new Promise(function(c,u){a=n[i](a),s(c,u,a.done,a.value)})}}function s(i,a,c,u){Promise.resolve(u).then(function(l){i({value:l,done:c})},a)}}function Ud(n,r){return Object.defineProperty?Object.defineProperty(n,"raw",{value:r}):n.raw=r,n}function Hd(n){if(n&&n.__esModule)return n;var r={};if(n!=null)for(var e in n)Object.hasOwnProperty.call(n,e)&&(r[e]=n[e]);return r.default=n,r}function Wd(n){return n&&n.__esModule?n:{default:n}}function zd(n,r){if(!r.has(n))throw new TypeError("attempted to get private field on non-instance");return r.get(n)}function jd(n,r,e){if(!r.has(n))throw new TypeError("attempted to set private field on non-instance");return r.set(n,e),e}const Fd=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return Jr},__asyncDelegator:Bd,__asyncGenerator:Nd,__asyncValues:Dd,__await:Jt,__awaiter:Id,__classPrivateFieldGet:zd,__classPrivateFieldSet:jd,__createBinding:Md,__decorate:Ed,__exportStar:Od,__extends:Rd,__generator:Pd,__importDefault:Wd,__importStar:Hd,__makeTemplateObject:Ud,__metadata:$d,__param:Td,__read:Vc,__rest:Ad,__spread:Cd,__spreadArrays:Ld,__values:Xr},Symbol.toStringTag,{value:"Module"})),Jc=Fo(Fd);var Bt={},te={},co;function Xc(){return co||(co=1,Object.defineProperty(te,"__esModule",{value:!0}),te.MAX_HASHABLE_LENGTH=te.INIT=te.KEY=te.DIGEST_LENGTH=te.BLOCK_SIZE=void 0,te.BLOCK_SIZE=64,te.DIGEST_LENGTH=32,te.KEY=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),te.INIT=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],te.MAX_HASHABLE_LENGTH=Math.pow(2,53)-1),te}var Dt={},lo;function qd(){if(lo)return Dt;lo=1,Object.defineProperty(Dt,"__esModule",{value:!0}),Dt.RawSha256=void 0;var n=Xc(),r=(function(){function e(){this.state=Int32Array.from(n.INIT),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}return e.prototype.update=function(t){if(this.finished)throw new Error("Attempted to update an already finished hash.");var s=0,i=t.byteLength;if(this.bytesHashed+=i,this.bytesHashed*8>n.MAX_HASHABLE_LENGTH)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;i>0;)this.buffer[this.bufferLength++]=t[s++],i--,this.bufferLength===n.BLOCK_SIZE&&(this.hashBuffer(),this.bufferLength=0)},e.prototype.digest=function(){if(!this.finished){var t=this.bytesHashed*8,s=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),i=this.bufferLength;if(s.setUint8(this.bufferLength++,128),i%n.BLOCK_SIZE>=n.BLOCK_SIZE-8){for(var a=this.bufferLength;a<n.BLOCK_SIZE;a++)s.setUint8(a,0);this.hashBuffer(),this.bufferLength=0}for(var a=this.bufferLength;a<n.BLOCK_SIZE-8;a++)s.setUint8(a,0);s.setUint32(n.BLOCK_SIZE-8,Math.floor(t/4294967296),!0),s.setUint32(n.BLOCK_SIZE-4,t),this.hashBuffer(),this.finished=!0}for(var c=new Uint8Array(n.DIGEST_LENGTH),a=0;a<8;a++)c[a*4]=this.state[a]>>>24&255,c[a*4+1]=this.state[a]>>>16&255,c[a*4+2]=this.state[a]>>>8&255,c[a*4+3]=this.state[a]>>>0&255;return c},e.prototype.hashBuffer=function(){for(var t=this,s=t.buffer,i=t.state,a=i[0],c=i[1],u=i[2],l=i[3],p=i[4],d=i[5],g=i[6],_=i[7],m=0;m<n.BLOCK_SIZE;m++){if(m<16)this.temp[m]=(s[m*4]&255)<<24|(s[m*4+1]&255)<<16|(s[m*4+2]&255)<<8|s[m*4+3]&255;else{var y=this.temp[m-2],x=(y>>>17|y<<15)^(y>>>19|y<<13)^y>>>10;y=this.temp[m-15];var E=(y>>>7|y<<25)^(y>>>18|y<<14)^y>>>3;this.temp[m]=(x+this.temp[m-7]|0)+(E+this.temp[m-16]|0)}var b=(((p>>>6|p<<26)^(p>>>11|p<<21)^(p>>>25|p<<7))+(p&d^~p&g)|0)+(_+(n.KEY[m]+this.temp[m]|0)|0)|0,k=((a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10))+(a&c^a&u^c&u)|0;_=g,g=d,d=p,p=l+b|0,l=u,u=c,c=a,a=b+k|0}i[0]+=a,i[1]+=c,i[2]+=u,i[3]+=l,i[4]+=p,i[5]+=d,i[6]+=g,i[7]+=_},e})();return Dt.RawSha256=r,Dt}var Ar={},Ut={};const Kd=n=>{const r=[];for(let e=0,t=n.length;e<t;e++){const s=n.charCodeAt(e);if(s<128)r.push(s);else if(s<2048)r.push(s>>6|192,s&63|128);else if(e+1<n.length&&(s&64512)===55296&&(n.charCodeAt(e+1)&64512)===56320){const i=65536+((s&1023)<<10)+(n.charCodeAt(++e)&1023);r.push(i>>18|240,i>>12&63|128,i>>6&63|128,i&63|128)}else r.push(s>>12|224,s>>6&63|128,s&63|128)}return Uint8Array.from(r)},Vd=n=>{let r="";for(let e=0,t=n.length;e<t;e++){const s=n[e];if(s<128)r+=String.fromCharCode(s);else if(192<=s&&s<224){const i=n[++e];r+=String.fromCharCode((s&31)<<6|i&63)}else if(240<=s&&s<365){const a="%"+[s,n[++e],n[++e],n[++e]].map(c=>c.toString(16)).join("%");r+=decodeURIComponent(a)}else r+=String.fromCharCode((s&15)<<12|(n[++e]&63)<<6|n[++e]&63)}return r};function Jd(n){return new TextEncoder().encode(n)}function Xd(n){return new TextDecoder("utf-8").decode(n)}const Gd=n=>typeof TextEncoder=="function"?Jd(n):Kd(n),Qd=n=>typeof TextDecoder=="function"?Xd(n):Vd(n),Yd=Object.freeze(Object.defineProperty({__proto__:null,fromUtf8:Gd,toUtf8:Qd},Symbol.toStringTag,{value:"Module"})),Zd=Fo(Yd);var uo;function eh(){if(uo)return Ut;uo=1,Object.defineProperty(Ut,"__esModule",{value:!0}),Ut.convertToBuffer=void 0;var n=Zd,r=typeof Buffer<"u"&&Buffer.from?function(t){return Buffer.from(t,"utf8")}:n.fromUtf8;function e(t){return t instanceof Uint8Array?t:typeof t=="string"?r(t):ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(t)}return Ut.convertToBuffer=e,Ut}var Ht={},ho;function th(){if(ho)return Ht;ho=1,Object.defineProperty(Ht,"__esModule",{value:!0}),Ht.isEmptyData=void 0;function n(r){return typeof r=="string"?r.length===0:r.byteLength===0}return Ht.isEmptyData=n,Ht}var Wt={},fo;function nh(){if(fo)return Wt;fo=1,Object.defineProperty(Wt,"__esModule",{value:!0}),Wt.numToUint8=void 0;function n(r){return new Uint8Array([(r&4278190080)>>24,(r&16711680)>>16,(r&65280)>>8,r&255])}return Wt.numToUint8=n,Wt}var zt={},po;function rh(){if(po)return zt;po=1,Object.defineProperty(zt,"__esModule",{value:!0}),zt.uint32ArrayFrom=void 0;function n(r){if(!Uint32Array.from){for(var e=new Uint32Array(r.length),t=0;t<r.length;)e[t]=r[t],t+=1;return e}return Uint32Array.from(r)}return zt.uint32ArrayFrom=n,zt}var _o;function sh(){return _o||(_o=1,(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.uint32ArrayFrom=n.numToUint8=n.isEmptyData=n.convertToBuffer=void 0;var r=eh();Object.defineProperty(n,"convertToBuffer",{enumerable:!0,get:function(){return r.convertToBuffer}});var e=th();Object.defineProperty(n,"isEmptyData",{enumerable:!0,get:function(){return e.isEmptyData}});var t=nh();Object.defineProperty(n,"numToUint8",{enumerable:!0,get:function(){return t.numToUint8}});var s=rh();Object.defineProperty(n,"uint32ArrayFrom",{enumerable:!0,get:function(){return s.uint32ArrayFrom}})})(Ar)),Ar}var go;function ih(){if(go)return Bt;go=1,Object.defineProperty(Bt,"__esModule",{value:!0}),Bt.Sha256=void 0;var n=Jc,r=Xc(),e=qd(),t=sh(),s=(function(){function a(c){this.secret=c,this.hash=new e.RawSha256,this.reset()}return a.prototype.update=function(c){if(!((0,t.isEmptyData)(c)||this.error))try{this.hash.update((0,t.convertToBuffer)(c))}catch(u){this.error=u}},a.prototype.digestSync=function(){if(this.error)throw this.error;return this.outer?(this.outer.finished||this.outer.update(this.hash.digest()),this.outer.digest()):this.hash.digest()},a.prototype.digest=function(){return n.__awaiter(this,void 0,void 0,function(){return n.__generator(this,function(c){return[2,this.digestSync()]})})},a.prototype.reset=function(){if(this.hash=new e.RawSha256,this.secret){this.outer=new e.RawSha256;var c=i(this.secret),u=new Uint8Array(r.BLOCK_SIZE);u.set(c);for(var l=0;l<r.BLOCK_SIZE;l++)c[l]^=54,u[l]^=92;this.hash.update(c),this.outer.update(u);for(var l=0;l<c.byteLength;l++)c[l]=0}},a})();Bt.Sha256=s;function i(a){var c=(0,t.convertToBuffer)(a);if(c.byteLength>r.BLOCK_SIZE){var u=new e.RawSha256;u.update(c),c=u.digest()}var l=new Uint8Array(r.BLOCK_SIZE);return l.set(c),l}return Bt}var mo;function ah(){return mo||(mo=1,(function(n){Object.defineProperty(n,"__esModule",{value:!0});var r=Jc;r.__exportStar(ih(),n)})(Rr)),Rr}var oh=ah();class wo{statusCode;reason;headers;body;constructor(r){this.statusCode=r.statusCode,this.reason=r.reason,this.headers=r.headers||{},this.body=r.body}static isInstance(r){if(!r)return!1;const e=r;return typeof e.statusCode=="number"&&typeof e.headers=="object"}}const Er=n=>encodeURIComponent(n).replace(/[!'()*]/g,ch),ch=n=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`;function lh(n){const r=[];for(let e of Object.keys(n).sort()){const t=n[e];if(e=Er(e),Array.isArray(t))for(let s=0,i=t.length;s<i;s++)r.push(`${e}=${Er(t[s])}`);else{let s=e;(t||typeof t=="string")&&(s+=`=${Er(t)}`),r.push(s)}}return r.join("&")}function yo(n,r){return new Request(n,r)}function uh(n=0){return new Promise((r,e)=>{n&&setTimeout(()=>{const t=new Error(`Request did not complete within ${n} ms`);t.name="TimeoutError",e(t)},n)})}const Tr={supported:void 0};class ls{config;configProvider;static create(r){return typeof r?.handle=="function"?r:new ls(r)}constructor(r){typeof r=="function"?this.configProvider=r().then(e=>e||{}):(this.config=r??{},this.configProvider=Promise.resolve(this.config)),Tr.supported===void 0&&(Tr.supported=typeof Request<"u"&&"keepalive"in yo("https://[::1]"))}destroy(){}async handle(r,{abortSignal:e,requestTimeout:t}={}){this.config||(this.config=await this.configProvider);const s=t??this.config.requestTimeout,i=this.config.keepAlive===!0,a=this.config.credentials;if(e?.aborted){const b=bo(e);return Promise.reject(b)}let c=r.path;const u=lh(r.query||{});u&&(c+=`?${u}`),r.fragment&&(c+=`#${r.fragment}`);let l="";if(r.username!=null||r.password!=null){const b=r.username??"",k=r.password??"";l=`${b}:${k}@`}const{port:p,method:d}=r,g=`${r.protocol}//${l}${r.hostname}${p?`:${p}`:""}${c}`,_=d==="GET"||d==="HEAD"?void 0:r.body,m={body:_,headers:new Headers(r.headers),method:d,credentials:a};this.config?.cache&&(m.cache=this.config.cache),_&&(m.duplex="half"),typeof AbortController<"u"&&(m.signal=e),Tr.supported&&(m.keepalive=i),typeof this.config.requestInit=="function"&&Object.assign(m,this.config.requestInit(r));let y=()=>{};const x=yo(g,m),E=[fetch(x).then(b=>{const k=b.headers,R={};for(const $ of k.entries())R[$[0]]=$[1];return b.body!=null?{response:new wo({headers:R,reason:b.statusText,statusCode:b.status,body:b.body})}:b.blob().then($=>({response:new wo({headers:R,reason:b.statusText,statusCode:b.status,body:$})}))}),uh(s)];return e&&E.push(new Promise((b,k)=>{const R=()=>{const T=bo(e);k(T)};if(typeof e.addEventListener=="function"){const T=e;T.addEventListener("abort",R,{once:!0}),y=()=>T.removeEventListener("abort",R)}else e.onabort=R})),Promise.race(E).finally(y)}updateHttpClientConfig(r,e){this.config=void 0,this.configProvider=this.configProvider.then(t=>(t[r]=e,t))}httpHandlerConfigs(){return this.config??{}}}function bo(n){const r=n&&typeof n=="object"&&"reason"in n?n.reason:void 0;if(r){if(r instanceof Error){const s=new Error("Request aborted");return s.name="AbortError",s.cause=r,s}const t=new Error(String(r));return t.name="AbortError",t}const e=new Error("Request aborted");return e.name="AbortError",e}var vo;(function(n){n.HEADER="header",n.QUERY="query"})(vo||(vo={}));var ko;(function(n){n.HEADER="header",n.QUERY="query"})(ko||(ko={}));var So;(function(n){n.HTTP="http",n.HTTPS="https"})(So||(So={}));var xo;(function(n){n.MD5="md5",n.CRC32="crc32",n.CRC32C="crc32c",n.SHA1="sha1",n.SHA256="sha256"})(xo||(xo={}));var Ro;(function(n){n[n.HEADER=0]="HEADER",n[n.TRAILER=1]="TRAILER"})(Ro||(Ro={}));var Ao;(function(n){n.PROFILE="profile",n.SSO_SESSION="sso-session",n.SERVICES="services"})(Ao||(Ao={}));var Eo;(function(n){n.HTTP_0_9="http/0.9",n.HTTP_1_0="http/1.0",n.TDS_8_0="tds/8.0"})(Eo||(Eo={}));class us{constructor(r){this.method=r.method||"GET",this.hostname=r.hostname||"localhost",this.port=r.port,this.query=r.query||{},this.headers=r.headers||{},this.body=r.body,this.protocol=r.protocol?r.protocol.slice(-1)!==":"?`${r.protocol}:`:r.protocol:"https:",this.path=r.path?r.path.charAt(0)!=="/"?`/${r.path}`:r.path:"/",this.username=r.username,this.password=r.password,this.fragment=r.fragment}static isInstance(r){if(!r)return!1;const e=r;return"method"in e&&"protocol"in e&&"hostname"in e&&"path"in e&&typeof e.query=="object"&&typeof e.headers=="object"}clone(){const r=new us({...this,headers:{...this.headers}});return r.query&&(r.query=dh(r.query)),r}}function dh(n){return Object.keys(n).reduce((r,e)=>{const t=n[e];return{...r,[e]:Array.isArray(t)?[...t]:t}},{})}const Gc={},Gr={};for(let n=0;n<256;n++){let r=n.toString(16).toLowerCase();r.length===1&&(r=`0${r}`),Gc[n]=r,Gr[r]=n}function hh(n){if(n.length%2!==0)throw new Error("Hex encoded strings must have an even number length");const r=new Uint8Array(n.length/2);for(let e=0;e<n.length;e+=2){const t=n.slice(e,e+2).toLowerCase();if(t in Gr)r[e/2]=Gr[t];else throw new Error(`Cannot decode unrecognized sequence ${t} as hexadecimal`)}return r}function Ne(n){let r="";for(let e=0;e<n.byteLength;e++)r+=Gc[n[e]];return r}var To;(function(n){n.HEADER="header",n.QUERY="query"})(To||(To={}));var $o;(function(n){n.HEADER="header",n.QUERY="query"})($o||($o={}));var Io;(function(n){n.HTTP="http",n.HTTPS="https"})(Io||(Io={}));var Po;(function(n){n.MD5="md5",n.CRC32="crc32",n.CRC32C="crc32c",n.SHA1="sha1",n.SHA256="sha256"})(Po||(Po={}));var Mo;(function(n){n[n.HEADER=0]="HEADER",n[n.TRAILER=1]="TRAILER"})(Mo||(Mo={}));var Oo;(function(n){n.PROFILE="profile",n.SSO_SESSION="sso-session",n.SERVICES="services"})(Oo||(Oo={}));var Co;(function(n){n.HTTP_0_9="http/0.9",n.HTTP_1_0="http/1.0",n.TDS_8_0="tds/8.0"})(Co||(Co={}));const Lo=n=>{if(typeof n=="function")return n;const r=Promise.resolve(n);return()=>r},jt=n=>encodeURIComponent(n).replace(/[!'()*]/g,fh),fh=n=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`,Qr=n=>new TextEncoder().encode(n),Kt=n=>typeof n=="string"?Qr(n):ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(n),ph="X-Amz-Algorithm",_h="X-Amz-Credential",Qc="X-Amz-Date",gh="X-Amz-SignedHeaders",mh="X-Amz-Expires",Yc="X-Amz-Signature",Zc="X-Amz-Security-Token",el="authorization",tl=Qc.toLowerCase(),wh="date",yh=[el,tl,wh],bh=Yc.toLowerCase(),Yr="x-amz-content-sha256",vh=Zc.toLowerCase(),kh={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0},Sh=/^proxy-/,xh=/^sec-/,$r="AWS4-HMAC-SHA256",Rh="AWS4-HMAC-SHA256-PAYLOAD",Ah="UNSIGNED-PAYLOAD",Eh=50,nl="aws4_request",Th=3600*24*7,Nn={},Ir=[],Pr=(n,r,e)=>`${n}/${r}/${e}/${nl}`,$h=async(n,r,e,t,s)=>{const i=await No(n,r.secretAccessKey,r.accessKeyId),a=`${e}:${t}:${s}:${Ne(i)}:${r.sessionToken}`;if(a in Nn)return Nn[a];for(Ir.push(a);Ir.length>Eh;)delete Nn[Ir.shift()];let c=`AWS4${r.secretAccessKey}`;for(const u of[e,t,s,nl])c=await No(n,c,u);return Nn[a]=c},No=(n,r,e)=>{const t=new n(r);return t.update(Kt(e)),t.digest()},Bo=({headers:n},r,e)=>{const t={};for(const s of Object.keys(n).sort()){if(n[s]==null)continue;const i=s.toLowerCase();(i in kh||r?.has(i)||Sh.test(i)||xh.test(i))&&(!e||e&&!e.has(i))||(t[i]=n[s].trim().replace(/\s+/g," "))}return t},Ih=({query:n={}})=>{const r=[],e={};for(const t of Object.keys(n).sort()){if(t.toLowerCase()===bh)continue;r.push(t);const s=n[t];typeof s=="string"?e[t]=`${jt(t)}=${jt(s)}`:Array.isArray(s)&&(e[t]=s.slice(0).reduce((i,a)=>i.concat([`${jt(t)}=${jt(a)}`]),[]).sort().join("&"))}return r.map(t=>e[t]).filter(t=>t).join("&")},Ph=n=>typeof ArrayBuffer=="function"&&n instanceof ArrayBuffer||Object.prototype.toString.call(n)==="[object ArrayBuffer]",Mr=async({headers:n,body:r},e)=>{for(const t of Object.keys(n))if(t.toLowerCase()===Yr)return n[t];if(r==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if(typeof r=="string"||ArrayBuffer.isView(r)||Ph(r)){const t=new e;return t.update(Kt(r)),Ne(await t.digest())}return Ah};class Mh{format(r){const e=[];for(const i of Object.keys(r)){const a=Qr(i);e.push(Uint8Array.from([a.byteLength]),a,this.formatHeaderValue(r[i]))}const t=new Uint8Array(e.reduce((i,a)=>i+a.byteLength,0));let s=0;for(const i of e)t.set(i,s),s+=i.byteLength;return t}formatHeaderValue(r){switch(r.type){case"boolean":return Uint8Array.from([r.value?0:1]);case"byte":return Uint8Array.from([2,r.value]);case"short":const e=new DataView(new ArrayBuffer(3));return e.setUint8(0,3),e.setInt16(1,r.value,!1),new Uint8Array(e.buffer);case"integer":const t=new DataView(new ArrayBuffer(5));return t.setUint8(0,4),t.setInt32(1,r.value,!1),new Uint8Array(t.buffer);case"long":const s=new Uint8Array(9);return s[0]=5,s.set(r.value.bytes,1),s;case"binary":const i=new DataView(new ArrayBuffer(3+r.value.byteLength));i.setUint8(0,6),i.setUint16(1,r.value.byteLength,!1);const a=new Uint8Array(i.buffer);return a.set(r.value,3),a;case"string":const c=Qr(r.value),u=new DataView(new ArrayBuffer(3+c.byteLength));u.setUint8(0,7),u.setUint16(1,c.byteLength,!1);const l=new Uint8Array(u.buffer);return l.set(c,3),l;case"timestamp":const p=new Uint8Array(9);return p[0]=8,p.set(ds.fromNumber(r.value.valueOf()).bytes,1),p;case"uuid":if(!Oh.test(r.value))throw new Error(`Invalid UUID received: ${r.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(hh(r.value.replace(/\-/g,"")),1),d}}}var Do;(function(n){n[n.boolTrue=0]="boolTrue",n[n.boolFalse=1]="boolFalse",n[n.byte=2]="byte",n[n.short=3]="short",n[n.integer=4]="integer",n[n.long=5]="long",n[n.byteArray=6]="byteArray",n[n.string=7]="string",n[n.timestamp=8]="timestamp",n[n.uuid=9]="uuid"})(Do||(Do={}));const Oh=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class ds{constructor(r){if(this.bytes=r,r.byteLength!==8)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(r){if(r>9223372036854776e3||r<-9223372036854776e3)throw new Error(`${r} is too large (or, if negative, too small) to represent as an Int64`);const e=new Uint8Array(8);for(let t=7,s=Math.abs(Math.round(r));t>-1&&s>0;t--,s/=256)e[t]=s;return r<0&&Uo(e),new ds(e)}valueOf(){const r=this.bytes.slice(0),e=r[0]&128;return e&&Uo(r),parseInt(Ne(r),16)*(e?-1:1)}toString(){return String(this.valueOf())}}function Uo(n){for(let r=0;r<8;r++)n[r]^=255;for(let r=7;r>-1&&(n[r]++,n[r]===0);r--);}const Ch=(n,r)=>{n=n.toLowerCase();for(const e of Object.keys(r))if(n===e.toLowerCase())return!0;return!1},rl=({headers:n,query:r,...e})=>({...e,headers:{...n},query:r?Lh(r):void 0}),Lh=n=>Object.keys(n).reduce((r,e)=>{const t=n[e];return{...r,[e]:Array.isArray(t)?[...t]:t}},{}),Nh=(n,r={})=>{const{headers:e,query:t={}}=typeof n.clone=="function"?n.clone():rl(n);for(const s of Object.keys(e)){const i=s.toLowerCase();i.slice(0,6)==="x-amz-"&&!r.unhoistableHeaders?.has(i)&&(t[s]=e[s],delete e[s])}return{...n,headers:e,query:t}},Ho=n=>{n=typeof n.clone=="function"?n.clone():rl(n);for(const r of Object.keys(n.headers))yh.indexOf(r.toLowerCase())>-1&&delete n.headers[r];return n},Bh=n=>Dh(n).toISOString().replace(/\.\d{3}Z$/,"Z"),Dh=n=>typeof n=="number"?new Date(n*1e3):typeof n=="string"?Number(n)?new Date(Number(n)*1e3):new Date(n):n;class Uh{constructor({applyChecksum:r,credentials:e,region:t,service:s,sha256:i,uriEscapePath:a=!0}){this.headerFormatter=new Mh,this.service=s,this.sha256=i,this.uriEscapePath=a,this.applyChecksum=typeof r=="boolean"?r:!0,this.regionProvider=Lo(t),this.credentialProvider=Lo(e)}async presign(r,e={}){const{signingDate:t=new Date,expiresIn:s=3600,unsignableHeaders:i,unhoistableHeaders:a,signableHeaders:c,signingRegion:u,signingService:l}=e,p=await this.credentialProvider();this.validateResolvedCredentials(p);const d=u??await this.regionProvider(),{longDate:g,shortDate:_}=Bn(t);if(s>Th)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");const m=Pr(_,d,l??this.service),y=Nh(Ho(r),{unhoistableHeaders:a});p.sessionToken&&(y.query[Zc]=p.sessionToken),y.query[ph]=$r,y.query[_h]=`${p.accessKeyId}/${m}`,y.query[Qc]=g,y.query[mh]=s.toString(10);const x=Bo(y,i,c);return y.query[gh]=Wo(x),y.query[Yc]=await this.getSignature(g,m,this.getSigningKey(p,d,_,l),this.createCanonicalRequest(y,x,await Mr(r,this.sha256))),y}async sign(r,e){return typeof r=="string"?this.signString(r,e):r.headers&&r.payload?this.signEvent(r,e):r.message?this.signMessage(r,e):this.signRequest(r,e)}async signEvent({headers:r,payload:e},{signingDate:t=new Date,priorSignature:s,signingRegion:i,signingService:a}){const c=i??await this.regionProvider(),{shortDate:u,longDate:l}=Bn(t),p=Pr(u,c,a??this.service),d=await Mr({headers:{},body:e},this.sha256),g=new this.sha256;g.update(r);const _=Ne(await g.digest()),m=[Rh,l,p,s,_,d].join(`
|
|
34
|
+
`);return this.signString(m,{signingDate:t,signingRegion:c,signingService:a})}async signMessage(r,{signingDate:e=new Date,signingRegion:t,signingService:s}){return this.signEvent({headers:this.headerFormatter.format(r.message.headers),payload:r.message.body},{signingDate:e,signingRegion:t,signingService:s,priorSignature:r.priorSignature}).then(a=>({message:r.message,signature:a}))}async signString(r,{signingDate:e=new Date,signingRegion:t,signingService:s}={}){const i=await this.credentialProvider();this.validateResolvedCredentials(i);const a=t??await this.regionProvider(),{shortDate:c}=Bn(e),u=new this.sha256(await this.getSigningKey(i,a,c,s));return u.update(Kt(r)),Ne(await u.digest())}async signRequest(r,{signingDate:e=new Date,signableHeaders:t,unsignableHeaders:s,signingRegion:i,signingService:a}={}){const c=await this.credentialProvider();this.validateResolvedCredentials(c);const u=i??await this.regionProvider(),l=Ho(r),{longDate:p,shortDate:d}=Bn(e),g=Pr(d,u,a??this.service);l.headers[tl]=p,c.sessionToken&&(l.headers[vh]=c.sessionToken);const _=await Mr(l,this.sha256);!Ch(Yr,l.headers)&&this.applyChecksum&&(l.headers[Yr]=_);const m=Bo(l,s,t),y=await this.getSignature(p,g,this.getSigningKey(c,u,d,a),this.createCanonicalRequest(l,m,_));return l.headers[el]=`${$r} Credential=${c.accessKeyId}/${g}, SignedHeaders=${Wo(m)}, Signature=${y}`,l}createCanonicalRequest(r,e,t){const s=Object.keys(e).sort();return`${r.method}
|
|
35
|
+
${this.getCanonicalPath(r)}
|
|
36
|
+
${Ih(r)}
|
|
37
|
+
${s.map(i=>`${i}:${e[i]}`).join(`
|
|
38
|
+
`)}
|
|
39
|
+
|
|
40
|
+
${s.join(";")}
|
|
41
|
+
${t}`}async createStringToSign(r,e,t){const s=new this.sha256;s.update(Kt(t));const i=await s.digest();return`${$r}
|
|
42
|
+
${r}
|
|
43
|
+
${e}
|
|
44
|
+
${Ne(i)}`}getCanonicalPath({path:r}){if(this.uriEscapePath){const e=[];for(const i of r.split("/"))i?.length!==0&&i!=="."&&(i===".."?e.pop():e.push(i));const t=`${r?.startsWith("/")?"/":""}${e.join("/")}${e.length>0&&r?.endsWith("/")?"/":""}`;return jt(t).replace(/%2F/g,"/")}return r}async getSignature(r,e,t,s){const i=await this.createStringToSign(r,e,s),a=new this.sha256(await t);return a.update(Kt(i)),Ne(await a.digest())}getSigningKey(r,e,t,s){return $h(this.sha256,r,t,e,s||this.service)}validateResolvedCredentials(r){if(typeof r!="object"||typeof r.accessKeyId!="string"||typeof r.secretAccessKey!="string")throw new Error("Resolved credential object is not valid")}}const Bn=n=>{const r=Bh(n).replace(/[\-:]/g,"");return{longDate:r,shortDate:r.slice(0,8)}},Wo=n=>Object.keys(n).sort().join(";");function Hh(n,r){if(!n)throw new Error(r)}const Wh=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{const r=Object.prototype.toString.call(n);if(r==="[object Error]"||r==="[object DOMException]"){const e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)},zh=(n,r)=>ce(async()=>{const{createCredentialChain:e,fromEnv:t,fromNodeProviderChain:s}=await import("./aws-credential-providers-B7-NYDyv.js");return{createCredentialChain:e,fromEnv:t,fromNodeProviderChain:s}},[]).then(({createCredentialChain:e,fromEnv:t,fromNodeProviderChain:s})=>{const i=s({...n!=null?{profile:n}:{},...r!=null?{logger:r}:{},clientConfig:{...r!=null?{logger:r}:{},requestHandler:new ls({requestInit:a=>({...a})})}});return n!=null?i:e(t(r!=null?{logger:r}:{}),i)}).catch(e=>{throw new Error(`Failed to import '@aws-sdk/credential-providers'. You can provide a custom \`providerChainResolver\` in the client options if your runtime does not have access to '@aws-sdk/credential-providers': \`new AnthropicAws({ providerChainResolver })\` Original error: ${e.message}`)}),jh=async(n,r)=>{Hh(n.method,"Expected request method property to be set");let e;if(r.awsAccessKey&&r.awsSecretAccessKey)e={accessKeyId:r.awsAccessKey,secretAccessKey:r.awsSecretAccessKey,...r.awsSessionToken!=null&&{sessionToken:r.awsSessionToken}};else{const l=await(r.providerChainResolver?r.providerChainResolver():zh(r.awsProfile,r.logger));try{e=await l()}catch(p){throw new ut({message:"Failed to resolve AWS credentials from the credential provider chain.",cause:Wh(p)})}}const t=new Uh({service:r.serviceName,region:r.regionName,credentials:e,sha256:oh.Sha256}),s=new URL(r.url),i=n.headers?Symbol.iterator in n.headers?Object.fromEntries(Array.from(n.headers).map(l=>[...l])):{...n.headers}:{};delete i.connection,i.host=s.host;const a=Object.fromEntries([...new Set(s.searchParams.keys())].map(l=>[l,s.searchParams.getAll(l)])),c=new us({method:n.method.toUpperCase(),protocol:s.protocol,path:s.pathname,query:a,headers:i,body:n.body});return(await t.sign(c)).headers},zo={off:0,error:200,warn:300,info:400,debug:500};function Ft(){}function Dn(n,r,e){return!r||zo[n]>zo[e]?Ft:r[n].bind(r)}const Fh={error:Ft,warn:Ft,info:Ft,debug:Ft};let jo=new WeakMap;function qh(n,r){const e=jo.get(n);if(e&&e[0]===r)return e[1];const t={error:Dn("error",n,r),warn:Dn("warn",n,r),info:Dn("info",n,r),debug:Dn("debug",n,r)};return jo.set(n,[r,t]),t}function Kh(n){const r=n.logger,e=n.logLevel??"off";return r?qh(r,e):Fh}var Vh=function(n,r,e,t){if(typeof r=="function"?n!==r||!t:!r.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?t:e==="a"?t.call(n):t?t.value:r.get(n)},Zr,sl;const Jh="bedrock-mantle";class Xh extends Kc{constructor({awsRegion:r,baseURL:e,apiKey:t,awsAccessKey:s=null,awsSecretAccessKey:i=null,awsSessionToken:a=null,awsProfile:c,providerChainResolver:u=null,skipAuth:l=!1,...p}={}){const d=r??Gt("AWS_REGION")??Gt("AWS_DEFAULT_REGION"),g=e??Gt("ANTHROPIC_BEDROCK_MANTLE_BASE_URL")??(d?`https://bedrock-mantle.${d}.api.aws/anthropic`:void 0);if(!g)throw new S("No AWS region or base URL found. Set `awsRegion` in the constructor, the `AWS_REGION` / `AWS_DEFAULT_REGION` environment variable, or provide a `baseURL` / `ANTHROPIC_BEDROCK_MANTLE_BASE_URL` environment variable.");const _=t!=null;if(s!=null!=(i!=null))throw new S("`awsAccessKey` and `awsSecretAccessKey` must be provided together. You provided only one.");const y=s!=null&&i!=null,x=c!=null;let E;_?E=t:!y&&!x&&(E=Gt("AWS_BEARER_TOKEN_BEDROCK")??void 0),super({apiKey:E??null,authToken:null,baseURL:g,...p}),Zr.add(this),this.messages=new qr(this),this.beta=Gh(this),this.skipAuth=!1,this.awsRegion=d,this.awsAccessKey=s,this.awsSecretAccessKey=i,this.awsSessionToken=a,this.awsProfile=c??null,this.providerChainResolver=u,this.skipAuth=l,this._useSigV4=E==null}async authHeaders(r){if(!this.skipAuth&&!this._useSigV4)return ec([{Authorization:`Bearer ${this.apiKey}`}])}validateHeaders(){}_shouldResolveDefaultCredentials(){return!1}getUserAgent(){return`AnthropicBedrockMantle/JS ${ge}`}backendMiddleware(){return[async(r,e)=>e(await Vh(this,Zr,"m",sl).call(this,r))]}}Zr=new WeakSet,sl=async function(r){if(this.skipAuth||!this._useSigV4)return r;const e=this.awsRegion;if(!e)throw new S("No AWS region found. Set `awsRegion` in the constructor or the `AWS_REGION` / `AWS_DEFAULT_REGION` environment variable.");const t=await jh(r,{url:r.url,regionName:e,serviceName:Jh,awsAccessKey:this.awsAccessKey,awsSecretAccessKey:this.awsSecretAccessKey,awsSessionToken:this.awsSessionToken,awsProfile:this.awsProfile,providerChainResolver:this.providerChainResolver,logger:Kh(this)});return{...r,headers:ec([r.headers,t]).values}};function Gh(n){const{messages:r}=new Fr(n);return{messages:r}}const Qh=32e3,Yh=/^claude-(opus-5|fable-5|mythos-5)/;function hs(n){if(n.stop_reason==="refusal")throw new qt("refusal","The model declined to generate a mapping for these samples.");const r=n.content.map(e=>e.type==="text"&&typeof e.text=="string"?e.text:"").join("").trim();if(n.stop_reason==="max_tokens")throw new qt("truncated","The response hit the output token limit before finishing.");return{text:r,model:n.model,usage:{inputTokens:n.usage?.input_tokens??void 0,outputTokens:n.usage?.output_tokens??void 0}}}function fs(n){if(n instanceof qt)return n;if(n instanceof Kr.APIUserAbortError)return new qt("aborted","Request was cancelled.");if(n instanceof Kr.APIConnectionError)return _s(n);const r=n?.status;if(typeof r=="number"){const e=n instanceof Error?n.message:`HTTP ${r}`;return new qt(cl(r),e,r)}return _s(n)}function il(n){const r=[];return n.cacheablePrefix?.trim()&&r.push({type:"text",text:n.cacheablePrefix,cache_control:{type:"ephemeral"}}),n.prompt.trim()&&r.push({type:"text",text:n.prompt}),r}function al(n,r){return{model:n,max_tokens:r.maxTokens??Qh,system:r.system,messages:[{role:"user",content:il(r)}]}}function Zh(n,r={}){const e=new Kr({apiKey:n.credentials.apiKey,dangerouslyAllowBrowser:!0,...r.fetch?{fetch:r.fetch}:{}});return{id:"anthropic",async generate(t){try{const s=al(n.model,t),i={signal:t.signal},a=Yh.test(n.model)?await e.beta.messages.stream({...s,betas:["server-side-fallback-2026-07-01"],fallbacks:"default"},i).finalMessage():await e.messages.stream(s,i).finalMessage();return hs(a)}catch(s){throw fs(s)}}}}function ef(n,r={}){const e=n.credentials,t=new Xh({awsRegion:n.region,dangerouslyAllowBrowser:!0,...n.authMode==="apiKey"?{apiKey:e.apiKey}:{awsAccessKey:e.awsAccessKeyId,awsSecretAccessKey:e.awsSecretAccessKey,awsSessionToken:e.awsSessionToken||null},...r.fetch?{fetch:r.fetch}:{}});return{id:"bedrock-mantle",async generate(s){try{const i=await t.messages.stream(al(n.model,s),{signal:s.signal}).finalMessage();return hs(i)}catch(i){throw fs(i)}}}}const $f=Object.freeze(Object.defineProperty({__proto__:null,claudeUserContent:il,createAnthropicProvider:Zh,createBedrockMantleProvider:ef,toClaudeProviderError:fs,toClaudeResult:hs},Symbol.toStringTag,{value:"Module"}));export{S as A,af as D,ai as M,$f as a};
|