@rr0/ufoathome 0.50.1 → 0.52.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.
@@ -0,0 +1,42 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./node.browser-DLoyk0oM.js","./rr0-sighting-editor.mjs","./node.browser-CTpc2BHh.js"])))=>i.map(i=>d[i]);
2
+ import{_ as ue}from"./rr0-sighting-editor.mjs";function w(r,e,t,n,s){if(typeof e=="function"?r!==e||!0:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(r,t),t}function o(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}let mn=function(){const{crypto:r}=globalThis;if(r?.randomUUID)return mn=r.randomUUID.bind(r),r.randomUUID();const e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};function Qe(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}const wn=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{const e=Object.prototype.toString.call(r);if(e==="[object Error]"||e==="[object DOMException]"){const t=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(t.stack=r.stack),r.cause&&!t.cause&&(t.cause=r.cause),r.name&&(t.name=r.name),t}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};class x extends Error{}class q extends x{constructor(e,t,n,s,i){super(`${q.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.requestID=s?.get("request-id"),this.workspaceID=s?.get("anthropic-workspace-id"),this.error=t,this.type=i??null}static makeMessage(e,t,n){const s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new Ge({message:n,cause:wn(t)});const i=t,a=i?.error?.type;return e===400?new as(e,i,n,s,a):e===401?new os(e,i,n,s,a):e===403?new cs(e,i,n,s,a):e===404?new ls(e,i,n,s,a):e===409?new ds(e,i,n,s,a):e===422?new us(e,i,n,s,a):e===429?new hs(e,i,n,s,a):e>=500?new fs(e,i,n,s,a):new q(e,i,n,s,a)}}class se extends q{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Ge extends q{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class is extends Ge{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Ar extends x{constructor(e,{cause:t}={}){super(e??"Retryable error."),t!==void 0&&(this.cause=t)}}class as extends q{}class os extends q{}class cs extends q{}class ls extends q{}class ds extends q{}class us extends q{}class hs extends q{}class fs extends q{}const ra=/^[a-z][a-z0-9+.-]*:/i,ia=r=>ra.test(r);let J=r=>(J=Array.isArray,J(r)),Ds=J;function bn(r){return typeof r!="object"?{}:r??{}}function Ws(r){if(!r)return!0;for(const e in r)return!1;return!0}function aa(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function Fs(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}const oa=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new x(`${r} must be an integer`);if(e<0)throw new x(`${r} must be a positive integer`);return e},Ir=r=>{try{return JSON.parse(r)}catch{return}};const Me=(r,e)=>new Promise(t=>{if(e?.aborted)return t();const n=()=>{clearTimeout(s),t()},s=setTimeout(()=>{e?.removeEventListener("abort",n),t()},r);e?.addEventListener("abort",n,{once:!0})}),ve="0.124.0",ca=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function la(){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 da=()=>{const r=la();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ve,"X-Stainless-OS":qs(Deno.build.os),"X-Stainless-Arch":Bs(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":ve,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process?.version??"unknown"};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ve,"X-Stainless-OS":qs(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Bs(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=ua();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ve,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ve,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ua(){if(typeof navigator>"u"||!navigator)return null;const r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of r){const n=t.exec(navigator.userAgent);if(n){const s=n[1]||0,i=n[2]||0,a=n[3]||0;return{browser:e,version:`${s}.${i}.${a}`}}}return null}const Bs=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",qs=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown");let Hs;const ps=()=>Hs??(Hs=da()),yn=new WeakMap,Mr=typeof globalThis.FinalizationRegistry=="function"?new globalThis.FinalizationRegistry(r=>$e(r)):null;function ha(r,e){return()=>r.removeEventListener("abort",e)}function fa(r,e,t){yn.set(r,ha(e,t))}function pa(r,e){yn.has(e)&&Mr?.register(r,e,e)}function $e(r){const e=yn.get(r);e&&(yn.delete(r),Mr?.unregister(r),e())}function _a(){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 $r(...r){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function Pr(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return $r({start(){},async pull(t){const{done:n,value:s}=await e.next();n?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function _s(r){if(r[Symbol.asyncIterator])return r;const e=r.getReader();return{async next(){try{const t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function ga(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}const e=r.getReader(),t=e.cancel();e.releaseLock(),await t}const ma=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),Or="RFC3986",Cr=r=>String(r),Us={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:Cr},wa="RFC1738";let Xn=(r,e)=>(Xn=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Xn(r,e));const ce=(()=>{const r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})(),$n=1024,ba=(r,e,t,n,s)=>{if(r.length===0)return r;let i=r;if(typeof r=="symbol"?i=Symbol.prototype.toString.call(r):typeof r!="string"&&(i=String(r)),t==="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+=$n){const l=i.length>=$n?i.slice(c,c+$n):i,p=[];for(let g=0;g<l.length;++g){let h=l.charCodeAt(g);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||s===wa&&(h===40||h===41)){p[p.length]=l.charAt(g);continue}if(h<128){p[p.length]=ce[h];continue}if(h<2048){p[p.length]=ce[192|h>>6]+ce[128|h&63];continue}if(h<55296||h>=57344){p[p.length]=ce[224|h>>12]+ce[128|h>>6&63]+ce[128|h&63];continue}g+=1,h=65536+((h&1023)<<10|l.charCodeAt(g)&1023),p[p.length]=ce[240|h>>18]+ce[128|h>>12&63]+ce[128|h>>6&63]+ce[128|h&63]}a+=p.join("")}return a};function ya(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function js(r,e){if(J(r)){const t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}const Lr={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},Nr=function(r,e){Array.prototype.push.apply(r,J(e)?e:[e])};let zs;const H={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:ba,encodeValuesOnly:!1,format:Or,formatter:Cr,indices:!1,serializeDate(r){return(zs??(zs=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function ka(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}const Pn={};function Dr(r,e,t,n,s,i,a,c,l,p,g,h,f,d,m,b,v,S){let y=r,k=S,R=0,T=!1;for(;(k=k.get(Pn))!==void 0&&!T;){const I=k.get(r);if(R+=1,typeof I<"u"){if(I===R)throw new RangeError("Cyclic object value");T=!0}typeof k.get(Pn)>"u"&&(R=0)}if(typeof p=="function"?y=p(e,y):y instanceof Date?y=f?.(y):t==="comma"&&J(y)&&(y=js(y,function(I){return I instanceof Date?f?.(I):I})),y===null){if(i)return l&&!b?l(e,H.encoder,v,"key",d):e;y=""}if(ka(y)||ya(y)){if(l){const I=b?e:l(e,H.encoder,v,"key",d);return[m?.(I)+"="+m?.(l(y,H.encoder,v,"value",d))]}return[m?.(e)+"="+m?.(String(y))]}const A=[];if(typeof y>"u")return A;let L;if(t==="comma"&&J(y))b&&l&&(y=js(y,l)),L=[{value:y.length>0?y.join(",")||null:void 0}];else if(J(p))L=p;else{const I=Object.keys(y);L=g?I.sort(g):I}const N=c?String(e).replace(/\./g,"%2E"):String(e),O=n&&J(y)&&y.length===1?N+"[]":N;if(s&&J(y)&&y.length===0)return O+"[]";for(let I=0;I<L.length;++I){const Z=L[I],_e=typeof Z=="object"&&typeof Z.value<"u"?Z.value:y[Z];if(a&&_e===null)continue;const ge=h&&c?Z.replace(/\./g,"%2E"):Z,sa=J(y)?typeof t=="function"?t(O,ge):O:O+(h?"."+ge:"["+ge+"]");S.set(r,R);const Ns=new WeakMap;Ns.set(Pn,S),Nr(A,Dr(_e,sa,t,n,s,i,a,c,t==="comma"&&b&&J(y)?null:l,p,g,h,f,d,m,b,v,Ns))}return A}function Sa(r=H){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=r.charset||H.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Or;if(typeof r.format<"u"){if(!Xn(Us,r.format))throw new TypeError("Unknown format option provided.");t=r.format}const n=Us[t];let s=H.filter;(typeof r.filter=="function"||J(r.filter))&&(s=r.filter);let i;if(r.arrayFormat&&r.arrayFormat in Lr?i=r.arrayFormat:"indices"in r?i=r.indices?"indices":"repeat":i=H.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const a=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:H.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:H.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:H.allowEmptyArrays,arrayFormat:i,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:H.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?H.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:H.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:H.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:H.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:H.encodeValuesOnly,filter:s,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:H.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:H.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:H.strictNullHandling}}function va(r,e={}){let t=r;const n=Sa(e);let s,i;typeof n.filter=="function"?(i=n.filter,t=i("",t)):J(n.filter)&&(i=n.filter,s=i);const a=[];if(typeof t!="object"||t===null)return"";const c=Lr[n.arrayFormat],l=c==="comma"&&n.commaRoundTrip;s||(s=Object.keys(t)),n.sort&&s.sort(n.sort);const p=new WeakMap;for(let f=0;f<s.length;++f){const d=s[f];n.skipNulls&&t[d]===null||Nr(a,Dr(t[d],d,c,l,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,p))}const g=a.join(n.delimiter);let h=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),g.length>0?h+g:""}function xa(r){return va(r,{arrayFormat:"brackets"})}const Ra="urn:ietf:params:oauth:grant-type:jwt-bearer",Ea="refresh_token",Wr="/v1/oauth/token",kn="oauth-2025-04-20",Ta="oidc-federation-2026-04-01",Aa=120,gs=30,Ia=5,Ks=1<<20;function Fr(r){if(!r)return;let e;try{e=new URL(r)}catch(n){throw new C(`Invalid token endpoint base URL "${r}": ${n}`)}if(e.protocol==="https:")return;const t=e.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!(e.protocol==="http:"&&(t==="localhost"||t==="127.0.0.1"||t==="::1")))throw new C(`Refusing to send credential over non-https token endpoint "${r}"`)}async function Br(r,e){const t=await $a(r);let n;try{n=JSON.parse(t)}catch{throw new C(`Token endpoint returned non-JSON response (status ${r.status})`,r.status,re(t),e)}if(!n.access_token)throw new C(`Token endpoint response missing access_token: ${JSON.stringify(re(n))}`,r.status,re(n),e);if(n.token_type&&n.token_type.toLowerCase()!=="bearer")throw new C(`Token endpoint response: unsupported token_type "${n.token_type}" (want Bearer)`,r.status,re(n),e);return n}const On=2e3,Ma=new Set(["error","error_description","error_uri"]);function re(r){if(r==null)return r;if(typeof r=="string"){let e;try{e=JSON.parse(r)}catch{return r.length<=On?r:r.slice(0,On)+`... <${r.length-On} more chars>`}return JSON.stringify(re(e))}if(typeof r=="object"&&!Array.isArray(r)){const e={};for(const[t,n]of Object.entries(r))Ma.has(t)&&(e[t]=n);return e}return null}async function qr(r,e=t=>console.warn(`anthropic-sdk: ${t}`)){if(typeof process>"u"||process.platform==="win32")return;const{fs:t}=await ue(async()=>{const{fs:a}=await import("./node.browser-DLoyk0oM.js");return{fs:a}},__vite__mapDeps([0,1]),import.meta.url);let n=r,s;try{n=await t.promises.realpath(r),s=await t.promises.stat(n)}catch{return}const i=s.mode&511;if(i&18)throw new C(`Credentials file at ${n} is group/world-writable (mode 0o${i.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${n}\`.`);if(i&36)throw new C(`Credentials file at ${n} is group/world-readable (mode 0o${i.toString(8)}); run \`chmod 600 ${n}\` before retrying.`);typeof process.getuid=="function"&&s.uid!==process.getuid()&&e(`credentials file at ${n} is owned by uid ${s.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function Hr(r,e){const{fs:t,path:n}=await ue(async()=>{const{fs:a,path:c}=await import("./node.browser-DLoyk0oM.js");return{fs:a,path:c}},__vite__mapDeps([0,1]),import.meta.url),s=n.dirname(r);await t.promises.mkdir(s,{recursive:!0,mode:448});const i=`${r}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{const a=await t.promises.open(i,"w",384);try{await a.writeFile(JSON.stringify(e,null,2)),await a.sync()}finally{await a.close()}await t.promises.rename(i,r)}catch(a){throw await t.promises.unlink(i).catch(()=>{}),a}try{const a=await t.promises.open(s,"r");try{await a.sync()}finally{await a.close()}}catch{}}async function $a(r){if(!r.body)return"";const e=r.body.getReader(),t=[];let n=0;for(;;){const{done:i,value:a}=await e.read();if(i)break;if(n+a.length>Ks){const c=Ks-n;c>0&&t.push(a.subarray(0,c)),await e.cancel();break}t.push(a),n+=a.length}let s;if(t.length===1)s=t[0];else{s=new Uint8Array(t.reduce((a,c)=>a+c.length,0));let i=0;for(const a of t)s.set(a,i),i+=a.length}return new TextDecoder("utf-8").decode(s)}class C extends x{constructor(e,t=null,n=null,s=null){super(e),this.statusCode=t,this.body=n,this.requestId=s}}function Pe(){return Math.floor(Date.now()/1e3)}class Pa{constructor(e,t){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=e,this.onAdvisoryRefreshError=t}async getToken(){const e=this.nextForce;this.nextForce=!1;const t=this.cached;if(e||t==null)return(await this.refresh(e)).token;if(t.expiresAt==null)return t.token;const n=t.expiresAt-Pe();return n>Aa?t.token:n>gs?(this.backgroundRefresh(),t.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(e=!1){return this.pendingRefresh&&!e?this.pendingRefresh:this.doRefresh(e)}backgroundRefresh(){this.pendingRefresh||Pe()-this.lastAdvisoryError<Ia||this.doRefresh().catch(e=>{this.lastAdvisoryError=Pe(),this.onAdvisoryRefreshError?.(e)})}doRefresh(e=!1){return this.pendingRefresh=this.provider(e?{forceRefresh:!0}:void 0).then(t=>(this.cached=t,this.pendingRefresh=null,t),t=>{throw this.pendingRefresh=null,t}),this.pendingRefresh}}var Oa={};const M=r=>{if(typeof globalThis.process<"u")return Oa?.[r]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()||void 0};function Ca(r){let e=0;for(const s of r)e+=s.length;const t=new Uint8Array(e);let n=0;for(const s of r)t.set(s,n),n+=s.length;return t}let Vs;function ms(r){let e;return(Vs??(e=new globalThis.TextEncoder,Vs=e.encode.bind(e)))(r)}let Js;function Yn(r){let e;return(Js??(e=new globalThis.TextDecoder,Js=e.decode.bind(e)))(r)}const La=r=>{if(typeof globalThis.Buffer<"u"){const e=globalThis.Buffer.from(r,"base64");return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}if(typeof atob<"u"){const e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}throw new x("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")},Sn="warn",vn={off:0,error:200,warn:300,info:400,debug:500},Qn=(r,e,t)=>{if(r){if(aa(vn,r))return r;t.warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(vn))}`)}};function wt(){}function Ct(r,e,t){return!e||vn[r]>vn[t]?wt:e[r].bind(e)}const Na={error:wt,warn:wt,info:wt,debug:wt};let Xs=new WeakMap;function Gn(r,e){const t=Xs.get(r);if(t&&t[0]===e)return t[1];const n={error:Ct("error",r,e),warn:Ct("warn",r,e),info:Ct("info",r,e),debug:Ct("debug",r,e)};return Xs.set(r,[e,n]),n}function P(r){const e=r.logger,t=r.logLevel??"off";return e?Gn(e,t):Na}let Ys,Cn;function Da(){const r=M("ANTHROPIC_LOG");return(!Cn||r!==Ys)&&(Ys=r,Cn=Gn(console,Qn(r,"process.env['ANTHROPIC_LOG']",Gn(console,Sn))??Sn)),Cn}const ye=r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r),Ur="1.0",Wa=/^[A-Za-z0-9_.-]+$/;function jr(r){if(!r)throw new Error("profile name is empty");if(r==="."||r==="..")throw new Error(`profile name "${r}" is not allowed`);if(r.includes("/")||r.includes("\\"))throw new Error(`profile name "${r}" must not contain path separators`);if(!Wa.test(r))throw new Error(`profile name "${r}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}const Fa=async r=>{var e,t;const n=await ws();if(n===null)return null;const s=r??await zr();if(s===null)return null;jr(s);const{fs:i,path:a}=await ue(async()=>{const{fs:h,path:f}=await import("./node.browser-DLoyk0oM.js");return{fs:h,path:f}},__vite__mapDeps([0,1]),import.meta.url),c=a.join(n,"configs",`${s}.json`);let l;try{l=await i.promises.readFile(c,"utf-8")}catch(h){if(h?.code!=="ENOENT")throw new Error(`failed to read config file ${c}: ${h}`);l=null}if(l===null){const h=M("ANTHROPIC_ORGANIZATION_ID"),f=M("ANTHROPIC_IDENTITY_TOKEN_FILE"),d=M("ANTHROPIC_FEDERATION_RULE_ID");return d&&h?{fromFile:!1,config:{organization_id:h,workspace_id:M("ANTHROPIC_WORKSPACE_ID"),base_url:M("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:d,service_account_id:M("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:f?{source:"file",path:f}:void 0,scope:M("ANTHROPIC_SCOPE")}}}:null}let p;try{p=JSON.parse(l)}catch(h){throw new Error(`failed to parse config file ${c}: ${h}`)}if(!p.authentication)throw new Error(`config file ${c} is missing "authentication"`);const g=p.authentication.type;if(g!=="oidc_federation"&&g!=="user_oauth")throw new Error(`authentication.type "${g}" is not a known authentication type`);if(p.organization_id??(p.organization_id=M("ANTHROPIC_ORGANIZATION_ID")),p.workspace_id??(p.workspace_id=M("ANTHROPIC_WORKSPACE_ID")),p.base_url??(p.base_url=M("ANTHROPIC_BASE_URL")),(e=p.authentication).scope??(e.scope=M("ANTHROPIC_SCOPE")),p.authentication.type==="oidc_federation"){if(!p.authentication.identity_token){const h=M("ANTHROPIC_IDENTITY_TOKEN_FILE");h&&(p.authentication.identity_token={source:"file",path:h})}p.authentication.federation_rule_id||(p.authentication.federation_rule_id=M("ANTHROPIC_FEDERATION_RULE_ID")??""),(t=p.authentication).service_account_id??(t.service_account_id=M("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:p,fromFile:!0}},Ba=async(r,e)=>{if(r?.authentication.credentials_path)return r.authentication.credentials_path;const t=await ws();if(!t)return null;const n=e??await zr();if(!n)return null;jr(n);const{path:s}=await ue(async()=>{const{path:i}=await import("./node.browser-DLoyk0oM.js");return{path:i}},__vite__mapDeps([0,1]),import.meta.url);return s.join(t,"credentials",`${n}.json`)},ws=async()=>{if(!qa())return null;const{path:r}=await ue(async()=>{const{path:i}=await import("./node.browser-DLoyk0oM.js");return{path:i}},__vite__mapDeps([0,1]),import.meta.url),e=M("ANTHROPIC_CONFIG_DIR");if(e)return e;if(ps()["X-Stainless-OS"]==="Windows"){const i=M("APPDATA");if(i)return r.join(i,"Anthropic");const a=M("USERPROFILE");return a?r.join(a,"AppData","Roaming","Anthropic"):null}const n=M("XDG_CONFIG_HOME");if(n)return r.join(n,"anthropic");const s=M("HOME");return s?r.join(s,".config","anthropic"):null},qa=()=>{const r=ps()["X-Stainless-Runtime"];return r==="node"||r==="deno"},zr=async()=>{const r=await ws();if(!r)return null;const e=M("ANTHROPIC_PROFILE");if(e)return e;const{fs:t,path:n}=await ue(async()=>{const{fs:i,path:a}=await import("./node.browser-DLoyk0oM.js");return{fs:i,path:a}},__vite__mapDeps([0,1]),import.meta.url),s=n.join(r,"active_config");try{return(await t.promises.readFile(s,"utf-8")).trim()||"default"}catch(i){if(i?.code!=="ENOENT")throw new Error(`failed to read ${s}: ${i}`);return"default"}};function Qs(r){if(!r)throw new x("Identity token file path is empty");return async()=>{const{fs:e}=await ue(async()=>{const{fs:s}=await import("./node.browser-DLoyk0oM.js");return{fs:s}},__vite__mapDeps([0,1]),import.meta.url);let t;try{t=await e.promises.readFile(r,"utf-8")}catch(s){throw new x(`Failed to read identity token file at ${r}: ${s}`)}const n=t.trim();if(!n)throw new x(`Identity token file at ${r} is empty`);return n}}function Ha(r){if(!r)throw new x("Identity token value is empty");return()=>r}function Ua(r){return async()=>{Fr(r.baseURL);const e=await r.identityTokenProvider();if(e.length>16*1024)throw new C(`Identity token is ${Math.ceil(e.length/1024)} KiB, exceeds the 16 KiB assertion limit`);const t={grant_type:Ra,assertion:e,federation_rule_id:r.federationRuleId,organization_id:r.organizationId};r.serviceAccountId&&(t.service_account_id=r.serviceAccountId),r.workspaceId&&(t.workspace_id=r.workspaceId);const n=`${r.baseURL}${Wr}`;let s;try{s=await r.fetch(n,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${kn},${Ta}`,"User-Agent":r.userAgent||`anthropic-sdk-typescript/${ve} oidcFederationProvider`},body:JSON.stringify(t)})}catch(l){throw new C(`Failed to reach token endpoint ${n}: ${l}`)}const i=s.headers.get("Request-Id");if(!s.ok){const l=await s.text().catch(()=>""),p=re(l);let g="";throw s.status===401&&(g=` Ensure your federation rule matches your identity token. ${r.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 C(`Token exchange failed with status ${s.status}${i?` (request-id ${i})`:""}: ${p}${g}`,s.status,p,i)}const a=await Br(s,i),c=Number(a.expires_in);if(!Number.isFinite(c))throw new C(`Token endpoint response missing required fields: ${JSON.stringify(re(a))}`,s.status,re(a),i);return{token:a.access_token,expiresAt:Pe()+c}}}function ja(r){return async e=>{const{fs:t}=await ue(async()=>{const{fs:v}=await import("./node.browser-DLoyk0oM.js");return{fs:v}},__vite__mapDeps([0,1]),import.meta.url);await qr(r.credentialsPath,r.onSafetyWarning);let n;try{n=await t.promises.readFile(r.credentialsPath,"utf-8")}catch(v){throw new C(`Credentials file not found at ${r.credentialsPath}: ${v}`)}let s;try{s=JSON.parse(n)}catch(v){throw new C(`Credentials file at ${r.credentialsPath} is not valid JSON: ${v}`)}const i=s.access_token;if(!i)throw new C(`Credentials file at ${r.credentialsPath} must include 'access_token'`);const a=s.expires_at;if(!e?.forceRefresh&&(a==null||Pe()<a-gs))return{token:i,expiresAt:a??null};const c=s.refresh_token;if(!r.clientId||!c)throw new C(`Access token at ${r.credentialsPath} has expired and no refresh is available (client_id ${r.clientId?"set":"empty"}, refresh_token ${c?"set":"empty"})`);Fr(r.baseURL);const l={grant_type:Ea,refresh_token:c,client_id:r.clientId},p=`${r.baseURL}${Wr}`;let g;try{g=await r.fetch(p,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":kn,"User-Agent":r.userAgent||`anthropic-sdk-typescript/${ve} userOAuthProvider`},body:JSON.stringify(l)})}catch(v){throw new C(`User OAuth refresh failed to reach token endpoint: ${v}`)}const h=g.headers.get("Request-Id");if(!g.ok){const v=await g.text().catch(()=>"");throw new C(`User OAuth refresh failed (HTTP ${g.status}): ${re(v)}`,g.status,re(v),h)}const f=await Br(g,h),d=Number(f.expires_in);if(!Number.isFinite(d))throw new C(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(re(f))}`,g.status,re(f),h);const m=Pe()+d,b=f.refresh_token||c;return await Hr(r.credentialsPath,{...s,version:Ur,type:"oauth_token",access_token:f.access_token,expires_at:m,refresh_token:b}),{token:f.access_token,expiresAt:m}}}function Kr(r,e){const t=r.authentication.credentials_path??null,n=(r.base_url||e.baseURL).replace(/\/+$/,""),s=Ka(r,t,n,e),i={};return r.workspace_id&&r.authentication.type==="user_oauth"&&(i["anthropic-workspace-id"]=r.workspace_id),{provider:s,extraHeaders:i,baseURL:r.base_url||void 0}}async function za(r,e){const t=await Fa(e);if(!t)return null;const{config:n,fromFile:s}=t,i=n.authentication.credentials_path||!s?n:{...n,authentication:{...n.authentication,credentials_path:await Ba(n,e)??void 0}};return Kr(i,r)}function Ka(r,e,t,n){switch(r.authentication.type){case"oidc_federation":{const s=r.authentication,i=Va(s);if(!i)throw new C("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 C("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(!r.organization_id)throw new C("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");const a=Ua({identityTokenProvider:i,federationRuleId:s.federation_rule_id,organizationId:r.organization_id,serviceAccountId:s.service_account_id,workspaceId:r.workspace_id,baseURL:t,fetch:n.fetch,userAgent:n.userAgent});return e?Ja(a,e,n.onCacheWriteError,n.onSafetyWarning):a}case"user_oauth":{if(!e)throw new C("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return ja({credentialsPath:e,clientId:r.authentication.client_id,baseURL:t,fetch:n.fetch,userAgent:n.userAgent,onSafetyWarning:n.onSafetyWarning})}default:{const s=r.authentication.type;throw new C(`authentication.type "${s}" is not a known authentication type`)}}}function Va(r){if(r.identity_token){const n=r.identity_token.source;if(n!=="file")throw new C(`identity_token.source "${n}" is not supported by this SDK version (only "file")`);if(!r.identity_token.path)throw new C('identity_token.source "file" requires a non-empty path');return Qs(r.identity_token.path)}const e=M("ANTHROPIC_IDENTITY_TOKEN_FILE");if(e)return Qs(e);const t=M("ANTHROPIC_IDENTITY_TOKEN");return t?Ha(t):null}function Ja(r,e,t,n){return async s=>{const{fs:i}=await ue(async()=>{const{fs:l}=await import("./node.browser-DLoyk0oM.js");return{fs:l}},__vite__mapDeps([0,1]),import.meta.url);await qr(e,n);let a;try{const l=await i.promises.readFile(e,"utf-8");a=JSON.parse(l);const p=a?.access_token;if(p&&!s?.forceRefresh){const g=a?.expires_at;if(g==null||Pe()<g-gs)return{token:p,expiresAt:g??null}}}catch(l){l?.code!=="ENOENT"&&!(l instanceof SyntaxError)&&t?.(l)}const c=await r(s);try{await Hr(e,{...a??{},version:Ur,type:"oauth_token",access_token:c.token,expires_at:c.expiresAt})}catch(l){t?.(l)}return c}}var Y,Q;class Tt{constructor(){Y.set(this,void 0),Q.set(this,void 0),w(this,Y,new Uint8Array),w(this,Q,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ms(e):e;w(this,Y,Ca([o(this,Y,"f"),t]));const n=[];let s;for(;(s=Xa(o(this,Y,"f"),o(this,Q,"f")))!=null;){if(s.carriage&&o(this,Q,"f")==null){w(this,Q,s.index);continue}if(o(this,Q,"f")!=null&&(s.index!==o(this,Q,"f")+1||s.carriage)){n.push(Yn(o(this,Y,"f").subarray(0,o(this,Q,"f")-1))),w(this,Y,o(this,Y,"f").subarray(o(this,Q,"f"))),w(this,Q,null);continue}const i=o(this,Q,"f")!==null?s.preceding-1:s.preceding,a=Yn(o(this,Y,"f").subarray(0,i));n.push(a),w(this,Y,o(this,Y,"f").subarray(s.index)),w(this,Q,null)}return n}flush(){return o(this,Y,"f").length?this.decode(`
3
+ `):[]}}Y=new WeakMap,Q=new WeakMap;Tt.NEWLINE_CHARS=new Set([`
4
+ `,"\r"]);Tt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Xa(r,e){for(let s=e??0;s<r.length;s++){if(r[s]===10)return{preceding:s,index:s+1,carriage:!1};if(r[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function Ya(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}var et;class ae{constructor(e,t,n){this.iterator=e,et.set(this,void 0),this.controller=t,w(this,et,n)}static rawEvents(e,t=new AbortController){return Gs(e,t)}static fromSSEResponse(e,t,n){let s=!1;const i=n?P(n):console;async function*a(){if(s)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(const l of Gs(e,t)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(p){throw i.error("Could not parse message into JSON:",l.data),i.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 i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),p}if(l.event!=="ping"&&l.event==="error"){const p=Ir(l.data)??l.data,g=p?.error?.type;throw new q(void 0,p,void 0,e.headers,g)}}c=!0}catch(l){if(Qe(l))return;throw l}finally{c||t.abort(),$e(t)}}return new ae(a,t,n)}static fromReadableStream(e,t,n){let s=!1;async function*i(){const c=new Tt,l=_s(e);for await(const p of l)for(const g of c.decode(p))yield g;for(const p of c.flush())yield p}async function*a(){if(s)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(const l of i())c||l&&(yield JSON.parse(l));c=!0}catch(l){if(Qe(l))return;throw l}finally{c||t.abort(),$e(t)}}return new ae(a,t,n)}[(et=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),s=i=>({next:()=>{if(i.length===0){const a=n.next();e.push(a),t.push(a)}return i.shift()}});return[new ae(()=>s(e),this.controller,o(this,et,"f")),new ae(()=>s(t),this.controller,o(this,et,"f"))]}toReadableStream(){const e=this;let t;return $r({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{const{value:s,done:i}=await t.next();if(i)return n.close();const a=ms(JSON.stringify(s)+`
5
+ `);n.enqueue(a)}catch(s){n.error(s)}},async cancel(){await t.return?.()}})}}async function*Gs(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new x("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 x("Attempted to iterate over a response with no body");const t=new Ga,n=new Tt,s=_s(r.body);for await(const i of Qa(s))for(const a of n.decode(i)){const c=t.decode(a);c&&(yield c)}for(const i of n.flush()){const a=t.decode(i);a&&(yield a)}}async function*Qa(r){let e=new Uint8Array;for await(const t of r){if(t==null)continue;const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?ms(t):t;let s=new Uint8Array(e.length+n.length);s.set(e),s.set(n,e.length),e=s;let i;for(;(i=Ya(e))!==-1;)yield e.subarray(0,i),e=e.subarray(i)}e.length>0&&(yield e)}class Ga{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const 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(e),e.startsWith(":"))return null;let[t,n,s]=Za(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}}function Za(r,e){const t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}async function Vr(r,e){const{response:t,requestLogID:n,retryOfRequestLogID:s,startTime:i}=e,a=await(async()=>{if(e.options.stream)return P(r).debug("response",t.status,t.url,t.headers,t.body),ae.fromSSEResponse(t,e.controller,r);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const l=t.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;const f=await t.json();return bs(f,t)}return await t.text()})().finally(()=>{!e.options.stream&&!e.options.__binaryResponse&&$e(e.controller)});return P(r).debug(`[${n}] response parsed`,ye({retryOfRequestLogID:s,url:t.url,status:t.status,body:a,durationMs:Date.now()-i})),a}function bs(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperties(r,{_request_id:{value:e.headers.get("request-id"),enumerable:!1},_workspace_id:{value:e.headers.get("anthropic-workspace-id"),enumerable:!1}})}const Jr=new WeakSet;function Xr(r){return typeof r=="object"&&r!==null&&Jr.has(r)}function eo(r){const e=new Set;for(;typeof r=="object"&&r!==null&&!e.has(r);){if(e.add(r),Xr(r)||Qe(r)||r instanceof Ge||r instanceof Ar)return!0;r=r.cause}return!1}function Zs(r,e,t,n){return async(s,i={})=>{if(e.length===0)return r.call(void 0,s,i);const a=i.headers instanceof Headers?i.headers:new Headers(i.headers),c=await no(r,e,t,n)({...i,headers:a,url:typeof s=="string"?s:s instanceof URL?s.href:s.url});if(c.bodyUsed||c.body?.locked)throw new x("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 to(r,e){const t=new WeakMap;return{options:r,logger:e?P(e):Da(),parse(n){if(r?.stream&&n.ok)return er(n,r,e);let s=t.get(n);return s||(s=er(n,r,e),t.set(n,s)),s}}}async function er(r,e,t){if(r.bodyUsed||r.body?.locked)throw new x("cannot ctx.parse() a response whose body was already consumed; call ctx.parse() instead of reading the body, or read via response.clone()");if(e?.stream&&r.ok)return ae.fromSSEResponse(r.clone(),new AbortController,t);if(r.status===204)return null;if(e?.__binaryResponse)return r;const s=r.headers.get("content-type")?.split(";")[0]?.trim();return s?.includes("application/json")||s?.endsWith("+json")?r.headers.get("content-length")==="0"?void 0:bs(await r.clone().json(),r):await r.clone().text()}function no(r,e,t,n){let s=async({url:a,...c})=>{try{return await r.call(void 0,a,c)}catch(l){const p=wn(l);throw Jr.add(p),p}};const i=to(t,n);for(let a=e.length-1;a>=0;a--){const c=e[a],l=s;s=async p=>c(p,l,i)}return s}var bt;class At extends Promise{constructor(e,t,n=Vr){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=n,bt.set(this,void 0),w(this,bt,e)}_thenUnwrap(e){return new At(o(this,bt,"f"),this.responsePromise,async(t,n)=>bs(e(await this.parseResponse(t,n),n),n.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,bt,"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)}}bt=new WeakMap;var Lt;class ys{constructor(e,t,n,s){Lt.set(this,void 0),w(this,Lt,e),this.options=s,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new x("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await o(this,Lt,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Lt=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Yr extends At{constructor(e,t,n){super(e,t,async(s,i)=>new n(s,i.response,await Vr(s,i),i.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class pe extends ys{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){const t=this.first_id;return t?{...this.options,query:{...bn(this.options.query),before_id:t}}:null}const e=this.last_id;return e?{...this.options,query:{...bn(this.options.query),after_id:e}}:null}}class $ extends ys{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.next_page=n.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){const e=this.next_page;return e?{...this.options,query:{...bn(this.options.query),page:e}}:null}}class so extends ys{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.next_page=n.next_page||null,this.prev_page=n.prev_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){const e=this.next_page;return e?{...this.options,query:{...bn(this.options.query),page:e}}:null}}const Qr=()=>{if(typeof File>"u"){const{process:r}=globalThis,e=typeof r?.versions?.node=="string"&&parseInt(r.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Je(r,e,t){return Qr(),new File(r,e??"unknown_file",t)}function on(r,e){const t=typeof r=="object"&&r!==null&&("name"in r&&r.name&&String(r.name)||"url"in r&&r.url&&String(r.url)||"filename"in r&&r.filename&&String(r.filename)||"path"in r&&r.path&&String(r.path))||"";return e?t.split(/[\\/]/).pop()||void 0:t}const Gr=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",Ze=async(r,e,t=!0)=>({...r,body:await io(r.body,e,t)}),tr=new WeakMap;function ro(r){const e=typeof r=="function"?r:r.fetch,t=tr.get(e);if(t)return t;const n=(async()=>{try{const s="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new s(i).text()}catch{return!0}})();return tr.set(e,n),n}const io=async(r,e,t=!0)=>{if(!await ro(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const n=new FormData;return await Promise.all(Object.entries(r||{}).map(([s,i])=>Zn(n,s,i,t))),n},Zn=async(r,e,t,n)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")r.append(e,String(t));else if(t instanceof Response){let s={};const i=t.headers.get("Content-Type");i&&(s={type:i}),r.append(e,Je([await t.blob()],on(t,n),s))}else if(Gr(t))r.append(e,Je([await new Response(Pr(t)).blob()],on(t,n)));else if(t instanceof Blob)r.append(e,Je([t],on(t,n)||void 0,{type:t.type}));else if(Array.isArray(t))await Promise.all(t.map(s=>Zn(r,e+"[]",s,n)));else{if(typeof t.then=="function")throw new TypeError(`Received a Promise for "${e}"; await it first, e.g. \`await toFile(...)\``);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))throw new TypeError(`Received ${t.constructor.name} for "${e}"; to upload raw bytes, wrap them with \`await toFile(bytes, 'filename')\``);if(typeof t=="object")await Promise.all(Object.entries(t).map(([s,i])=>Zn(r,`${e}[${s}]`,i,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}}},Zr=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function",ao=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&Zr(r),oo=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function";async function ei(r,e,t){if(Qr(),r=await r,e||(e=on(r,!0)),ao(r))return r instanceof File&&e==null&&t==null?r:Je([await r.arrayBuffer()],e??r.name,{type:r.type,lastModified:r.lastModified,...t});if(oo(r)){const s=await r.blob();return e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()),Je(await es(s),e,t)}const n=await es(r);if(!t?.type){const s=n.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof s=="string"&&(t={...t,type:s})}return Je(n,e,t)}async function es(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(Zr(r))e.push(r instanceof Blob?r:await r.arrayBuffer());else if(Gr(r))for await(const t of r)e.push(...await es(t));else{const t=r?.constructor?.name;throw new Error(`Unexpected data type: ${typeof r}${t?`; constructor: ${t}`:""}${co(r)}`)}return e}function co(r){return typeof r!="object"||r===null?"":`; props: [${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}class E{constructor(e){this._client=e}}const ti=Symbol.for("brand.privateNullableHeaders");function*lo(r){if(!r)return;if(ti in r){const{values:n,nulls:s}=r;yield*n.entries();for(const i of s)yield[i,null];return}let e=!1,t;r instanceof Headers?t=r.entries():Ds(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let n of t){const s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const i=Ds(n[1])?n[1]:[n[1]];let a=!1;for(const c of i)c!==void 0&&(e&&!a&&(a=!0,yield[s,cn]),yield[s,c])}}const cn=Symbol("clear"),uo=new Set(["x-stainless-helper"]),ho=(r,e)=>{const t=r?r.split(",").map(n=>n.trim()).filter(Boolean):[];for(const n of e.split(",").map(s=>s.trim()))n&&!t.includes(n)&&t.push(n);return t.join(", ")},u=r=>{const e=new Headers,t=new Set;for(const n of r){const s=new Set;for(const[i,a]of lo(n)){const c=i.toLowerCase();if(uo.has(c)){if(a===cn)continue;a===null?(e.delete(i),t.add(c)):(e.set(i,ho(e.get(i),a)),t.delete(c));continue}(a===cn||!s.has(c))&&(e.delete(i),s.add(c),a===cn)||(a===null?(e.delete(i),t.add(c)):(e.append(i,a),t.delete(c)))}}return{[ti]:!0,values:e,nulls:t}};function ni(r){return r.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const nr=Object.freeze(Object.create(null)),fo=(r=ni)=>function(t,...n){if(t.length===1)return t[0];let s=!1;const i=[],a=t.reduce((g,h,f)=>{/[?#]/.test(h)&&(s=!0);const d=n[f];let m=(s?encodeURIComponent:r)(""+d);return f!==n.length&&(d==null||typeof d=="object"&&d.toString===Object.getPrototypeOf(Object.getPrototypeOf(d.hasOwnProperty??nr)??nr)?.toString)&&(m=d+"",i.push({start:g.length+h.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(d).slice(8,-1)} is not a valid path parameter`})),g+h+(f===n.length?"":m)},""),c=a.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let p;for(;(p=l.exec(c))!==null;)i.push({start:p.index,length:p[0].length,error:`Value "${p[0]}" can't be safely passed as a path parameter`});if(i.sort((g,h)=>g.start-h.start),i.length>0){let g=0;const h=i.reduce((f,d)=>{const m=" ".repeat(d.start-g),b="^".repeat(d.length);return g=d.start+d.length,f+m+b},"");throw new x(`Path parameters result in path with invalid segments:
7
+ ${i.map(f=>f.error).join(`
8
+ `)}
9
+ ${a}
10
+ ${h}`)}return a},_=fo(ni);class si extends E{retrieve(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.get(_`/v1/deployment_runs/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}list(e={},t){const{betas:n,workspace_id:s,...i}=e??{};return this._client.getAPIList("/v1/deployment_runs?beta=true",$,{query:i,...t,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}}class ri extends E{create(e,t){const{betas:n,workspace_id:s,...i}=e;return this._client.post("/v1/deployments?beta=true",{body:i,...t,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}retrieve(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.get(_`/v1/deployments/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}update(e,t,n){const{betas:s,workspace_id:i,...a}=t;return this._client.post(_`/v1/deployments/${e}?beta=true`,{body:a,...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}list(e={},t){const{betas:n,workspace_id:s,...i}=e??{};return this._client.getAPIList("/v1/deployments?beta=true",$,{query:i,...t,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}archive(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.post(_`/v1/deployments/${e}/archive?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}pause(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.post(_`/v1/deployments/${e}/pause?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}run(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.post(_`/v1/deployments/${e}/run?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}unpause(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.post(_`/v1/deployments/${e}/unpause?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}}class ii extends E{create(e,t){const{betas:n,workspace_id:s,...i}=e;return this._client.post("/v1/dreams?beta=true",{body:i,...t,headers:u([{"anthropic-beta":[...n??[],"dreaming-2026-04-21"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}retrieve(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.get(_`/v1/dreams/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"dreaming-2026-04-21"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}list(e={},t){const{betas:n,workspace_id:s,...i}=e??{};return this._client.getAPIList("/v1/dreams?beta=true",$,{query:i,...t,headers:u([{"anthropic-beta":[...n??[],"dreaming-2026-04-21"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}archive(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.post(_`/v1/dreams/${e}/archive?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"dreaming-2026-04-21"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}cancel(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.post(_`/v1/dreams/${e}/cancel?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"dreaming-2026-04-21"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}}const It="x-stainless-helper",ai="x-stainless-helper-method";function ts(r){return{[It]:r}}const xt=Symbol("anthropic.sdk.stainlessHelper");function ln(r){return typeof r=="object"&&r!==null&&xt in r}function oi(r,e){const t=new Set;if(r)for(const n of r)ln(n)&&t.add(n[xt]);if(e)for(const n of e){ln(n)&&t.add(n[xt]);const s=n.content;if(Array.isArray(s))for(const i of s)ln(i)&&t.add(i[xt])}return Array.from(t)}function ci(r,e){const t=oi(r,e);return t.length===0?{}:{[It]:t.join(", ")}}function li(r){return ln(r)?{[It]:r[xt]}:{}}let di=class extends E{list(e={},t){const{betas:n,workspace_id:s,...i}=e??{};return this._client.getAPIList("/v1/files?beta=true",$,{query:i,...t,headers:u([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.delete(_`/v1/files/${e}?beta=true`,{...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}download(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.get(_`/v1/files/${e}/content?beta=true`,{...n,headers:u([{Accept:"application/binary",...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.get(_`/v1/files/${e}?beta=true`,{...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}upload(e,t){const{betas:n,workspace_id:s,...i}=e;return this._client.post("/v1/files?beta=true",Ze({body:i,...t,headers:u([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...s!=null?{"anthropic-workspace-id":s}:void 0},li(i.file),t?.headers])},this._client))}},ui=class extends E{retrieve(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.get(_`/v1/models/${e}?beta=true`,{...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}list(e={},t){const{betas:n,workspace_id:s,...i}=e??{};return this._client.getAPIList("/v1/models?beta=true",pe,{query:i,...t,headers:u([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}};class hi extends E{create(e,t){const{betas:n,...s}=e;return this._client.post("/v1/user_profiles?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...n??[],"user-profiles-2026-08-18"].toString()},t?.headers])})}retrieve(e,t={},n){const{betas:s}=t??{};return this._client.get(_`/v1/user_profiles/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"user-profiles-2026-08-18"].toString()},n?.headers])})}update(e,t,n){const{betas:s,...i}=t;return this._client.post(_`/v1/user_profiles/${e}?beta=true`,{body:i,...n,headers:u([{"anthropic-beta":[...s??[],"user-profiles-2026-08-18"].toString()},n?.headers])})}list(e={},t){const{betas:n,...s}=e??{};return this._client.getAPIList("/v1/user_profiles?beta=true",$,{query:s,...t,headers:u([{"anthropic-beta":[...n??[],"user-profiles-2026-08-18"].toString()},t?.headers])})}createEnrollmentURL(e,t={},n){const{betas:s}=t??{};return this._client.post(_`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"user-profiles-2026-08-18"].toString()},n?.headers])})}}var Re={},z={},sr;function po(){if(sr)return z;sr=1;var r=z&&z.__extends||(function(){var g=function(h,f){return g=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,m){d.__proto__=m}||function(d,m){for(var b in m)m.hasOwnProperty(b)&&(d[b]=m[b])},g(h,f)};return function(h,f){g(h,f);function d(){this.constructor=h}h.prototype=f===null?Object.create(f):(d.prototype=f.prototype,new d)}})();Object.defineProperty(z,"__esModule",{value:!0});var e=256,t=(function(){function g(h){h===void 0&&(h="="),this._paddingCharacter=h}return g.prototype.encodedLength=function(h){return this._paddingCharacter?(h+2)/3*4|0:(h*8+5)/6|0},g.prototype.encode=function(h){for(var f="",d=0;d<h.length-2;d+=3){var m=h[d]<<16|h[d+1]<<8|h[d+2];f+=this._encodeByte(m>>>18&63),f+=this._encodeByte(m>>>12&63),f+=this._encodeByte(m>>>6&63),f+=this._encodeByte(m>>>0&63)}var b=h.length-d;if(b>0){var m=h[d]<<16|(b===2?h[d+1]<<8:0);f+=this._encodeByte(m>>>18&63),f+=this._encodeByte(m>>>12&63),b===2?f+=this._encodeByte(m>>>6&63):f+=this._paddingCharacter||"",f+=this._paddingCharacter||""}return f},g.prototype.maxDecodedLength=function(h){return this._paddingCharacter?h/4*3|0:(h*6+7)/8|0},g.prototype.decodedLength=function(h){return this.maxDecodedLength(h.length-this._getPaddingLength(h))},g.prototype.decode=function(h){if(h.length===0)return new Uint8Array(0);for(var f=this._getPaddingLength(h),d=h.length-f,m=new Uint8Array(this.maxDecodedLength(d)),b=0,v=0,S=0,y=0,k=0,R=0,T=0;v<d-4;v+=4)y=this._decodeChar(h.charCodeAt(v+0)),k=this._decodeChar(h.charCodeAt(v+1)),R=this._decodeChar(h.charCodeAt(v+2)),T=this._decodeChar(h.charCodeAt(v+3)),m[b++]=y<<2|k>>>4,m[b++]=k<<4|R>>>2,m[b++]=R<<6|T,S|=y&e,S|=k&e,S|=R&e,S|=T&e;if(v<d-1&&(y=this._decodeChar(h.charCodeAt(v)),k=this._decodeChar(h.charCodeAt(v+1)),m[b++]=y<<2|k>>>4,S|=y&e,S|=k&e),v<d-2&&(R=this._decodeChar(h.charCodeAt(v+2)),m[b++]=k<<4|R>>>2,S|=R&e),v<d-3&&(T=this._decodeChar(h.charCodeAt(v+3)),m[b++]=R<<6|T,S|=T&e),S!==0)throw new Error("Base64Coder: incorrect characters for decoding");return m},g.prototype._encodeByte=function(h){var f=h;return f+=65,f+=25-h>>>8&6,f+=51-h>>>8&-75,f+=61-h>>>8&-15,f+=62-h>>>8&3,String.fromCharCode(f)},g.prototype._decodeChar=function(h){var f=e;return f+=(42-h&h-44)>>>8&-e+h-43+62,f+=(46-h&h-48)>>>8&-e+h-47+63,f+=(47-h&h-58)>>>8&-e+h-48+52,f+=(64-h&h-91)>>>8&-e+h-65+0,f+=(96-h&h-123)>>>8&-e+h-97+26,f},g.prototype._getPaddingLength=function(h){var f=0;if(this._paddingCharacter){for(var d=h.length-1;d>=0&&h[d]===this._paddingCharacter;d--)f++;if(h.length<4||f>2)throw new Error("Base64Coder: incorrect padding")}return f},g})();z.Coder=t;var n=new t;function s(g){return n.encode(g)}z.encode=s;function i(g){return n.decode(g)}z.decode=i;var a=(function(g){r(h,g);function h(){return g!==null&&g.apply(this,arguments)||this}return h.prototype._encodeByte=function(f){var d=f;return d+=65,d+=25-f>>>8&6,d+=51-f>>>8&-75,d+=61-f>>>8&-13,d+=62-f>>>8&49,String.fromCharCode(d)},h.prototype._decodeChar=function(f){var d=e;return d+=(44-f&f-46)>>>8&-e+f-45+62,d+=(94-f&f-96)>>>8&-e+f-95+63,d+=(47-f&f-58)>>>8&-e+f-48+52,d+=(64-f&f-91)>>>8&-e+f-65+0,d+=(96-f&f-123)>>>8&-e+f-97+26,d},h})(t);z.URLSafeCoder=a;var c=new a;function l(g){return c.encode(g)}z.encodeURLSafe=l;function p(g){return c.decode(g)}return z.decodeURLSafe=p,z.encodedLength=function(g){return n.encodedLength(g)},z.maxDecodedLength=function(g){return n.maxDecodedLength(g)},z.decodedLength=function(g){return n.decodedLength(g)},z}var dn={exports:{}},_o=dn.exports,rr;function go(){return rr||(rr=1,(function(r){(function(e,t){var n={};t(n);var s=n.default;for(var i in n)s[i]=n[i];r.exports=s})(_o,function(e){e.__esModule=!0,e.digestLength=32,e.blockSize=64;var t=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 n(f,d,m,b,v){for(var S,y,k,R,T,A,L,N,O,I,Z,_e,ge;v>=64;){for(S=d[0],y=d[1],k=d[2],R=d[3],T=d[4],A=d[5],L=d[6],N=d[7],I=0;I<16;I++)Z=b+I*4,f[I]=(m[Z]&255)<<24|(m[Z+1]&255)<<16|(m[Z+2]&255)<<8|m[Z+3]&255;for(I=16;I<64;I++)O=f[I-2],_e=(O>>>17|O<<15)^(O>>>19|O<<13)^O>>>10,O=f[I-15],ge=(O>>>7|O<<25)^(O>>>18|O<<14)^O>>>3,f[I]=(_e+f[I-7]|0)+(ge+f[I-16]|0);for(I=0;I<64;I++)_e=(((T>>>6|T<<26)^(T>>>11|T<<21)^(T>>>25|T<<7))+(T&A^~T&L)|0)+(N+(t[I]+f[I]|0)|0)|0,ge=((S>>>2|S<<30)^(S>>>13|S<<19)^(S>>>22|S<<10))+(S&y^S&k^y&k)|0,N=L,L=A,A=T,T=R+_e|0,R=k,k=y,y=S,S=_e+ge|0;d[0]+=S,d[1]+=y,d[2]+=k,d[3]+=R,d[4]+=T,d[5]+=A,d[6]+=L,d[7]+=N,b+=64,v-=64}return b}var s=(function(){function f(){this.digestLength=e.digestLength,this.blockSize=e.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 f.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},f.prototype.clean=function(){for(var d=0;d<this.buffer.length;d++)this.buffer[d]=0;for(var d=0;d<this.temp.length;d++)this.temp[d]=0;this.reset()},f.prototype.update=function(d,m){if(m===void 0&&(m=d.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");var b=0;if(this.bytesHashed+=m,this.bufferLength>0){for(;this.bufferLength<64&&m>0;)this.buffer[this.bufferLength++]=d[b++],m--;this.bufferLength===64&&(n(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(m>=64&&(b=n(this.temp,this.state,d,b,m),m%=64);m>0;)this.buffer[this.bufferLength++]=d[b++],m--;return this},f.prototype.finish=function(d){if(!this.finished){var m=this.bytesHashed,b=this.bufferLength,v=m/536870912|0,S=m<<3,y=m%64<56?64:128;this.buffer[b]=128;for(var k=b+1;k<y-8;k++)this.buffer[k]=0;this.buffer[y-8]=v>>>24&255,this.buffer[y-7]=v>>>16&255,this.buffer[y-6]=v>>>8&255,this.buffer[y-5]=v>>>0&255,this.buffer[y-4]=S>>>24&255,this.buffer[y-3]=S>>>16&255,this.buffer[y-2]=S>>>8&255,this.buffer[y-1]=S>>>0&255,n(this.temp,this.state,this.buffer,0,y),this.finished=!0}for(var k=0;k<8;k++)d[k*4+0]=this.state[k]>>>24&255,d[k*4+1]=this.state[k]>>>16&255,d[k*4+2]=this.state[k]>>>8&255,d[k*4+3]=this.state[k]>>>0&255;return this},f.prototype.digest=function(){var d=new Uint8Array(this.digestLength);return this.finish(d),d},f.prototype._saveState=function(d){for(var m=0;m<this.state.length;m++)d[m]=this.state[m]},f.prototype._restoreState=function(d,m){for(var b=0;b<this.state.length;b++)this.state[b]=d[b];this.bytesHashed=m,this.finished=!1,this.bufferLength=0},f})();e.Hash=s;var i=(function(){function f(d){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(d.length>this.blockSize)new s().update(d).finish(m).clean();else for(var b=0;b<d.length;b++)m[b]=d[b];for(var b=0;b<m.length;b++)m[b]^=54;this.inner.update(m);for(var b=0;b<m.length;b++)m[b]^=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 b=0;b<m.length;b++)m[b]=0}return f.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},f.prototype.clean=function(){for(var d=0;d<this.istate.length;d++)this.ostate[d]=this.istate[d]=0;this.inner.clean(),this.outer.clean()},f.prototype.update=function(d){return this.inner.update(d),this},f.prototype.finish=function(d){return this.outer.finished?this.outer.finish(d):(this.inner.finish(d),this.outer.update(d,this.digestLength).finish(d)),this},f.prototype.digest=function(){var d=new Uint8Array(this.digestLength);return this.finish(d),d},f})();e.HMAC=i;function a(f){var d=new s().update(f),m=d.digest();return d.clean(),m}e.hash=a,e.default=a;function c(f,d){var m=new i(f).update(d),b=m.digest();return m.clean(),b}e.hmac=c;function l(f,d,m,b){var v=b[0];if(v===0)throw new Error("hkdf: cannot expand more");d.reset(),v>1&&d.update(f),m&&d.update(m),d.update(b),d.finish(f),b[0]++}var p=new Uint8Array(e.digestLength);function g(f,d,m,b){d===void 0&&(d=p),b===void 0&&(b=32);for(var v=new Uint8Array([1]),S=c(d,f),y=new i(S),k=new Uint8Array(y.digestLength),R=k.length,T=new Uint8Array(b),A=0;A<b;A++)R===k.length&&(l(k,y,m,v),R=0),T[A]=k[R++];return y.clean(),k.fill(0),v.fill(0),T}e.hkdf=g;function h(f,d,m,b){for(var v=new i(f),S=v.digestLength,y=new Uint8Array(4),k=new Uint8Array(S),R=new Uint8Array(S),T=new Uint8Array(b),A=0;A*S<b;A++){var L=A+1;y[0]=L>>>24&255,y[1]=L>>>16&255,y[2]=L>>>8&255,y[3]=L>>>0&255,v.reset(),v.update(d),v.update(y),v.finish(R);for(var N=0;N<S;N++)k[N]=R[N];for(var N=2;N<=m;N++){v.reset(),v.update(R).finish(R);for(var O=0;O<S;O++)k[O]^=R[O]}for(var N=0;N<S&&A*S+N<b;N++)T[A*S+N]=k[N]}for(var A=0;A<S;A++)k[A]=R[A]=0;for(var A=0;A<4;A++)y[A]=0;return v.clean(),T}e.pbkdf2=h})})(dn)),dn.exports}var Nt={},ir;function mo(){if(ir)return Nt;ir=1,Object.defineProperty(Nt,"__esModule",{value:!0}),Nt.timingSafeEqual=e;function r(t,n=""){if(!t)throw new Error(n)}function e(t,n){if(t.byteLength!==n.byteLength)return!1;t instanceof DataView||(t=new DataView(ArrayBuffer.isView(t)?t.buffer:t)),n instanceof DataView||(n=new DataView(ArrayBuffer.isView(n)?n.buffer:n)),r(t instanceof DataView),r(n instanceof DataView);const s=t.byteLength;let i=0,a=-1;for(;++a<s;)i|=t.getUint8(a)^n.getUint8(a);return i===0}return Nt}var ar;function wo(){if(ar)return Re;ar=1,Object.defineProperty(Re,"__esModule",{value:!0}),Re.Webhook=Re.WebhookVerificationError=void 0;const r=po(),e=go(),t=mo(),n=300;class s extends Error{constructor(l){super(l),Object.setPrototypeOf(this,s.prototype),this.name="ExtendableError",this.stack=new Error(l).stack}}class i extends s{constructor(l){super(l),Object.setPrototypeOf(this,i.prototype),this.name="WebhookVerificationError"}}Re.WebhookVerificationError=i;class a{constructor(l,p){if(p?.format==="raw")l instanceof Uint8Array?this.key=l:this.key=Uint8Array.from(l,g=>g.charCodeAt(0));else{if(typeof l!="string")throw new Error("Expected secret to be of type string");l.startsWith(a.prefix)&&(l=l.substring(a.prefix.length)),this.key=r.decode(l)}if(this.key.length===0)throw new Error("Secret can't be empty.")}verify(l,p,g){var h;const f=(h=g?.jsonParse)!==null&&h!==void 0?h:!0,d={};for(const A of Object.keys(p))d[A.toLowerCase()]=p[A];const m=d["webhook-id"],b=d["webhook-signature"],v=d["webhook-timestamp"];if(!b||!m||!v)throw new i("Missing required headers");const S=this.verifyTimestamp(v),k=this.sign(m,S,l).split(",")[1],R=b.split(" "),T=new globalThis.TextEncoder;for(const A of R){const[L,N]=A.split(",");if(L==="v1"&&(0,t.timingSafeEqual)(T.encode(N),T.encode(k))){const O=l.toString();return O===""?void 0:f?JSON.parse(O):void 0}}throw new i("No matching signature found")}sign(l,p,g){if(typeof g!="string")if(g.constructor.name==="Buffer")g=g.toString();else throw new Error("Expected payload to be of type string or Buffer.");const h=new TextEncoder,f=Math.floor(p.getTime()/1e3),d=h.encode(`${l}.${f}.${g}`);return`v1,${r.encode(e.hmac(this.key,d))}`}verifyTimestamp(l){const p=Math.floor(Date.now()/1e3),g=parseInt(l,10);if(Number.isNaN(g))throw new i("Invalid Signature Headers");if(p-g>n)throw new i("Message timestamp too old");if(g>p+n)throw new i("Message timestamp too new");return new Date(g*1e3)}}return Re.Webhook=a,a.prefix="whsec_",Re}var bo=wo();class fi extends E{parseUnverified(e){return JSON.parse(e)}unwrap(e,t){const n=t?.headers;if(n==null)throw new Error("Webhook headers are required in order to verify the signature");const s=t.key===void 0?this._client.webhookKey:t.key;if(!s)throw new Error("Webhook key must not be null or empty in order to unwrap");return new bo.Webhook(s).verify(e,n),JSON.parse(e)}}let pi=class extends E{list(e,t={},n){const{betas:s,workspace_id:i,...a}=t??{};return this._client.getAPIList(_`/v1/agents/${e}/versions?beta=true`,$,{query:a,...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}};class ks extends E{constructor(){super(...arguments),this.versions=new pi(this._client)}create(e,t){const{betas:n,workspace_id:s,...i}=e;return this._client.post("/v1/agents?beta=true",{body:i,...t,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}retrieve(e,t={},n){const{betas:s,workspace_id:i,...a}=t??{};return this._client.get(_`/v1/agents/${e}?beta=true`,{query:a,...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}update(e,t,n){const{betas:s,workspace_id:i,...a}=t;return this._client.post(_`/v1/agents/${e}?beta=true`,{body:a,...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}list(e={},t){const{betas:n,workspace_id:s,...i}=e??{};return this._client.getAPIList("/v1/agents?beta=true",$,{query:i,...t,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}archive(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.post(_`/v1/agents/${e}/archive?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}}ks.Versions=pi;function Mt(r,e){if(!r)return()=>{};if(r.aborted)return e.abort(),()=>{};const t=()=>e.abort();return r.addEventListener("abort",t),()=>r.removeEventListener("abort",t)}function Xe(r,e){return r instanceof q&&r.status===e}function yo(r){return r instanceof q&&typeof r.status=="number"&&r.status>=400&&r.status<500}function xn(r){return yo(r)&&!Xe(r,408)&&!Xe(r,409)&&!Xe(r,429)}function _i(r,e,t){return Math.min(e*2**r,t)}function ko(r,e){return r+Math.random()*(e-r)}function gi(r){return r*(1-Math.random()*.25)}function mi(r,{authToken:e,helper:t}){if(!e)throw new x(`copyClientForHelper: expected a non-empty authToken but received ${JSON.stringify(e)}`);const n=r,s=n._options.defaultHeaders,i=n._authState?.extraHeaders,a=i?Object.fromEntries(Object.entries(i).filter(([l])=>{const p=l.toLowerCase();return p!=="authorization"&&p!=="x-api-key"})):void 0,c=u([a,s,{[It]:t}]);return r.withOptions({apiKey:null,authToken:e,baseURL:r.baseURL,credentials:void 0,defaultHeaders:c})}var Oe,Dt,ee,Wt,Ft,Bt,tt,nt,Ce,We,un,Fe,yt;const So=999,vo=1e3,xo=6e4,Ro=3e5;class Ss{constructor(e){Oe.set(this,void 0),Dt.set(this,!1),ee.set(this,void 0),Wt.set(this,void 0),Ft.set(this,void 0),Bt.set(this,void 0),tt.set(this,void 0),nt.set(this,void 0),Ce.set(this,void 0),this.client=e.client,this.environmentId=e.environmentId,this.environmentKey=e.environmentKey,this.workerId=e.workerId??Ao(),w(this,Oe,mi(e.client,{authToken:e.environmentKey,helper:"environments-work-poller"})),w(this,Ft,e.autoStop??!0),w(this,Bt,e.drain??!1),w(this,tt,e.blockMs===void 0?So:e.blockMs),w(this,nt,e.reclaimOlderThanMs??null),w(this,Ce,e.requestOptions),w(this,ee,new AbortController),w(this,Wt,Mt(e.signal,o(this,ee,"f")))}get signal(){return o(this,ee,"f").signal}abort(){o(this,ee,"f").abort()}async*[(Oe=new WeakMap,Dt=new WeakMap,ee=new WeakMap,Wt=new WeakMap,Ft=new WeakMap,Bt=new WeakMap,tt=new WeakMap,nt=new WeakMap,Ce=new WeakMap,Symbol.asyncIterator)](){if(o(this,Dt,"f"))throw new x("Cannot iterate over a consumed WorkPoller");w(this,Dt,!0);const e=P(this.client);e.info("poller starting",{component:"work-poller",environment_id:this.environmentId});const t=new To(e,this.environmentId);try{let n=0;for(;!o(this,ee,"f").signal.aborted;){let s;try{s=await o(this,Oe,"f").beta.environments.work.poll(this.environmentId,{"Anthropic-Worker-ID":this.workerId,...o(this,tt,"f")!==null?{block_ms:o(this,tt,"f")}:{},...o(this,nt,"f")!==null?{reclaim_older_than_ms:o(this,nt,"f")}:{}},{headers:u([o(this,Ce,"f")?.headers]),signal:o(this,ee,"f").signal})}catch(i){if(o(this,ee,"f").signal.aborted)return;if(xn(i))throw e.error("poll failed permanently, stopping poller",{error:String(i)}),i;const a=gi(Eo(n));e.warn("poll failed, backing off",{error:String(i),backoff_ms:a}),n++,await Me(a,o(this,ee,"f").signal);continue}if(n=0,s==null){if(o(this,Bt,"f"))return;t.onEmptyPoll(),await Me(ko(1e3,3e3),o(this,ee,"f").signal);continue}t.onClaim(),e.info("claimed work",{component:"work-poller",environment_id:this.environmentId,work_id:s.id,work_type:s.data.type});try{await o(this,Oe,"f").beta.environments.work.ack(s.id,{environment_id:s.environment_id},{headers:u([o(this,Ce,"f")?.headers]),signal:o(this,ee,"f").signal})}catch(i){e.error("ack failed",{work_id:s.id,error:String(i)});continue}try{yield s}finally{if(o(this,Ft,"f"))try{await o(this,Oe,"f").beta.environments.work.stop(s.id,{environment_id:s.environment_id},{headers:u([o(this,Ce,"f")?.headers])})}catch(i){Xe(i,409)||e.warn("stop failed",{work_id:s.id,error:String(i)})}}}}finally{o(this,Wt,"f").call(this)}}}function Eo(r){return _i(r,vo,xo)}class To{constructor(e,t){We.set(this,void 0),un.set(this,void 0),Fe.set(this,void 0),yt.set(this,0),w(this,We,e),w(this,un,t)}onEmptyPoll(){const e=Date.now(),t={component:"work-poller",environment_id:o(this,un,"f")};o(this,Fe,"f")===void 0?(w(this,Fe,w(this,yt,e,"f")),o(this,We,"f").info("idle; polling for work",t)):e-o(this,yt,"f")>=Ro?(w(this,yt,e),o(this,We,"f").info(`still polling; idle for ${Math.round((e-o(this,Fe,"f"))/1e3)}s`,t)):o(this,We,"f").debug("poll returned no work",t)}onClaim(){w(this,Fe,void 0)}}We=new WeakMap,un=new WeakMap,Fe=new WeakMap,yt=new WeakMap;function Ao(){const e=globalThis.process?.env?.HOSTNAME;return e?`${e}-${mn()}`:mn()}var Be,ke,qe;class Io{constructor(){Be.set(this,[]),ke.set(this,[]),qe.set(this,!1)}push(e){if(o(this,qe,"f"))return!1;const t=o(this,ke,"f").shift();return t?t({done:!1,value:e}):o(this,Be,"f").push(e),!0}close(){if(!o(this,qe,"f"))for(w(this,qe,!0);o(this,ke,"f").length>0;)o(this,ke,"f").shift()({done:!0,value:void 0})}next(e){return o(this,Be,"f").length>0?Promise.resolve({done:!1,value:o(this,Be,"f").shift()}):o(this,qe,"f")||e?.aborted?Promise.resolve({done:!0,value:void 0}):new Promise(t=>{const n=i=>{e?.removeEventListener("abort",s),t(i)},s=()=>{const i=o(this,ke,"f").indexOf(n);i>=0&&o(this,ke,"f").splice(i,1),t({done:!0,value:void 0})};o(this,ke,"f").push(n),e?.addEventListener("abort",s,{once:!0})})}tryShift(){return o(this,Be,"f").shift()}}Be=new WeakMap,ke=new WeakMap,qe=new WeakMap;class vs extends Error{constructor(e){const t=typeof e=="string"?e:e.map(n=>n.type==="text"?n.text:`[${n.type}]`).join(" ");super(t),this.name="ToolError",this.content=e}}function or(r){return"name"in r?r.name:"mcp_server_name"in r?r.mcp_server_name:r.type}function Mo(r){return r instanceof vs?r.content:`Error: ${r instanceof Error?r.message:String(r)}`}async function $o(r,e,t){try{const n=r.parse?r.parse(e):e;return{content:await r.run(n,t),isError:!1}}catch(n){return{content:Mo(n),isError:!0}}}var kt,hn,He,Ie,ie,W,qt,j,Ht,Rt,fn,B,Ke,G,Ve,Se,Ue,he,pn,Et,ne,Ut,wi,cr,lr,dr,Ln,ur,jt,zt,Nn,hr,bi;const fr=500,Po=1e4,Oo=12e4,Co=3e4,Lo=1e3,No=3e4,Do=5*6e4,Wo=6e4;function yi(r){return r.type==="session.status_idle"&&r.stop_reason?.type==="end_turn"}class Fo{constructor(e,t){kt.set(this,void 0),hn.set(this,void 0),He.set(this,new Set),Ie.set(this,!1),ie.set(this,void 0),w(this,kt,e),w(this,hn,t)}noteEvent(e){e.type!=="user.tool_confirmation"&&(yi(e)?this.arm():this.disarm())}block(e){o(this,He,"f").add(e),o(this,ie,"f")!==void 0&&(w(this,Ie,!0),clearTimeout(o(this,ie,"f")),w(this,ie,void 0))}unblock(e){o(this,He,"f").delete(e),o(this,He,"f").size===0&&o(this,Ie,"f")&&this.arm()}arm(){if(!(o(this,kt,"f")<=0)){if(o(this,He,"f").size>0){w(this,Ie,!0);return}w(this,Ie,!1),o(this,ie,"f")!==void 0&&clearTimeout(o(this,ie,"f")),w(this,ie,setTimeout(o(this,hn,"f"),o(this,kt,"f")))}}disarm(){w(this,Ie,!1),o(this,ie,"f")!==void 0&&(clearTimeout(o(this,ie,"f")),w(this,ie,void 0))}}kt=new WeakMap,hn=new WeakMap,He=new WeakMap,Ie=new WeakMap,ie=new WeakMap;class xs{constructor(e,t){W.add(this),qt.set(this,!1),j.set(this,void 0),Ht.set(this,void 0),Rt.set(this,void 0),fn.set(this,void 0),B.set(this,void 0),Ke.set(this,new Set),G.set(this,new Set),Ve.set(this,new Map),Se.set(this,new Map),Ue.set(this,new Io),he.set(this,0),pn.set(this,Do),Et.set(this,null),ne.set(this,void 0),this.client=t.client,this.sessionId=e,this.tools=t.tools,this.maxIdleMs=t.maxIdleMs??Wo,w(this,B,P(t.client)),w(this,fn,new Map(t.tools.map(n=>[or(n),n]))),w(this,j,new AbortController),w(this,Ht,Mt(t.signal,o(this,j,"f"))),w(this,Rt,t.requestOptions),w(this,ne,new Fo(this.maxIdleMs,()=>{o(this,B,"f").info("session idle after end_turn; 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,pn,e)}async*[(qt=new WeakMap,j=new WeakMap,Ht=new WeakMap,Rt=new WeakMap,fn=new WeakMap,B=new WeakMap,Ke=new WeakMap,G=new WeakMap,Ve=new WeakMap,Se=new WeakMap,Ue=new WeakMap,he=new WeakMap,pn=new WeakMap,Et=new WeakMap,ne=new WeakMap,W=new WeakSet,Symbol.asyncIterator)](){if(o(this,qt,"f"))throw new x("Cannot iterate over a consumed SessionToolRunner");w(this,qt,!0),o(this,B,"f").info("session tool runner starting",{component:"session-tool-runner",session_id:this.sessionId});const e=o(this,W,"m",wi).call(this).catch(t=>{o(this,j,"f").signal.aborted||o(this,B,"f").error("stream loop failed",{error:String(t)}),o(this,j,"f").abort()});try{for(;;){const n=await o(this,Ue,"f").next(o(this,j,"f").signal);if(n.done)break;yield n.value}await e;let t;for(;(t=o(this,Ue,"f").tryShift())!==void 0;)yield t}finally{o(this,j,"f").abort(),o(this,ne,"f").disarm(),await e;try{await o(this,W,"m",bi).call(this)}catch(t){o(this,B,"f").warn("drain failed",{error:String(t)})}o(this,Ue,"f").close();for(const t of this.tools)try{await t.close?.()}catch(n){o(this,B,"f").warn("tool.close failed",{tool:or(t),error:String(n)})}o(this,Ht,"f").call(this)}}}Ut=function(){return{...o(this,Rt,"f"),headers:u([ts("session-tool-runner"),o(this,Rt,"f")?.headers]),signal:o(this,j,"f").signal}},wi=async function(){const e=o(this,j,"f");let t=fr;for(;!e.signal.aborted;){try{const n=await this.client.beta.sessions.events.stream(this.sessionId,{},o(this,W,"m",Ut).call(this));await o(this,W,"m",cr).call(this);for await(const s of n)if(t=fr,await o(this,W,"m",dr).call(this,s))return}catch(n){if(e.signal.throwIfAborted(),xn(n))throw o(this,B,"f").error("permanent stream failure, shutting down",{error:String(n)}),e.abort(),n;o(this,B,"f").warn("stream disconnected, reconnecting",{error:String(n),backoff_ms:t})}e.signal.throwIfAborted(),await Me(t,e.signal),t=Math.min(t*2,Po)}},cr=async function(){const e=o(this,j,"f"),t=[];let n=!1;try{for await(const a of this.client.beta.sessions.events.list(this.sessionId,{limit:1e3},o(this,W,"m",Ut).call(this)))o(this,W,"m",lr).call(this,a,t),n=yi(a)}catch(a){e.signal.throwIfAborted(),o(this,B,"f").warn("reconcile list failed",{error:String(a)});for(const c of t)o(this,Ke,"f").delete(c.id);return}const s=t.filter(a=>!o(this,G,"f").has(a.id));o(this,ne,"f").disarm();for(const a of s)await o(this,W,"m",Ln).call(this,a);for(const a of[...o(this,Se,"f").values()]){const c=o(this,Ve,"f").get(a.id);c!==void 0&&await o(this,W,"m",jt).call(this,a,c)}const i=s.filter(a=>!o(this,G,"f").has(a.id)&&!o(this,Se,"f").has(a.id));n&&i.length===0?o(this,ne,"f").arm():o(this,ne,"f").disarm()},lr=function(e,t){e.type==="agent.tool_use"||e.type==="agent.custom_tool_use"?(o(this,Ke,"f").add(e.id),o(this,G,"f").has(e.id)||t.push(e)):e.type==="user.tool_result"?o(this,G,"f").add(e.tool_use_id):e.type==="user.custom_tool_result"?o(this,G,"f").add(e.custom_tool_use_id):e.type==="user.tool_confirmation"&&(o(this,G,"f").has(e.tool_use_id)||o(this,Ve,"f").set(e.tool_use_id,e.result))},dr=async function(e){switch(o(this,ne,"f").noteEvent(e),e.type){case"agent.tool_use":case"agent.custom_tool_use":return o(this,Ke,"f").has(e.id)||(o(this,Ke,"f").add(e.id),await o(this,W,"m",Ln).call(this,e)),!1;case"user.tool_confirmation":return await o(this,W,"m",ur).call(this,e),!1;case"user.tool_result":return o(this,G,"f").add(e.tool_use_id),!1;case"user.custom_tool_result":return o(this,G,"f").add(e.custom_tool_use_id),!1;case"session.status_terminated":case"session.deleted":return o(this,B,"f").info("session terminated",{component:"session-tool-runner",session_id:this.sessionId}),o(this,j,"f").abort(),!0;default:return!1}},Ln=async function(e){const t=e.evaluated_permission,n=t==="deny"?"deny":o(this,Ve,"f").get(e.id);if(n===void 0){t===void 0||t==="allow"?await o(this,W,"m",Nn).call(this,e,void 0):o(this,Se,"f").has(e.id)||(o(this,B,"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,Se,"f").set(e.id,e),o(this,ne,"f").block(e.id));return}await o(this,W,"m",jt).call(this,e,n)},ur=async function(e){o(this,Ve,"f").set(e.tool_use_id,e.result);const t=o(this,Se,"f").get(e.tool_use_id);t!==void 0&&await o(this,W,"m",jt).call(this,t,e.result)},jt=async function(e,t){const n=o(this,Se,"f").delete(e.id);if(t==="allow"){o(this,B,"f").info("tool call confirmed",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),n||o(this,ne,"f").block(e.id);try{await o(this,W,"m",Nn).call(this,e,"allow")}finally{o(this,ne,"f").unblock(e.id)}return}n&&o(this,ne,"f").unblock(e.id),o(this,G,"f").add(e.id),o(this,B,"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,W,"m",zt).call(this,{event:e,toolUseId:e.id,name:e.name,isError:!1,posted:!1,confirmation:"deny"})},zt=function(e){o(this,Ue,"f").push(e)},Nn=async function(e,t){var n,s;if(!o(this,G,"f").has(e.id)){o(this,B,"f").info("executing tool",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),w(this,he,(n=o(this,he,"f"),n++,n));try{const i=o(this,fn,"f").get(e.name);if(!i){o(this,B,"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}),o(this,W,"m",zt).call(this,{event:e,toolUseId:e.id,name:e.name,isError:!1,posted:!1,confirmation:t});return}let a,c;const l=new AbortController,p=Mt(o(this,j,"f").signal,l),g=setTimeout(()=>l.abort(),Oo);try{const d=await $o(i,e.input,{toolUse:e,toolUseBlock:e,signal:l.signal});a=d.content,c=d.isError}finally{clearTimeout(g),p()}const h=Bo(e,c,qo(a)),f=await o(this,W,"m",hr).call(this,h,e.id);o(this,W,"m",zt).call(this,{event:e,result:h,toolUseId:e.id,name:e.name,isError:c,posted:f,confirmation:t})}finally{w(this,he,(s=o(this,he,"f"),s--,s)),o(this,he,"f")===0&&o(this,Et,"f")?.call(this)}}},hr=async function(e,t){const n=o(this,j,"f"),s=Date.now();let i,a=0;for(;;){a++,n.signal.throwIfAborted();try{return await this.client.beta.sessions.events.send(this.sessionId,{events:[e]},o(this,W,"m",Ut).call(this)),o(this,G,"f").add(t),!0}catch(c){if(i=c,xn(c))break;const l=o(this,pn,"f")-(Date.now()-s);if(l<=0)break;const p=Math.min(gi(_i(a-1,Lo,No)),l);o(this,B,"f").warn("tool result send failed; retrying",{tool_use_id:t,attempt:a,backoff_ms:p,error:String(c)}),await Me(p,n.signal)}}return o(this,B,"f").error("failed to send tool result",{tool_use_id:t,attempts:a,error:String(i)}),!1},bi=async function(){o(this,he,"f")!==0&&(await Promise.race([new Promise(e=>w(this,Et,e)),Me(Co)]),w(this,Et,null),o(this,he,"f")>0&&o(this,B,"f").warn("drain timeout exceeded"))};function Bo(r,e,t){return r.type==="agent.custom_tool_use"?{type:"user.custom_tool_result",custom_tool_use_id:r.id,is_error:e,content:t}:{type:"user.tool_result",tool_use_id:r.id,is_error:e,content:t}}function qo(r){if(typeof r=="string")return[{type:"text",text:r||"(no output)"}];const e=r.map(t=>t.type==="text"?{type:"text",text:t.text||"(no output)"}:t.type==="image"||t.type==="document"?t:t.type==="search_result"?{type:"search_result",source:t.source,title:t.title,content:t.content.map(n=>({type:"text",text:n.text})),citations:{enabled:t.citations?.enabled??!1}}:{type:"text",text:JSON.stringify(t)});return e.length>0?e:[{type:"text",text:"(no output)"}]}const wc=15e3,pr=5e3;function Ho(r,e){if(!(r>=pr))throw new x(`${e} must be at least ${pr}ms (got ${r}); to run without memory sync, pass \`memorySyncIntervalMs: null\` to the worker instead`)}var _n,St,ns,vt,je;const _r=3e4,Uo=9e4,jo="NO_HEARTBEAT";function zo(r){return r.resources.some(e=>e.type==="memory_store")}function Ko(r){if(!r)return null;let e;try{const n=r.replace(/-/g,"+").replace(/_/g,"/"),s=n.padEnd(Math.ceil(n.length/4)*4,"=");e=JSON.parse(Yn(La(s)))}catch{return null}if(e===null||typeof e!="object"||Array.isArray(e))return null;const t=e.sessions_token;return typeof t=="string"&&t!==""?t:null}class ki{constructor(e){if(_n.add(this),St.set(this,void 0),e.unrestrictedPaths!==void 0)throw new x("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&&Ho(e.memorySyncIntervalMs,"memorySyncIntervalMs"),this.memorySyncIntervalMs=e.memorySyncIntervalMs,this.memorySyncDeletions=e.memorySyncDeletions??"enabled",this.workerId=e.workerId,this.requestOptions=e.requestOptions,w(this,St,e.signal)}async run(e){const{environmentId:t,environmentKey:n}=this;if(t===void 0||n===void 0)throw new x("EnvironmentWorker.run: environmentId and environmentKey are required to poll for work");const s=e??o(this,St,"f"),i=new Ss({client:this.client,environmentId:t,environmentKey:n,...this.workerId!==void 0?{workerId:this.workerId}:{},...s?{signal:s}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},autoStop:!1});for await(const a of i)try{await o(this,_n,"m",ns).call(this,a,n,i.signal)}catch(c){if(i.signal?.aborted)throw c;P(this.client).error("work item failed",{work_id:a.id,error:String(c)})}}async handleItem(e){const t=e?.workId??M("ANTHROPIC_WORK_ID"),n=e?.environmentId??M("ANTHROPIC_ENVIRONMENT_ID"),s=e?.sessionId??M("ANTHROPIC_SESSION_ID"),i=e?.environmentKey??this.environmentKey??M("ANTHROPIC_ENVIRONMENT_KEY"),a=e?.workSecret||M("ANTHROPIC_WORK_SECRET")||null;if(!t)throw new x("handleItem: workId is required — pass it or set ANTHROPIC_WORK_ID");if(!n)throw new x("handleItem: environmentId is required — pass it or set ANTHROPIC_ENVIRONMENT_ID");if(!s)throw new x("handleItem: sessionId is required — pass it or set ANTHROPIC_SESSION_ID");if(!i)throw new x("handleItem: environmentKey is required — pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY");const c={id:t,environment_id:n,secret:a,data:{type:"session",id:s}};await o(this,_n,"m",ns).call(this,c,i,e?.signal??o(this,St,"f"))}}St=new WeakMap,_n=new WeakSet,ns=async function(e,t,n){const s=P(this.client),i=Ko(e.secret);e.secret&&i===null&&s.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 a=i??t,c=mi(this.client,{authToken:a,helper:"environments-worker"}),l=e.data.id,p=new AbortController,g=Mt(n,p),h=new Jo(p),f=await ue(()=>import("./node.browser-CTpc2BHh.js"),__vite__mapDeps([2,1]),import.meta.url);let d,m;const b=Yo(c,e,h,s,this.requestOptions,k=>{d=k,m?._setSendRetryWindow(k)}).catch(k=>{p.signal.aborted||s.error("heartbeat loop failed",{work_id:e.id,error:String(k)}),p.abort()});let v=async()=>{},S,y=!1;try{if(e.data.type!=="session"){s.debug("skipping non-session work item",{work_id:e.id,type:e.data.type});return}const k=await c.beta.sessions.retrieve(l);if(i===null&&this.memorySyncIntervalMs!==null&&zo(k))throw new f.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 R={workdir:this.workdir,client:c,session:k,...this.maxFileBytes!==void 0?{maxFileBytes:this.maxFileBytes}:{}};try{v=await f.setupSkills(R)}catch(A){s.warn("skill setup failed",{session_id:l,work_id:e.id,error:String(A)})}i!==null&&this.memorySyncIntervalMs!==null?(S=new f.SessionMemoryStores(c,{workdir:this.workdir,...this.memorySyncIntervalMs!==void 0?{syncIntervalMs:this.memorySyncIntervalMs}:{},syncDeletions:this.memorySyncDeletions}),await S.download(k),R.allowedRoots=S.roots,R.readOnlyRoots=S.readOnlyRoots):s.debug("memory stores disabled for this item",{work_id:e.id});const T=typeof this.tools=="function"?this.tools(R):this.tools??f.betaAgentToolset20260401(R);m=new xs(l,{client:c,tools:T,...this.maxIdleMs!==void 0?{maxIdleMs:this.maxIdleMs}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},signal:p.signal}),d!==void 0&&m._setSendRetryWindow(d);for await(const A of m)S&&await S.syncIfDue();y=!p.signal.aborted}finally{try{await v().catch(k=>{s.warn("skill cleanup failed",{session_id:l,work_id:e.id,error:String(k)})})}finally{if(S){const k=f.MEMORY_FLUSH_TIMEOUT_MS;y&&await gr(S.finish(),k)&&s.warn(`final memory sync cut off after ${k}ms; the flush that follows still uploads changed files`,{session_id:l,work_id:e.id});const R=new AbortController;await gr(S.flushWrites(R.signal),k)&&(R.abort(),s.warn(`memory flush cut off after ${k}ms; changed files it had not uploaded yet are not saved`,{session_id:l,work_id:e.id})),await S.dispose().catch(A=>{s.warn("memory store cleanup failed",{session_id:l,work_id:e.id,error:String(A)})})}}h.finish("runner_done"),g(),await b,h.lost?s.info("lease lost; released without stopping it",{session_id:l,work_id:e.id}):await Vo(c,e,s,this.requestOptions)}};async function gr(r,e){let t;try{return await Promise.race([r.then(()=>!1,()=>!1),new Promise(n=>{t=setTimeout(()=>n(!0),e)})])}finally{t!==void 0&&clearTimeout(t)}}async function Vo(r,e,t,n){try{await r.beta.environments.work.stop(e.id,{environment_id:e.environment_id,force:!0},{...n,headers:u([n?.headers])})}catch(s){Xe(s,409)||t.error("force-stop on exit failed",{work_id:e.id,error:String(s)})}}class Jo{constructor(e){vt.set(this,void 0),je.set(this,void 0),w(this,vt,e)}get signal(){return o(this,vt,"f").signal}finish(e){w(this,je,o(this,je,"f")??e),o(this,vt,"f").abort()}get lost(){return o(this,je,"f")==="lease_lost"||o(this,je,"f")==="assumed_lost"}}vt=new WeakMap,je=new WeakMap;function Xo(r){let e=r instanceof q?r.error:void 0;for(const t of["error","details","current_state"]){if(!Fs(e))return{};e=e[t]}return Fs(e)?e:{}}async function Yo(r,e,t,n,s,i){let a=_r,c=Uo,l=Date.now(),p=jo;const g=async()=>{const h=new AbortController,f=Mt(t.signal,h),d=setTimeout(()=>h.abort(),a);try{const m=await r.beta.environments.work.heartbeat(e.id,{environment_id:e.environment_id,expected_last_heartbeat:p},{...s,headers:u([s?.headers]),signal:h.signal});l=Date.now(),p=m.last_heartbeat,m.ttl_seconds>0&&(c=m.ttl_seconds*1e3,a=Math.max(1e3,Math.min(c/2,_r)),i?.(c)),(m.state==="stopping"||m.state==="stopped")&&(n.info("heartbeat signals shutdown",{work_id:e.id,state:m.state}),t.finish("control_plane_stop")),m.lease_extended||(n.warn("lease not extended, shutting down",{work_id:e.id}),t.finish("control_plane_stop"))}catch(m){if(t.signal.throwIfAborted(),Xe(m,412)){const b=Xo(m);n.error("lease lost: heartbeat precondition failed",{work_id:e.id,server_state:b.state,server_ttl_seconds:b.ttl_seconds,server_last_heartbeat:b.last_heartbeat}),t.finish("lease_lost");return}if(xn(m))throw n.error("permanent heartbeat failure",{work_id:e.id,error:String(m)}),t.finish("heartbeat_rejected"),m;if(Date.now()-l>c){n.error("lease assumed lost: no successful heartbeat in ttl",{work_id:e.id,ttl_ms:c,error:String(m)}),t.finish("assumed_lost");return}n.warn("transient heartbeat failure",{work_id:e.id,error:String(m)})}finally{clearTimeout(d),f()}};for(await g();!t.signal.aborted;)await Me(a,t.signal),t.signal.throwIfAborted(),await g()}class Tn extends E{retrieve(e,t,n){const{environment_id:s,betas:i,workspace_id:a}=t;return this._client.get(_`/v1/environments/${s}/work/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}update(e,t,n){const{environment_id:s,betas:i,workspace_id:a,...c}=t;return this._client.post(_`/v1/environments/${s}/work/${e}?beta=true`,{body:c,...n,headers:u([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}list(e,t={},n){const{betas:s,...i}=t??{};return this._client.getAPIList(_`/v1/environments/${e}/work?beta=true`,$,{query:i,...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}ack(e,t,n){const{environment_id:s,betas:i}=t;return this._client.post(_`/v1/environments/${s}/work/${e}/ack?beta=true`,{...n,headers:u([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}heartbeat(e,t,n){const{environment_id:s,desired_ttl_seconds:i,expected_last_heartbeat:a,betas:c}=t;return this._client.post(_`/v1/environments/${s}/work/${e}/heartbeat?beta=true`,{query:{desired_ttl_seconds:i,expected_last_heartbeat:a},...n,headers:u([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}poll(e,t={},n){const{betas:s,"Anthropic-Worker-ID":i,...a}=t??{};return this._client.get(_`/v1/environments/${e}/work/poll?beta=true`,{query:a,...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"Anthropic-Worker-ID":i}:void 0},n?.headers])})}stats(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.get(_`/v1/environments/${e}/work/stats?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}stop(e,t,n){const{environment_id:s,betas:i,workspace_id:a,...c}=t;return this._client.post(_`/v1/environments/${s}/work/${e}/stop?beta=true`,{body:c,...n,headers:u([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}poller(e){return new Ss({...e,client:this._client})}worker(e){return new ki({...e,client:this._client})}}Tn.WorkPoller=Ss;Tn.EnvironmentWorker=ki;class Rs extends E{constructor(){super(...arguments),this.work=new Tn(this._client)}create(e,t){const{betas:n,workspace_id:s,...i}=e;return this._client.post("/v1/environments?beta=true",{body:i,...t,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}retrieve(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.get(_`/v1/environments/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}update(e,t,n){const{betas:s,workspace_id:i,...a}=t;return this._client.post(_`/v1/environments/${e}?beta=true`,{body:a,...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}list(e={},t){const{betas:n,workspace_id:s,...i}=e??{};return this._client.getAPIList("/v1/environments?beta=true",$,{query:i,...t,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.delete(_`/v1/environments/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}archive(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.post(_`/v1/environments/${e}/archive?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}}Rs.Work=Tn;class Si extends E{create(e,t,n){const{view:s,betas:i,workspace_id:a,...c}=t;return this._client.post(_`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:s},body:c,...n,headers:u([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}retrieve(e,t,n){const{memory_store_id:s,betas:i,workspace_id:a,...c}=t;return this._client.get(_`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:c,...n,headers:u([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}update(e,t,n){const{memory_store_id:s,view:i,betas:a,workspace_id:c,...l}=t;return this._client.post(_`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:{view:i},body:l,...n,headers:u([{"anthropic-beta":[...a??[],"agent-memory-2026-07-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},n?.headers])})}list(e,t={},n){const{betas:s,workspace_id:i,...a}=t??{};return this._client.getAPIList(_`/v1/memory_stores/${e}/memories?beta=true`,$,{query:a,...n,headers:u([{"anthropic-beta":[...s??[],"agent-memory-2026-07-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}delete(e,t,n){const{memory_store_id:s,expected_content_sha256:i,betas:a,workspace_id:c}=t;return this._client.delete(_`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:{expected_content_sha256:i},...n,headers:u([{"anthropic-beta":[...a??[],"agent-memory-2026-07-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},n?.headers])})}}class vi extends E{retrieve(e,t,n){const{memory_store_id:s,betas:i,workspace_id:a,...c}=t;return this._client.get(_`/v1/memory_stores/${s}/memory_versions/${e}?beta=true`,{query:c,...n,headers:u([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}list(e,t={},n){const{betas:s,workspace_id:i,...a}=t??{};return this._client.getAPIList(_`/v1/memory_stores/${e}/memory_versions?beta=true`,$,{query:a,...n,headers:u([{"anthropic-beta":[...s??[],"agent-memory-2026-07-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}redact(e,t,n){const{memory_store_id:s,betas:i,workspace_id:a}=t;return this._client.post(_`/v1/memory_stores/${s}/memory_versions/${e}/redact?beta=true`,{...n,headers:u([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}}class An extends E{constructor(){super(...arguments),this.memories=new Si(this._client),this.memoryVersions=new vi(this._client)}create(e,t){const{betas:n,workspace_id:s,...i}=e;return this._client.post("/v1/memory_stores?beta=true",{body:i,...t,headers:u([{"anthropic-beta":[...n??[],"agent-memory-2026-07-22"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}retrieve(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.get(_`/v1/memory_stores/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"agent-memory-2026-07-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}update(e,t,n){const{betas:s,workspace_id:i,...a}=t;return this._client.post(_`/v1/memory_stores/${e}?beta=true`,{body:a,...n,headers:u([{"anthropic-beta":[...s??[],"agent-memory-2026-07-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}list(e={},t){const{betas:n,workspace_id:s,...i}=e??{};return this._client.getAPIList("/v1/memory_stores?beta=true",$,{query:i,...t,headers:u([{"anthropic-beta":[...n??[],"agent-memory-2026-07-22"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.delete(_`/v1/memory_stores/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"agent-memory-2026-07-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}archive(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.post(_`/v1/memory_stores/${e}/archive?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"agent-memory-2026-07-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}}An.Memories=Si;An.MemoryVersions=vi;class In{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new Tt;for await(const t of this.iterator)for(const n of e.decode(t))yield JSON.parse(n);for(const t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new x("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 x("Attempted to iterate over a response with no body");return new In(_s(e.body),t)}}let xi=class extends E{create(e,t){const{betas:n,user_profile_id:s,workspace_id:i,...a}=e;return this._client.post("/v1/messages/batches?beta=true",{body:a,...t,headers:u([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...s!=null?{"anthropic-user-profile-id":s}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}retrieve(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.get(_`/v1/messages/batches/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}list(e={},t){const{betas:n,workspace_id:s,...i}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",pe,{query:i,...t,headers:u([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.delete(_`/v1/messages/batches/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}cancel(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.post(_`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}async results(e,t={},n){const s=await this.retrieve(e,t,n);if(!s.results_url)throw new x(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);const{betas:i,workspace_id:a}=t??{};return this._client.get(s.results_url,{...n,headers:u([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((c,l)=>In.fromResponse(l.response,l.controller))}};const Ri={"claude-opus-4@20250514":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function Ei(r){return r?.output_format??r?.output_config?.format}function mr(r,e,t){const n=Ei(e);return!e||!("parse"in(n??{}))?{...r,content:r.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 t.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return s}),parsed_output:null}:Ti(r,e,t)}function Ti(r,e,t){let n=null;const s=r.content.map(i=>{if(i.type==="text"){const a=Qo(e,i.text);n===null&&(n=a);const c=Object.defineProperty({...i},"parsed_output",{value:a,enumerable:!1});return Object.defineProperty(c,"parsed",{get(){return t.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),a},enumerable:!1})}return i});return{...r,content:s,parsed_output:n}}function Qo(r,e){const t=Ei(r);if(t?.type!=="json_schema")return null;try{return"parse"in t?t.parse(e):JSON.parse(e)}catch(n){throw new x(`Failed to parse structured output: ${n}`)}}const Go=r=>{let e=0,t=[];for(;e<r.length;){let n=r[e];if(n==="\\"){e++;continue}if(n==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(n==="["){t.push({type:"paren",value:"["}),e++;continue}if(n==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(n===":"){t.push({type:"separator",value:":"}),e++;continue}if(n===","){t.push({type:"delimiter",value:","}),e++;continue}if(n==='"'){let c="",l=!1;for(n=r[++e];n!=='"';){if(e===r.length){l=!0;break}if(n==="\\"){if(e++,e===r.length){l=!0;break}c+=n+r[e],n=r[++e]}else c+=n,n=r[++e]}n=r[++e],l||t.push({type:"string",value:c});continue}if(n&&/\s/.test(n)){e++;continue}let i=/[0-9]/;if(n&&i.test(n)||n==="-"||n==="."){let c="";for(n==="-"&&(c+=n,n=r[++e]);n&&(i.test(n)||n==="."||n==="e"||n==="E"||(n==="-"||n==="+")&&(c[c.length-1]==="e"||c[c.length-1]==="E"));)c+=n,n=r[++e];t.push({type:"number",value:c});continue}let a=/[a-z]/i;if(n&&a.test(n)){let c="";for(;n&&a.test(n)&&e!==r.length;)c+=n,n=r[++e];if(c=="true"||c=="false"||c==="null")t.push({type:"name",value:c});else{e++;continue}continue}e++}return t},ze=r=>{if(r.length===0)return r;let e=r[r.length-1];switch(e.type){case"separator":return r=r.slice(0,r.length-1),ze(r);case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-"||t==="+"||t==="e"||t==="E")return r=r.slice(0,r.length-1),ze(r);case"string":let n=r[r.length-2];if(n?.type==="delimiter")return r=r.slice(0,r.length-1),ze(r);if(n?.type==="brace"&&n.value==="{")return r=r.slice(0,r.length-1),ze(r);break;case"delimiter":return r=r.slice(0,r.length-1),ze(r)}return r},Zo=r=>{let e=[];return r.map(t=>{t.type==="brace"&&(t.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),t.type==="paren"&&(t.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(t=>{t==="}"?r.push({type:"brace",value:"}"}):t==="]"&&r.push({type:"paren",value:"]"})}),r},ec=r=>{let e="";return r.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},tc=r=>JSON.parse(ec(Zo(ze(Go(r))))),Ye="__json_buf";function Ai(r,e){const t={};for(const i of Object.keys(r))i!=="input"&&(t[i]=r[i]);Object.defineProperty(t,Ye,{value:e,enumerable:!1,writable:!0});let n,s=!1;return Object.defineProperty(t,"input",{enumerable:!0,configurable:!0,get(){return s||(n=e?tc(e):{},s=!0),n}}),t}var K,me,Le,st,Kt,rt,it,Vt,at,le,ot,Jt,Xt,Ee,Yt,Qt,Gt,ct,Dn,wr,lt,Wn,Fn,Bn,br,qn;function Hn(r){return r.type==="tool_use"||r.type==="server_tool_use"||r.type==="mcp_tool_use"}class Rn{constructor(e,t){K.add(this),this.messages=[],this.receivedMessages=[],me.set(this,void 0),Le.set(this,null),this.controller=new AbortController,st.set(this,void 0),Kt.set(this,()=>{}),rt.set(this,()=>{}),it.set(this,void 0),Vt.set(this,()=>{}),at.set(this,()=>{}),le.set(this,{}),ot.set(this,!1),Jt.set(this,!1),Xt.set(this,!1),Ee.set(this,!1),Yt.set(this,void 0),Qt.set(this,void 0),Gt.set(this,void 0),ct.set(this,void 0),lt.set(this,n=>{if(w(this,Jt,!0),Qe(n)&&(n=new se),n instanceof se)return w(this,Xt,!0),this._emit("abort",n);if(n instanceof x)return this._emit("error",n);if(n instanceof Error){const s=new x(n.message);return s.cause=n,this._emit("error",s)}return this._emit("error",new x(String(n)))}),w(this,st,new Promise((n,s)=>{w(this,Kt,n,"f"),w(this,rt,s,"f")})),w(this,it,new Promise((n,s)=>{w(this,Vt,n,"f"),w(this,at,s,"f")})),o(this,st,"f").catch(()=>{}),o(this,it,"f").catch(()=>{}),w(this,Le,e),w(this,ct,t?.logger??console)}get response(){return o(this,Yt,"f")}get request_id(){return o(this,Qt,"f")}get workspace_id(){return o(this,Gt,"f")}async withResponse(){w(this,Ee,!0);const e=await o(this,st,"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 Rn(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n,{logger:s}={}){const i=new Rn(t,{logger:s});for(const a of t.messages)i._addMessageParam(a);return w(i,Le,{...t,stream:!0}),i._run(()=>i._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,[ai]:"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},o(this,lt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){const s=n?.signal;let i;s&&(s.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),s.addEventListener("abort",i));try{o(this,K,"m",Wn).call(this);const{response:a,data:c}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(a);for await(const l of c)o(this,K,"m",Fn).call(this,l);if(c.controller.signal?.aborted)throw new se;o(this,K,"m",Bn).call(this)}finally{s&&i&&s.removeEventListener("abort",i)}}_connected(e){this.ended||(w(this,Yt,e),w(this,Qt,e?.headers.get("request-id")),w(this,Gt,e?.headers.get("anthropic-workspace-id")),o(this,Kt,"f").call(this,e),this._emit("connect"))}get ended(){return o(this,ot,"f")}get errored(){return o(this,Jt,"f")}get aborted(){return o(this,Xt,"f")}abort(){this.controller.abort()}on(e,t){return(o(this,le,"f")[e]||(o(this,le,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=o(this,le,"f")[e];if(!n)return this;const s=n.findIndex(i=>i.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(o(this,le,"f")[e]||(o(this,le,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{w(this,Ee,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){w(this,Ee,!0),await o(this,it,"f")}get currentMessage(){return o(this,me,"f")}async finalMessage(){return await this.done(),o(this,K,"m",Dn).call(this)}async finalText(){return await this.done(),o(this,K,"m",wr).call(this)}_emit(e,...t){if(o(this,ot,"f"))return;e==="end"&&(w(this,ot,!0),o(this,Vt,"f").call(this));const n=o(this,le,"f")[e];if(n&&(o(this,le,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!o(this,Ee,"f")&&!n?.length&&Promise.reject(s),o(this,rt,"f").call(this,s),o(this,at,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!o(this,Ee,"f")&&!n?.length&&Promise.reject(s),o(this,rt,"f").call(this,s),o(this,at,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",o(this,K,"m",Dn).call(this))}async _fromReadableStream(e,t){const n=t?.signal;let s;n&&(n.aborted&&this.controller.abort(),s=this.controller.abort.bind(this.controller),n.addEventListener("abort",s));try{o(this,K,"m",Wn).call(this),this._connected(null);const i=ae.fromReadableStream(e,this.controller);for await(const a of i)o(this,K,"m",Fn).call(this,a);if(i.controller.signal?.aborted)throw new se;o(this,K,"m",Bn).call(this)}finally{n&&s&&n.removeEventListener("abort",s)}}[(me=new WeakMap,Le=new WeakMap,st=new WeakMap,Kt=new WeakMap,rt=new WeakMap,it=new WeakMap,Vt=new WeakMap,at=new WeakMap,le=new WeakMap,ot=new WeakMap,Jt=new WeakMap,Xt=new WeakMap,Ee=new WeakMap,Yt=new WeakMap,Qt=new WeakMap,Gt=new WeakMap,ct=new WeakMap,lt=new WeakMap,K=new WeakSet,Dn=function(){if(this.receivedMessages.length===0)throw new x("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},wr=function(){if(this.receivedMessages.length===0)throw new x("stream ended without producing a Message with role=assistant");const t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new x("stream ended without producing a content block with type=text");return t.join(" ")},Wn=function(){this.ended||w(this,me,void 0)},Fn=function(t){if(this.ended)return;const n=o(this,K,"m",br).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{const s=n.content.at(-1);switch(t.delta.type){case"text_delta":{s.type==="text"&&this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{s.type==="text"&&this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{if(Hn(s)&&o(this,le,"f").inputJson?.length){let i;try{i=s.input}catch(a){o(this,lt,"f").call(this,o(this,K,"m",qn).call(this,s,a));break}this._emit("inputJson",t.delta.partial_json,i)}break}case"thinking_delta":{s.type==="thinking"&&this._emit("thinking",t.delta.thinking,s.thinking);break}case"signature_delta":{s.type==="thinking"&&this._emit("signature",s.signature);break}case"compaction_delta":{s.type==="compaction"&&s.content&&this._emit("compaction",s.content);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(mr(n,o(this,Le,"f"),{logger:o(this,ct,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{w(this,me,n);break}}},Bn=function(){if(this.ended)throw new x("stream has ended, this shouldn't happen");const t=o(this,me,"f");if(!t)throw new x("request ended without sending any chunks");return w(this,me,void 0),mr(t,o(this,Le,"f"),{logger:o(this,ct,"f")})},br=function(t){let n=o(this,me,"f");if(t.type==="message_start"){if(n)throw new x(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new x(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.stop_details=t.delta.stop_details,n.usage.output_tokens=t.usage.output_tokens,t.delta.container!=null&&(n.container=t.delta.container),t.context_management!=null&&(n.context_management=t.context_management),t.input_transformations!=null&&(n.input_transformations=t.input_transformations),t.usage.input_tokens!=null&&(n.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(n.usage.server_tool_use=t.usage.server_tool_use),t.usage.iterations!=null&&(n.usage.iterations=t.usage.iterations),t.usage.fallback_credit!=null&&(n.usage.fallback_credit=t.usage.fallback_credit),t.usage.output_tokens_details!=null&&(n.usage.output_tokens_details=t.usage.output_tokens_details),n;case"content_block_start":return n.content.push(t.content_block),t.content_block.type==="fallback"&&(n.model=t.content_block.to.model),n;case"content_block_delta":{const s=n.content.at(t.index);switch(t.delta.type){case"text_delta":{s?.type==="text"&&(n.content[t.index]={...s,text:(s.text||"")+t.delta.text});break}case"citations_delta":{s?.type==="text"&&(n.content[t.index]={...s,citations:[...s.citations??[],t.delta.citation]});break}case"input_json_delta":{if(s&&Hn(s)){const i=(s[Ye]||"")+t.delta.partial_json;n.content[t.index]=Ai(s,i)}break}case"thinking_delta":{s?.type==="thinking"&&(n.content[t.index]={...s,thinking:s.thinking+t.delta.thinking});break}case"signature_delta":{s?.type==="thinking"&&(n.content[t.index]={...s,signature:t.delta.signature});break}case"compaction_delta":{s?.type==="compaction"&&(n.content[t.index]={...s,content:(s.content||"")+t.delta.content,encrypted_content:t.delta.encrypted_content});break}default:t.delta}return n}case"content_block_stop":{const s=n.content.at(t.index);if(s&&Hn(s)&&Ye in s){let i;try{i=s.input}catch(a){i={},o(this,lt,"f").call(this,o(this,K,"m",qn).call(this,s,a))}Object.defineProperty(s,"input",{value:i,enumerable:!0,configurable:!0,writable:!0})}return n}}},qn=function(t,n){const s=t[Ye];return new x(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${n}. JSON: ${s}`)},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("streamEvent",s=>{const i=t.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(const i of t)i.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const i of t)i.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((i,a)=>t.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new ae(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function yr(){let r,e;return{promise:new Promise((n,s)=>{r=n,e=s}),resolve:r,reject:e}}const nc=1e5,sc=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
11
+ 1. Task Overview
12
+ The user's core request and success criteria
13
+ Any clarifications or constraints they specified
14
+ 2. Current State
15
+ What has been completed so far
16
+ Files created, modified, or analyzed (with paths if relevant)
17
+ Key outputs or artifacts produced
18
+ 3. Important Discoveries
19
+ Technical constraints or requirements uncovered
20
+ Decisions made and their rationale
21
+ Errors encountered and how they were resolved
22
+ What approaches were tried that didn't work (and why)
23
+ 4. Next Steps
24
+ Specific actions needed to complete the task
25
+ Any blockers or open questions to resolve
26
+ Priority order if multiple steps remain
27
+ 5. Context to Preserve
28
+ User preferences or style requirements
29
+ Domain-specific details that aren't obvious
30
+ Any promises made to the user
31
+ Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
32
+ Wrap your summary in <summary></summary> tags.`;var dt,Ne,Te,D,V,X,fe,we,ut,kr,ss;class Ii{constructor(e,t,n){dt.add(this),this.client=e,Ne.set(this,!1),Te.set(this,!1),D.set(this,void 0),V.set(this,void 0),X.set(this,void 0),fe.set(this,void 0),we.set(this,void 0),ut.set(this,0),w(this,D,{params:{...t,messages:structuredClone(t.messages)}});const s=oi(t.tools,t.messages);w(this,V,{...n,headers:u([ts("BetaToolRunner"),s.length?{[It]:s.join(", ")}:void 0,n?.headers])}),w(this,we,yr()),t.compactionControl?.enabled&&console.warn('Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction')}async*[(Ne=new WeakMap,Te=new WeakMap,D=new WeakMap,V=new WeakMap,X=new WeakMap,fe=new WeakMap,we=new WeakMap,ut=new WeakMap,dt=new WeakSet,kr=async function(){const t=o(this,D,"f").params.compactionControl;if(!t||!t.enabled)return!1;let n=0;if(o(this,X,"f")!==void 0)try{const p=await o(this,X,"f");n=p.usage.input_tokens+(p.usage.cache_creation_input_tokens??0)+(p.usage.cache_read_input_tokens??0)+p.usage.output_tokens}catch{return!1}const s=t.contextTokenThreshold??nc;if(n<s)return!1;const i=t.model??o(this,D,"f").params.model,a=t.summaryPrompt??sc,c=o(this,D,"f").params.messages;if(c[c.length-1].role==="assistant"){const p=c[c.length-1];if(Array.isArray(p.content)){const g=p.content.filter(h=>h.type!=="tool_use");g.length===0?c.pop():p.content=g}}const l=await this.client.beta.messages.create({model:i,messages:[...c,{role:"user",content:[{type:"text",text:a}]}],max_tokens:o(this,D,"f").params.max_tokens},{signal:o(this,V,"f").signal,headers:u([o(this,V,"f").headers,ts("compaction")])});if(l.content[0]?.type!=="text")throw new x("Expected text response for compaction");return o(this,D,"f").params.messages=[{role:"user",content:l.content}],!0},Symbol.asyncIterator)](){var e;if(o(this,Ne,"f"))throw new x("Cannot iterate over a consumed stream");w(this,Ne,!0),w(this,Te,!0),w(this,fe,void 0);try{for(;;){let t;try{if(o(this,D,"f").params.max_iterations&&o(this,ut,"f")>=o(this,D,"f").params.max_iterations)break;w(this,Te,!1,"f"),w(this,fe,void 0,"f"),w(this,ut,(e=o(this,ut,"f"),e++,e),"f"),w(this,X,void 0,"f");const{max_iterations:n,compactionControl:s,...i}=o(this,D,"f").params;if(i.stream?(t=this.client.beta.messages.stream({...i},o(this,V,"f")),w(this,X,t.finalMessage(),"f"),o(this,X,"f").catch(()=>{}),yield t):(w(this,X,this.client.beta.messages.create({...i,stream:!1},o(this,V,"f")),"f"),yield o(this,X,"f")),!await o(this,dt,"m",kr).call(this)){if(!o(this,Te,"f")){const l=await o(this,X,"f"),p=dc(l.stop_reason);o(this,D,"f").params.messages.push({role:l.role,content:l.content});const{container:g}=o(this,D,"f").params;if(l.container&&(g==null?o(this,D,"f").params.container=l.container.id:typeof g=="object"&&g.id==null&&(o(this,D,"f").params.container={...g,id:l.container.id})),p==="stop")break;if(p==="resume")continue}const c=await o(this,dt,"m",ss).call(this,o(this,D,"f").params.messages.at(-1));if(c)o(this,D,"f").params.messages.push(c);else if(!o(this,Te,"f"))break}}finally{t&&t.abort()}}if(!o(this,X,"f"))throw new x("ToolRunner concluded without a message from the server");o(this,we,"f").resolve(await o(this,X,"f"))}catch(t){throw w(this,Ne,!1),o(this,we,"f").promise.catch(()=>{}),o(this,we,"f").reject(t),w(this,we,yr()),t}}setMessagesParams(e){typeof e=="function"?o(this,D,"f").params=e(o(this,D,"f").params):o(this,D,"f").params=e,w(this,Te,!0),w(this,fe,void 0)}setRequestOptions(e){typeof e=="function"?w(this,V,e(o(this,V,"f"))):w(this,V,{...o(this,V,"f"),...e})}async generateToolResponse(e=o(this,V,"f").signal){const t=await o(this,X,"f")??this.params.messages.at(-1);return t?o(this,dt,"m",ss).call(this,t,e):null}done(){return o(this,we,"f").promise}async runUntilDone(){if(!o(this,Ne,"f"))for await(const e of this);return this.done()}get params(){return o(this,D,"f").params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}}ss=async function(e,t=o(this,V,"f").signal){return o(this,fe,"f")!==void 0?o(this,fe,"f"):(w(this,fe,rc(o(this,D,"f").params,e,{...o(this,V,"f"),signal:t})),o(this,fe,"f"))};async function rc(r,e=r.messages.at(-1),t){if(!e||e.role!=="assistant"||!e.content||typeof e.content=="string")return null;const n=e.content.filter(a=>a.type==="tool_use");if(n.length===0)return null;const s=ac(r);return{role:"user",content:await Promise.all(n.map(async a=>{const c=r.tools.find(l=>("name"in l?l.name:"mcp_server_name"in l?l.mcp_server_name:l.type)===a.name);if(!c||!("run"in c)||!s.has(a.name))return ic(a);try{let l=a.input;"parse"in c&&c.parse&&(l=c.parse(l));const p=await c.run(l,{toolUse:a,toolUseBlock:a,signal:t?.signal});return{type:"tool_result",tool_use_id:a.id,content:p}}catch(l){return{type:"tool_result",tool_use_id:a.id,content:l instanceof vs?l.content:`Error: ${l instanceof Error?l.message:String(l)}`,is_error:!0}}}))}}function ic(r){return{type:"tool_result",tool_use_id:r.id,content:`Error: Tool '${r.name}' not found`,is_error:!0}}function ac(r){const e=new Set;for(const t of r.tools)"run"in t&&e.add(t.name);for(const t of r.messages)if(!(t.role!=="system"||typeof t.content=="string"))for(const n of t.content)oc(n,e);return e}function oc(r,e){switch(r.type){case"tool_removal":case"tool_addition":cc(r,e);break}}function cc(r,e){const t=lc(r.tool);t!==void 0&&(r.type==="tool_removal"?e.delete(t):e.add(t))}function lc(r){switch(r.type){case"tool_reference":return r.name;default:return}}function dc(r){if(r===null)return"stop";switch(r){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 Sr={},uc=["claude-mythos-preview","claude-opus-4-6"];let $t=class extends E{constructor(){super(...arguments),this.batches=new xi(this._client)}create(e,t){const n=vr(e),{betas:s,user_profile_id:i,workspace_id:a,...c}=n;c.model in Sr&&console.warn(`The model '${c.model}' is deprecated and will reach end-of-life on ${Sr[c.model]}
33
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),uc.includes(c.model)&&c.thinking&&c.thinking.type==="enabled"&&console.warn(`Using Claude with ${c.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(!c.stream&&l==null){const g=Ri[c.model]??void 0;l=this._client.calculateNonstreamingTimeout(c.max_tokens,g)}const p=ci(c.tools,c.messages);return this._client.post("/v1/messages?beta=true",{body:c,timeout:l??6e5,...t,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-user-profile-id":i}:void 0,...a!=null?{"anthropic-workspace-id":a}:void 0},p,t?.headers]),stream:n.stream??!1})}parse(e,t){return t={...t,headers:u([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},t?.headers])},this.create(e,t).then(n=>Ti(n,e,{logger:this._client.logger??console}))}stream(e,t){return Rn.createMessage(this,e,t)}countTokens(e,t){const n=vr(e),{betas:s,user_profile_id:i,workspace_id:a,...c}=n;return this._client.post("/v1/messages/count_tokens?beta=true",{body:c,...t,headers:u([{"anthropic-beta":[...s??[],"token-counting-2024-11-01"].toString(),...i!=null?{"anthropic-user-profile-id":i}:void 0,...a!=null?{"anthropic-workspace-id":a}:void 0},t?.headers])})}toolRunner(e,t){return new Ii(this._client,e,t)}};function vr(r){if(!r.output_format)return r;if(r.output_config?.format)throw new x("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");const{output_format:e,...t}=r;return{...t,output_config:{...r.output_config,format:e}}}$t.Batches=xi;$t.BetaToolRunner=Ii;$t.ToolError=vs;class Mi extends E{retrieve(e,t){return this._client.get(_`/v1/organizations/api_keys/${e}?beta=true`,t)}update(e,t,n){return this._client.post(_`/v1/organizations/api_keys/${e}?beta=true`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/v1/organizations/api_keys?beta=true",pe,{query:e,...t})}}class $i extends E{retrieve(e){return this._client.get("/v1/organizations/compliance_settings?beta=true",e)}update(e,t){return this._client.post("/v1/organizations/compliance_settings?beta=true",{body:e,...t})}}class Pi extends E{create(e,t){return this._client.post("/v1/organizations/external_keys?beta=true",{body:e,...t})}retrieve(e,t){return this._client.get(_`/v1/organizations/external_keys/${e}?beta=true`,t)}update(e,t,n){return this._client.post(_`/v1/organizations/external_keys/${e}?beta=true`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/v1/organizations/external_keys?beta=true",$,{query:e,...t})}delete(e,t){return this._client.delete(_`/v1/organizations/external_keys/${e}?beta=true`,t)}validate(e,t){return this._client.post(_`/v1/organizations/external_keys/${e}/validate?beta=true`,t)}}class Oi extends E{create(e,t){return this._client.post("/v1/organizations/invites?beta=true",{body:e,...t})}retrieve(e,t){return this._client.get(_`/v1/organizations/invites/${e}?beta=true`,t)}list(e={},t){return this._client.getAPIList("/v1/organizations/invites?beta=true",pe,{query:e,...t})}delete(e,t){return this._client.delete(_`/v1/organizations/invites/${e}?beta=true`,t)}}let Ci=class extends E{list(e={},t){return this._client.getAPIList("/v1/organizations/rate_limits?beta=true",$,{query:e,...t})}};class Li extends E{retrieve(e,t){return this._client.get(_`/v1/organizations/users/${e}?beta=true`,t)}update(e,t,n){return this._client.post(_`/v1/organizations/users/${e}?beta=true`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/v1/organizations/users?beta=true",pe,{query:e,...t})}remove(e,t){return this._client.delete(_`/v1/organizations/users/${e}?beta=true`,t)}}class Ni extends E{create(e,t){const{betas:n,...s}=e;return this._client.post("/v1/organizations/federation_issuers?beta=true",{body:s,...t,headers:u([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}retrieve(e,t={},n){const{betas:s}=t??{};return this._client.get(_`/v1/organizations/federation_issuers/${e}?beta=true`,{...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers])})}update(e,t,n){const{betas:s,...i}=t;return this._client.post(_`/v1/organizations/federation_issuers/${e}?beta=true`,{body:i,...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers])})}list(e={},t){const{betas:n,...s}=e??{};return this._client.getAPIList("/v1/organizations/federation_issuers?beta=true",$,{query:s,...t,headers:u([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}archive(e,t={},n){const{betas:s}=t??{};return this._client.post(_`/v1/organizations/federation_issuers/${e}/archive?beta=true`,{...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers])})}}let Di=class extends E{list(e,t={},n){const{betas:s,...i}=t??{};return this._client.getAPIList(_`/v1/organizations/federation_rules/${e}/workspaces?beta=true`,$,{query:i,...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers])})}add(e,t,n){const{betas:s,...i}=t;return this._client.post(_`/v1/organizations/federation_rules/${e}/workspaces?beta=true`,{body:i,...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers])})}remove(e,t,n){const{federation_rule_id:s,betas:i}=t;return this._client.delete(_`/v1/organizations/federation_rules/${s}/workspaces/${e}?beta=true`,{...n,headers:u([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},n?.headers])})}};class Es extends E{constructor(){super(...arguments),this.workspaces=new Di(this._client)}create(e,t){const{betas:n,...s}=e;return this._client.post("/v1/organizations/federation_rules?beta=true",{body:s,...t,headers:u([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}retrieve(e,t={},n){const{betas:s}=t??{};return this._client.get(_`/v1/organizations/federation_rules/${e}?beta=true`,{...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers])})}update(e,t,n){const{betas:s,...i}=t;return this._client.post(_`/v1/organizations/federation_rules/${e}?beta=true`,{body:i,...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers])})}list(e={},t){const{betas:n,...s}=e??{};return this._client.getAPIList("/v1/organizations/federation_rules?beta=true",$,{query:s,...t,headers:u([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}archive(e,t={},n){const{betas:s}=t??{};return this._client.post(_`/v1/organizations/federation_rules/${e}/archive?beta=true`,{...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers])})}}Es.Workspaces=Di;class Mn extends E{constructor(){super(...arguments),this.issuers=new Ni(this._client),this.rules=new Es(this._client)}}Mn.Issuers=Ni;Mn.Rules=Es;let Wi=class extends E{list(e,t={},n){const{betas:s,...i}=t??{};return this._client.getAPIList(_`/v1/organizations/service_accounts/${e}/workspaces?beta=true`,$,{query:i,...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers])})}add(e,t,n){const{betas:s,...i}=t;return this._client.post(_`/v1/organizations/service_accounts/${e}/workspaces?beta=true`,{body:i,...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers])})}remove(e,t,n){const{service_account_id:s,betas:i}=t;return this._client.delete(_`/v1/organizations/service_accounts/${s}/workspaces/${e}?beta=true`,{...n,headers:u([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},n?.headers])})}},Ts=class extends E{constructor(){super(...arguments),this.workspaces=new Wi(this._client)}create(e,t){const{betas:n,...s}=e;return this._client.post("/v1/organizations/service_accounts?beta=true",{body:s,...t,headers:u([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}retrieve(e,t={},n){const{betas:s}=t??{};return this._client.get(_`/v1/organizations/service_accounts/${e}?beta=true`,{...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers])})}update(e,t,n){const{betas:s,...i}=t;return this._client.post(_`/v1/organizations/service_accounts/${e}?beta=true`,{body:i,...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers])})}list(e={},t){const{betas:n,...s}=e??{};return this._client.getAPIList("/v1/organizations/service_accounts?beta=true",$,{query:s,...t,headers:u([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}archive(e,t={},n){const{betas:s}=t??{};return this._client.post(_`/v1/organizations/service_accounts/${e}/archive?beta=true`,{...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers])})}};Ts.Workspaces=Wi;class Fi extends E{retrieve(e,t,n){const{workspace_id:s}=t;return this._client.get(_`/v1/organizations/workspaces/${s}/members/${e}?beta=true`,n)}update(e,t,n){const{workspace_id:s,...i}=t;return this._client.post(_`/v1/organizations/workspaces/${s}/members/${e}?beta=true`,{body:i,...n})}list(e,t={},n){return this._client.getAPIList(_`/v1/organizations/workspaces/${e}/members?beta=true`,pe,{query:t,...n})}add(e,t,n){return this._client.post(_`/v1/organizations/workspaces/${e}/members?beta=true`,{body:t,...n})}remove(e,t,n){const{workspace_id:s}=t;return this._client.delete(_`/v1/organizations/workspaces/${s}/members/${e}?beta=true`,n)}}class Bi extends E{list(e,t={},n){return this._client.getAPIList(_`/v1/organizations/workspaces/${e}/rate_limits?beta=true`,$,{query:t,...n})}}class qi extends E{retrieve(e,t,n){const{workspace_id:s,betas:i}=t;return this._client.get(_`/v1/organizations/workspaces/${s}/service_accounts/${e}?beta=true`,{...n,headers:u([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},n?.headers])})}update(e,t,n){const{workspace_id:s,betas:i,...a}=t;return this._client.post(_`/v1/organizations/workspaces/${s}/service_accounts/${e}?beta=true`,{body:a,...n,headers:u([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},n?.headers])})}list(e,t={},n){const{betas:s,...i}=t??{};return this._client.getAPIList(_`/v1/organizations/workspaces/${e}/service_accounts?beta=true`,$,{query:i,...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers])})}add(e,t,n){const{betas:s,...i}=t;return this._client.post(_`/v1/organizations/workspaces/${e}/service_accounts?beta=true`,{body:i,...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers])})}remove(e,t,n){const{workspace_id:s,betas:i}=t;return this._client.delete(_`/v1/organizations/workspaces/${s}/service_accounts/${e}?beta=true`,{...n,headers:u([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},n?.headers])})}}class Pt extends E{constructor(){super(...arguments),this.rateLimits=new Bi(this._client),this.members=new Fi(this._client),this.serviceAccounts=new qi(this._client)}create(e,t){const{betas:n,...s}=e;return this._client.post("/v1/organizations/workspaces?beta=true",{body:s,...t,headers:u([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}retrieve(e,t){return this._client.get(_`/v1/organizations/workspaces/${e}?beta=true`,t)}update(e,t,n){return this._client.post(_`/v1/organizations/workspaces/${e}?beta=true`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/v1/organizations/workspaces?beta=true",pe,{query:e,...t})}archive(e,t){return this._client.post(_`/v1/organizations/workspaces/${e}/archive?beta=true`,t)}}Pt.RateLimits=Bi;Pt.Members=Fi;Pt.ServiceAccounts=qi;class oe extends E{constructor(){super(...arguments),this.apiKeys=new Mi(this._client),this.externalKeys=new Pi(this._client),this.federation=new Mn(this._client),this.invites=new Oi(this._client),this.serviceAccounts=new Ts(this._client),this.users=new Li(this._client),this.workspaces=new Pt(this._client),this.rateLimits=new Ci(this._client),this.complianceSettings=new $i(this._client)}retrieve(e){return this._client.get("/v1/organizations/me?beta=true",e)}}oe.APIKeys=Mi;oe.ExternalKeys=Pi;oe.Federation=Mn;oe.Invites=Oi;oe.ServiceAccounts=Ts;oe.Users=Li;oe.Workspaces=Pt;oe.RateLimits=Ci;oe.ComplianceSettings=$i;let As=class extends E{list(e,t={},n){const{betas:s,workspace_id:i,...a}=t??{};return this._client.getAPIList(_`/v1/sessions/${e}/events?beta=true`,$,{query:a,...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}send(e,t,n){const{betas:s,workspace_id:i,...a}=t;return this._client.post(_`/v1/sessions/${e}/events?beta=true`,{body:a,...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}stream(e,t={},n){const{betas:s,workspace_id:i,...a}=t??{};return this._client.get(_`/v1/sessions/${e}/events/stream?beta=true`,{query:a,...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers]),stream:!0})}toolRunner(e,t){return new xs(e,{...t,client:this._client})}};As.SessionToolRunner=xs;class Hi extends E{retrieve(e,t,n){const{session_id:s,betas:i,workspace_id:a}=t;return this._client.get(_`/v1/sessions/${s}/resources/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}update(e,t,n){const{session_id:s,betas:i,workspace_id:a,...c}=t;return this._client.post(_`/v1/sessions/${s}/resources/${e}?beta=true`,{body:c,...n,headers:u([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}list(e,t={},n){const{betas:s,workspace_id:i,...a}=t??{};return this._client.getAPIList(_`/v1/sessions/${e}/resources?beta=true`,$,{query:a,...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}delete(e,t,n){const{session_id:s,betas:i,workspace_id:a}=t;return this._client.delete(_`/v1/sessions/${s}/resources/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}add(e,t,n){const{betas:s,workspace_id:i,...a}=t;return this._client.post(_`/v1/sessions/${e}/resources?beta=true`,{body:a,...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}}class Ui extends E{list(e,t,n){const{session_id:s,betas:i,workspace_id:a,...c}=t;return this._client.getAPIList(_`/v1/sessions/${s}/threads/${e}/events?beta=true`,$,{query:c,...n,headers:u([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}stream(e,t,n){const{session_id:s,betas:i,workspace_id:a,...c}=t;return this._client.get(_`/v1/sessions/${s}/threads/${e}/stream?beta=true`,{query:c,...n,headers:u([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers]),stream:!0})}}class Is extends E{constructor(){super(...arguments),this.events=new Ui(this._client)}retrieve(e,t,n){const{session_id:s,betas:i,workspace_id:a}=t;return this._client.get(_`/v1/sessions/${s}/threads/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}list(e,t={},n){const{betas:s,workspace_id:i,...a}=t??{};return this._client.getAPIList(_`/v1/sessions/${e}/threads?beta=true`,$,{query:a,...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}archive(e,t,n){const{session_id:s,betas:i,workspace_id:a}=t;return this._client.post(_`/v1/sessions/${s}/threads/${e}/archive?beta=true`,{...n,headers:u([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}}Is.Events=Ui;class Ot extends E{constructor(){super(...arguments),this.events=new As(this._client),this.resources=new Hi(this._client),this.threads=new Is(this._client)}create(e,t){const{betas:n,workspace_id:s,...i}=e;return this._client.post("/v1/sessions?beta=true",{body:i,...t,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}retrieve(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.get(_`/v1/sessions/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}update(e,t,n){const{betas:s,workspace_id:i,...a}=t;return this._client.post(_`/v1/sessions/${e}?beta=true`,{body:a,...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}list(e={},t){const{betas:n,workspace_id:s,...i}=e??{};return this._client.getAPIList("/v1/sessions?beta=true",so,{query:i,...t,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.delete(_`/v1/sessions/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}archive(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.post(_`/v1/sessions/${e}/archive?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}}Ot.Events=As;Ot.Resources=Hi;Ot.Threads=Is;let ji=class extends E{create(e,t,n){const{betas:s,workspace_id:i,...a}=t;return this._client.post(_`/v1/skills/${e}/versions?beta=true`,Ze({body:a,...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])},this._client,!1))}retrieve(e,t,n){const{skill_id:s,betas:i,workspace_id:a}=t;return this._client.get(_`/v1/skills/${s}/versions/${e}?beta=true`,{...n,headers:u([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}list(e,t={},n){const{betas:s,workspace_id:i,...a}=t??{};return this._client.getAPIList(_`/v1/skills/${e}/versions?beta=true`,$,{query:a,...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}delete(e,t,n){const{skill_id:s,betas:i,workspace_id:a}=t;return this._client.delete(_`/v1/skills/${s}/versions/${e}?beta=true`,{...n,headers:u([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}download(e,t,n){const{skill_id:s,betas:i,workspace_id:a}=t;return this._client.get(_`/v1/skills/${s}/versions/${e}/content?beta=true`,{...n,headers:u([{Accept:"application/binary",...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers]),__binaryResponse:!0})}},Ms=class extends E{constructor(){super(...arguments),this.versions=new ji(this._client)}create(e,t){const{betas:n,workspace_id:s,...i}=e;return this._client.post("/v1/skills?beta=true",Ze({body:i,...t,headers:u([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])},this._client,!1))}retrieve(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.get(_`/v1/skills/${e}?beta=true`,{...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}list(e={},t){const{betas:n,workspace_id:s,...i}=e??{};return this._client.getAPIList("/v1/skills?beta=true",$,{query:i,...t,headers:u([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.delete(_`/v1/skills/${e}?beta=true`,{...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}};Ms.Versions=ji;class zi extends E{create(e,t,n){const{betas:s,workspace_id:i,...a}=t;return this._client.post(_`/v1/tunnels/${e}/certificates?beta=true`,{body:a,...n,headers:u([{"anthropic-beta":[...s??[],"mcp-tunnels-2026-06-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}retrieve(e,t,n){const{tunnel_id:s,betas:i,workspace_id:a}=t;return this._client.get(_`/v1/tunnels/${s}/certificates/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}list(e,t={},n){const{betas:s,workspace_id:i,...a}=t??{};return this._client.getAPIList(_`/v1/tunnels/${e}/certificates?beta=true`,$,{query:a,...n,headers:u([{"anthropic-beta":[...s??[],"mcp-tunnels-2026-06-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}archive(e,t,n){const{tunnel_id:s,betas:i,workspace_id:a}=t;return this._client.post(_`/v1/tunnels/${s}/certificates/${e}/archive?beta=true`,{...n,headers:u([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}}class $s extends E{constructor(){super(...arguments),this.certificates=new zi(this._client)}create(e,t){const{betas:n,workspace_id:s,...i}=e;return this._client.post("/v1/tunnels?beta=true",{body:i,...t,headers:u([{"anthropic-beta":[...n??[],"mcp-tunnels-2026-06-22"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}retrieve(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.get(_`/v1/tunnels/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"mcp-tunnels-2026-06-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}list(e={},t){const{betas:n,workspace_id:s,...i}=e??{};return this._client.getAPIList("/v1/tunnels?beta=true",$,{query:i,...t,headers:u([{"anthropic-beta":[...n??[],"mcp-tunnels-2026-06-22"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}archive(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.post(_`/v1/tunnels/${e}/archive?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"mcp-tunnels-2026-06-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}revealToken(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.post(_`/v1/tunnels/${e}/reveal_token?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"mcp-tunnels-2026-06-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}rotateToken(e,t,n){const{betas:s,workspace_id:i,...a}=t;return this._client.post(_`/v1/tunnels/${e}/rotate_token?beta=true`,{body:a,...n,headers:u([{"anthropic-beta":[...s??[],"mcp-tunnels-2026-06-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}}$s.Certificates=zi;class Ki extends E{create(e,t,n){const{betas:s,workspace_id:i,...a}=t;return this._client.post(_`/v1/vaults/${e}/credentials?beta=true`,{body:a,...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}retrieve(e,t,n){const{vault_id:s,betas:i,workspace_id:a}=t;return this._client.get(_`/v1/vaults/${s}/credentials/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}update(e,t,n){const{vault_id:s,betas:i,workspace_id:a,...c}=t;return this._client.post(_`/v1/vaults/${s}/credentials/${e}?beta=true`,{body:c,...n,headers:u([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}list(e,t={},n){const{betas:s,workspace_id:i,...a}=t??{};return this._client.getAPIList(_`/v1/vaults/${e}/credentials?beta=true`,$,{query:a,...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}delete(e,t,n){const{vault_id:s,betas:i,workspace_id:a}=t;return this._client.delete(_`/v1/vaults/${s}/credentials/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}archive(e,t,n){const{vault_id:s,betas:i,workspace_id:a}=t;return this._client.post(_`/v1/vaults/${s}/credentials/${e}/archive?beta=true`,{...n,headers:u([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}mcpOAuthValidate(e,t,n){const{vault_id:s,betas:i,workspace_id:a}=t;return this._client.post(_`/v1/vaults/${s}/credentials/${e}/mcp_oauth_validate?beta=true`,{...n,headers:u([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...a!=null?{"anthropic-workspace-id":a}:void 0},n?.headers])})}}class Ps extends E{constructor(){super(...arguments),this.credentials=new Ki(this._client)}create(e,t){const{betas:n,workspace_id:s,...i}=e;return this._client.post("/v1/vaults?beta=true",{body:i,...t,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}retrieve(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.get(_`/v1/vaults/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}update(e,t,n){const{betas:s,workspace_id:i,...a}=t;return this._client.post(_`/v1/vaults/${e}?beta=true`,{body:a,...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}list(e={},t){const{betas:n,workspace_id:s,...i}=e??{};return this._client.getAPIList("/v1/vaults?beta=true",$,{query:i,...t,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.delete(_`/v1/vaults/${e}?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}archive(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.post(_`/v1/vaults/${e}/archive?beta=true`,{...n,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}}Ps.Credentials=Ki;class U extends E{constructor(){super(...arguments),this.models=new ui(this._client),this.messages=new $t(this._client),this.agents=new ks(this._client),this.environments=new Rs(this._client),this.sessions=new Ot(this._client),this.deployments=new ri(this._client),this.deploymentRuns=new si(this._client),this.vaults=new Ps(this._client),this.memoryStores=new An(this._client),this.files=new di(this._client),this.skills=new Ms(this._client),this.webhooks=new fi(this._client),this.userProfiles=new hi(this._client),this.dreams=new ii(this._client),this.tunnels=new $s(this._client),this.organization=new oe(this._client)}}U.Models=ui;U.Messages=$t;U.Agents=ks;U.Environments=Rs;U.Sessions=Ot;U.Deployments=ri;U.DeploymentRuns=si;U.Vaults=Ps;U.MemoryStores=An;U.Files=di;U.Skills=Ms;U.Webhooks=fi;U.UserProfiles=hi;U.Dreams=ii;U.Tunnels=$s;U.Organization=oe;class Vi extends E{create(e,t){const{betas:n,workspace_id:s,...i}=e;return this._client.post("/v1/complete",{body:i,timeout:this._client._options.timeout??6e5,...t,headers:u([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers]),stream:e.stream??!1})}}class Ji extends E{list(e={},t){const{workspace_id:n,...s}=e??{};return this._client.getAPIList("/v1/files",$,{query:s,...t,headers:u([{...n!=null?{"anthropic-workspace-id":n}:void 0},t?.headers])})}delete(e,t={},n){const{workspace_id:s}=t??{};return this._client.delete(_`/v1/files/${e}`,{...n,headers:u([{...s!=null?{"anthropic-workspace-id":s}:void 0},n?.headers])})}download(e,t={},n){const{workspace_id:s}=t??{};return this._client.get(_`/v1/files/${e}/content`,{...n,headers:u([{Accept:"application/binary",...s!=null?{"anthropic-workspace-id":s}:void 0},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},n){const{workspace_id:s}=t??{};return this._client.get(_`/v1/files/${e}`,{...n,headers:u([{...s!=null?{"anthropic-workspace-id":s}:void 0},n?.headers])})}upload(e,t){const{workspace_id:n,...s}=e;return this._client.post("/v1/files",Ze({body:s,...t,headers:u([{...n!=null?{"anthropic-workspace-id":n}:void 0},li(s.file),t?.headers])},this._client))}}function Xi(r){return r?.output_config?.format}function xr(r,e,t){const n=Xi(e);return!e||!("parse"in(n??{}))?{...r,content:r.content.map(s=>s.type==="text"?Object.defineProperty({...s},"parsed_output",{value:null,enumerable:!1}):s),parsed_output:null}:Yi(r,e)}function Yi(r,e,t){let n=null;const s=r.content.map(i=>{if(i.type==="text"){const a=hc(e,i.text);return n===null&&(n=a),Object.defineProperty({...i},"parsed_output",{value:a,enumerable:!1})}return i});return{...r,content:s,parsed_output:n}}function hc(r,e){const t=Xi(r);if(t?.type!=="json_schema")return null;try{return"parse"in t?t.parse(e):JSON.parse(e)}catch(n){throw new x(`Failed to parse structured output: ${n}`)}}var te,be,De,ht,Zt,ft,pt,en,_t,de,gt,tn,nn,Ae,sn,rn,an,mt,Un,Rr,jn,zn,Kn,Vn,Er;function Jn(r){return r.type==="tool_use"||r.type==="server_tool_use"}class En{constructor(e,t){te.add(this),this.messages=[],this.receivedMessages=[],be.set(this,void 0),De.set(this,null),this.controller=new AbortController,ht.set(this,void 0),Zt.set(this,()=>{}),ft.set(this,()=>{}),pt.set(this,void 0),en.set(this,()=>{}),_t.set(this,()=>{}),de.set(this,{}),gt.set(this,!1),tn.set(this,!1),nn.set(this,!1),Ae.set(this,!1),sn.set(this,void 0),rn.set(this,void 0),an.set(this,void 0),mt.set(this,void 0),jn.set(this,n=>{if(w(this,tn,!0),Qe(n)&&(n=new se),n instanceof se)return w(this,nn,!0),this._emit("abort",n);if(n instanceof x)return this._emit("error",n);if(n instanceof Error){const s=new x(n.message);return s.cause=n,this._emit("error",s)}return this._emit("error",new x(String(n)))}),w(this,ht,new Promise((n,s)=>{w(this,Zt,n,"f"),w(this,ft,s,"f")})),w(this,pt,new Promise((n,s)=>{w(this,en,n,"f"),w(this,_t,s,"f")})),o(this,ht,"f").catch(()=>{}),o(this,pt,"f").catch(()=>{}),w(this,De,e),w(this,mt,t?.logger??console)}get response(){return o(this,sn,"f")}get request_id(){return o(this,rn,"f")}get workspace_id(){return o(this,an,"f")}async withResponse(){w(this,Ae,!0);const e=await o(this,ht,"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 En(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n,{logger:s}={}){const i=new En(t,{logger:s});for(const a of t.messages)i._addMessageParam(a);return w(i,De,{...t,stream:!0}),i._run(()=>i._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,[ai]:"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},o(this,jn,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){const s=n?.signal;let i;s&&(s.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),s.addEventListener("abort",i));try{o(this,te,"m",zn).call(this);const{response:a,data:c}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(a);for await(const l of c)o(this,te,"m",Kn).call(this,l);if(c.controller.signal?.aborted)throw new se;o(this,te,"m",Vn).call(this)}finally{s&&i&&s.removeEventListener("abort",i)}}_connected(e){this.ended||(w(this,sn,e),w(this,rn,e?.headers.get("request-id")),w(this,an,e?.headers.get("anthropic-workspace-id")),o(this,Zt,"f").call(this,e),this._emit("connect"))}get ended(){return o(this,gt,"f")}get errored(){return o(this,tn,"f")}get aborted(){return o(this,nn,"f")}abort(){this.controller.abort()}on(e,t){return(o(this,de,"f")[e]||(o(this,de,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=o(this,de,"f")[e];if(!n)return this;const s=n.findIndex(i=>i.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(o(this,de,"f")[e]||(o(this,de,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{w(this,Ae,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){w(this,Ae,!0),await o(this,pt,"f")}get currentMessage(){return o(this,be,"f")}async finalMessage(){return await this.done(),o(this,te,"m",Un).call(this)}async finalText(){return await this.done(),o(this,te,"m",Rr).call(this)}_emit(e,...t){if(o(this,gt,"f"))return;e==="end"&&(w(this,gt,!0),o(this,en,"f").call(this));const n=o(this,de,"f")[e];if(n&&(o(this,de,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!o(this,Ae,"f")&&!n?.length&&Promise.reject(s),o(this,ft,"f").call(this,s),o(this,_t,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!o(this,Ae,"f")&&!n?.length&&Promise.reject(s),o(this,ft,"f").call(this,s),o(this,_t,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",o(this,te,"m",Un).call(this))}async _fromReadableStream(e,t){const n=t?.signal;let s;n&&(n.aborted&&this.controller.abort(),s=this.controller.abort.bind(this.controller),n.addEventListener("abort",s));try{o(this,te,"m",zn).call(this),this._connected(null);const i=ae.fromReadableStream(e,this.controller);for await(const a of i)o(this,te,"m",Kn).call(this,a);if(i.controller.signal?.aborted)throw new se;o(this,te,"m",Vn).call(this)}finally{n&&s&&n.removeEventListener("abort",s)}}[(be=new WeakMap,De=new WeakMap,ht=new WeakMap,Zt=new WeakMap,ft=new WeakMap,pt=new WeakMap,en=new WeakMap,_t=new WeakMap,de=new WeakMap,gt=new WeakMap,tn=new WeakMap,nn=new WeakMap,Ae=new WeakMap,sn=new WeakMap,rn=new WeakMap,an=new WeakMap,mt=new WeakMap,jn=new WeakMap,te=new WeakSet,Un=function(){if(this.receivedMessages.length===0)throw new x("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Rr=function(){if(this.receivedMessages.length===0)throw new x("stream ended without producing a Message with role=assistant");const t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new x("stream ended without producing a content block with type=text");return t.join(" ")},zn=function(){this.ended||w(this,be,void 0)},Kn=function(t){if(this.ended)return;const n=o(this,te,"m",Er).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{const s=n.content.at(-1);switch(t.delta.type){case"text_delta":{s.type==="text"&&this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{s.type==="text"&&this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{Jn(s)&&o(this,de,"f").inputJson?.length&&this._emit("inputJson",t.delta.partial_json,s.input);break}case"thinking_delta":{s.type==="thinking"&&this._emit("thinking",t.delta.thinking,s.thinking);break}case"signature_delta":{s.type==="thinking"&&this._emit("signature",s.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(xr(n,o(this,De,"f"),{logger:o(this,mt,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{w(this,be,n);break}}},Vn=function(){if(this.ended)throw new x("stream has ended, this shouldn't happen");const t=o(this,be,"f");if(!t)throw new x("request ended without sending any chunks");return w(this,be,void 0),xr(t,o(this,De,"f"),{logger:o(this,mt,"f")})},Er=function(t){let n=o(this,be,"f");if(t.type==="message_start"){if(n)throw new x(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new x(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.stop_details=t.delta.stop_details,n.usage.output_tokens=t.usage.output_tokens,t.delta.container!=null&&(n.container=t.delta.container),t.usage.input_tokens!=null&&(n.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(n.usage.server_tool_use=t.usage.server_tool_use),t.usage.output_tokens_details!=null&&(n.usage.output_tokens_details=t.usage.output_tokens_details),n;case"content_block_start":return n.content.push({...t.content_block}),n;case"content_block_delta":{const s=n.content.at(t.index);switch(t.delta.type){case"text_delta":{s?.type==="text"&&(n.content[t.index]={...s,text:(s.text||"")+t.delta.text});break}case"citations_delta":{s?.type==="text"&&(n.content[t.index]={...s,citations:[...s.citations??[],t.delta.citation]});break}case"input_json_delta":{if(s&&Jn(s)){const i=(s[Ye]||"")+t.delta.partial_json;n.content[t.index]=Ai(s,i)}break}case"thinking_delta":{s?.type==="thinking"&&(n.content[t.index]={...s,thinking:s.thinking+t.delta.thinking});break}case"signature_delta":{s?.type==="thinking"&&(n.content[t.index]={...s,signature:t.delta.signature});break}default:t.delta}return n}case"content_block_stop":{const s=n.content.at(t.index);return s&&Jn(s)&&Ye in s&&Object.defineProperty(s,"input",{value:s.input,enumerable:!0,configurable:!0,writable:!0}),n}}},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("streamEvent",s=>{const i=t.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(const i of t)i.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const i of t)i.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((i,a)=>t.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new ae(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class Qi extends E{create(e,t){const{user_profile_id:n,workspace_id:s,...i}=e;return this._client.post("/v1/messages/batches",{body:i,...t,headers:u([{...n!=null?{"anthropic-user-profile-id":n}:void 0,...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}retrieve(e,t={},n){const{workspace_id:s}=t??{};return this._client.get(_`/v1/messages/batches/${e}`,{...n,headers:u([{...s!=null?{"anthropic-workspace-id":s}:void 0},n?.headers])})}list(e={},t){const{workspace_id:n,...s}=e??{};return this._client.getAPIList("/v1/messages/batches",pe,{query:s,...t,headers:u([{...n!=null?{"anthropic-workspace-id":n}:void 0},t?.headers])})}delete(e,t={},n){const{workspace_id:s}=t??{};return this._client.delete(_`/v1/messages/batches/${e}`,{...n,headers:u([{...s!=null?{"anthropic-workspace-id":s}:void 0},n?.headers])})}cancel(e,t={},n){const{workspace_id:s}=t??{};return this._client.post(_`/v1/messages/batches/${e}/cancel`,{...n,headers:u([{...s!=null?{"anthropic-workspace-id":s}:void 0},n?.headers])})}async results(e,t={},n){const s=await this.retrieve(e,t,n);if(!s.results_url)throw new x(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);const{workspace_id:i}=t??{};return this._client.get(s.results_url,{...n,headers:u([{Accept:"application/binary",...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((a,c)=>In.fromResponse(c.response,c.controller))}}class Os extends E{constructor(){super(...arguments),this.batches=new Qi(this._client)}create(e,t){const{user_profile_id:n,workspace_id:s,...i}=e;i.model in Tr&&console.warn(`The model '${i.model}' is deprecated and will reach end-of-life on ${Tr[i.model]}
34
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),fc.includes(i.model)&&i.thinking&&i.thinking.type==="enabled"&&console.warn(`Using Claude with ${i.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 a=t?.timeout??this._client._options.timeout;if(!i.stream&&a==null){const l=Ri[i.model]??void 0;a=this._client.calculateNonstreamingTimeout(i.max_tokens,l)}const c=ci(i.tools,i.messages);return this._client.post("/v1/messages",{body:i,timeout:a??6e5,...t,headers:u([{...n!=null?{"anthropic-user-profile-id":n}:void 0,...s!=null?{"anthropic-workspace-id":s}:void 0},c,t?.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then(n=>Yi(n,e,{logger:this._client.logger??console}))}stream(e,t){return En.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){const{user_profile_id:n,workspace_id:s,...i}=e;return this._client.post("/v1/messages/count_tokens",{body:i,...t,headers:u([{...n!=null?{"anthropic-user-profile-id":n}:void 0,...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}}const Tr={},fc=["claude-mythos-preview","claude-opus-4-6"];Os.Batches=Qi;class Gi extends E{retrieve(e,t={},n){const{betas:s,workspace_id:i}=t??{};return this._client.get(_`/v1/models/${e}`,{...n,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}list(e={},t){const{betas:n,workspace_id:s,...i}=e??{};return this._client.getAPIList("/v1/models",pe,{query:i,...t,headers:u([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...s!=null?{"anthropic-workspace-id":s}:void 0},t?.headers])})}}class Zi extends E{create(e,t,n){const{workspace_id:s,...i}=t;return this._client.post(_`/v1/skills/${e}/versions`,Ze({body:i,...n,headers:u([{...s!=null?{"anthropic-workspace-id":s}:void 0},n?.headers])},this._client,!1))}retrieve(e,t,n){const{skill_id:s,workspace_id:i}=t;return this._client.get(_`/v1/skills/${s}/versions/${e}`,{...n,headers:u([{...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}list(e,t={},n){const{workspace_id:s,...i}=t??{};return this._client.getAPIList(_`/v1/skills/${e}/versions`,$,{query:i,...n,headers:u([{...s!=null?{"anthropic-workspace-id":s}:void 0},n?.headers])})}delete(e,t,n){const{skill_id:s,workspace_id:i}=t;return this._client.delete(_`/v1/skills/${s}/versions/${e}`,{...n,headers:u([{...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}}class Cs extends E{constructor(){super(...arguments),this.versions=new Zi(this._client)}create(e,t){const{workspace_id:n,...s}=e;return this._client.post("/v1/skills",Ze({body:s,...t,headers:u([{...n!=null?{"anthropic-workspace-id":n}:void 0},t?.headers])},this._client,!1))}retrieve(e,t={},n){const{workspace_id:s}=t??{};return this._client.get(_`/v1/skills/${e}`,{...n,headers:u([{...s!=null?{"anthropic-workspace-id":s}:void 0},n?.headers])})}list(e={},t){const{workspace_id:n,...s}=e??{};return this._client.getAPIList("/v1/skills",$,{query:s,...t,headers:u([{...n!=null?{"anthropic-workspace-id":n}:void 0},t?.headers])})}delete(e,t={},n){const{workspace_id:s}=t??{};return this._client.delete(_`/v1/skills/${e}`,{...n,headers:u([{...s!=null?{"anthropic-workspace-id":s}:void 0},n?.headers])})}}Cs.Versions=Zi;var rs,Ls,gn,ea;const ta="\\n\\nHuman:",na="\\n\\nAssistant:";class F{get credentials(){return this._authState.provider}constructor({baseURL:e=M("ANTHROPIC_BASE_URL"),apiKey:t,authToken:n,webhookKey:s=M("ANTHROPIC_WEBHOOK_SIGNING_KEY")??null,...i}={}){if(rs.add(this),this._requestAuthFlags=new WeakMap,gn.set(this,void 0),t===void 0&&(t=i.profile!=null?null:M("ANTHROPIC_API_KEY")??null),n===void 0&&(n=i.profile!=null?null:M("ANTHROPIC_AUTH_TOKEN")??null),i.profile!=null&&(i.credentials!=null||i.config!=null))throw new TypeError("Pass at most one of `profile`, `credentials`, or `config`.");const a={apiKey:t,authToken:n,webhookKey:s,...i,baseURL:e||"https://api.anthropic.com"};if(!a.dangerouslyAllowBrowser&&ca())throw new x(`It looks like you're running in a browser-like environment.
35
+
36
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
37
+ If you understand the risks and have appropriate mitigations in place,
38
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
39
+
40
+ new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
41
+ `);this.baseURL=a.baseURL,this._baseURLIsExplicit=i.__baseURLIsExplicit??!!e,this.timeout=a.timeout??Ls.DEFAULT_TIMEOUT,this.logger=a.logger??console,this.logLevel=Sn,this.logLevel=Qn(a.logLevel,"ClientOptions.logLevel",P(this))??Qn(M("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",P(this))??Sn,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??_a(),w(this,gn,ma),this.middleware=[...a.middleware??[]];const c=M("ANTHROPIC_CUSTOM_HEADERS");if(c){const p={};for(const g of c.split(`
42
+ `)){const h=g.indexOf(":");h>=0&&(p[g.substring(0,h).trim()]=g.substring(h+1).trim())}a.defaultHeaders={...p,...a.defaultHeaders}}const l=i.__auth;if(delete a.__auth,delete a.__baseURLIsExplicit,this._options=a,this.apiKey=typeof t=="string"?t:null,this.authToken=n,this.webhookKey=s,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=a.credentials??null;if(p)this._authState.provider=p,this._authState.tokenCache=this._makeTokenCache(p);else if(a.config!=null){const g=Kr(a.config,this._credentialResolverOptions());this._authState.provider=g.provider,this._authState.tokenCache=this._makeTokenCache(g.provider),this._authState.extraHeaders=g.extraHeaders,this._applyCredentialBaseURL(g.baseURL)}else a.profile!=null?this._authState.resolution=this._resolveDefaultCredentials(a.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=>{P(this).debug("credential cache write failed (best-effort)",e)},onSafetyWarning:e=>{P(this).warn(e)}}}_credentialsFetch(){return Zs(this.fetch,this.middleware,void 0,this)}_makeTokenCache(e){return new Pa(e,t=>{P(this).debug("advisory token refresh failed; serving cached token",t)})}withOptions(e){const t="credentials"in e||"config"in e||"profile"in e,n="apiKey"in e||"authToken"in e||t,s={...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:n?void 0:this._authState,__baseURLIsExplicit:"baseURL"in e?!0:this._baseURLIsExplicit};return new this.constructor(s)}async _resolveDefaultCredentials(e){try{const t=await za(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 x(`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,u([{Authorization:`Bearer ${t}`}])}return u([await this.apiKeyAuth(e),await this.bearerAuth(e)])}}async apiKeyAuth(e){if(this.apiKey!=null)return u([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return u([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return xa(e)}getUserAgent(){return`Anthropic/JS ${ve}`}defaultIdempotencyKey(){return`stainless-node-retry-${mn()}`}makeStatusError(e,t,n,s){return q.generate(e,t,n,s)}buildURL(e,t,n){const s=!o(this,rs,"m",ea).call(this)&&n||this.baseURL,i=ia(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),c=Object.fromEntries(i.searchParams);return(!Ws(a)||!Ws(c))&&(t={...c,...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new x("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){if(this._authState.tokenCache&&this.apiKey==null){const s=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(const[a,c]of Object.entries(this._authState.extraHeaders))s.has(a)||s.set(a,c);s.get("anthropic-beta")?.split(",").map(a=>a.trim())?.includes(kn)||s.append("anthropic-beta",kn),e.headers=s}}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,n){return this.request(Promise.resolve(n).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new At(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){const s=await e,i=s.maxRetries??this.maxRetries;t==null&&(t=i,this._requestAuthFlags.delete(s)),await this.prepareOptions(s);const{req:a,url:c,timeout:l}=await this.buildRequest(s,{retryCount:i-t}),p="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=n===void 0?"":`, retryOf: ${n}`,h=Date.now();if(s.signal?.aborted)throw new se;const f=new AbortController,d=await this.fetchWithTimeout(c,a,l,f,s,{requestLogID:p,retryOfRequestLogID:n}).catch(wn),m=Date.now();if(d instanceof globalThis.Error){$e(f);const S=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new se;const y=Qe(d)||/timed? ?out/i.test(String(d)+("cause"in d?String(d.cause):"")),k=this.middleware.length>0||!!s.middleware?.length||this.backendMiddleware().length>0;if(k&&!y&&!eo(d))throw P(this).info(`[${p}] middleware error (not retryable)`),P(this).debug(`[${p}] middleware error (not retryable)`,ye({retryOfRequestLogID:n,url:c,durationMs:m-h,message:d.message})),d;if(t)return P(this).info(`[${p}] connection ${y?"timed out":"failed"} - ${S}`),P(this).debug(`[${p}] connection ${y?"timed out":"failed"} (${S})`,ye({retryOfRequestLogID:n,url:c,durationMs:m-h,message:d.message})),this.retryRequest(s,t,n??p);throw P(this).info(`[${p}] connection ${y?"timed out":"failed"} - error; no more retries left`),P(this).debug(`[${p}] connection ${y?"timed out":"failed"} (error; no more retries left)`,ye({retryOfRequestLogID:n,url:c,durationMs:m-h,message:d.message})),y?new is:k&&!Xr(d)?d:new Ge({cause:d})}const b=[...d.headers.entries()].filter(([S])=>S==="request-id"||S==="anthropic-workspace-id").map(([S,y])=>", "+S+": "+JSON.stringify(y)).join(""),v=`[${p}${g}${b}] ${a.method} ${c} ${d.ok?"succeeded":"failed"} with status ${d.status} in ${m-h}ms`;if(!d.ok){const S=await this.shouldRetry(d,s);if(t&&S){const L=`retrying, ${t} attempts remaining`;return await ga(d.body),$e(f),P(this).info(`${v} - ${L}`),P(this).debug(`[${p}] response error (${L})`,ye({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:m-h})),this.retryRequest(s,t,n??p,d.headers)}const y=S?"error; no more retries left":"error; not retryable";P(this).info(`${v} - ${y}`);const k=await d.text().catch(L=>wn(L).message),R=Ir(k),T=R?void 0:k;throw P(this).debug(`[${p}] response error (${y})`,ye({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,message:T,durationMs:Date.now()-h})),$e(f),this.makeStatusError(d.status,R,T,d.headers)}return P(this).info(v),P(this).debug(`[${p}] response start`,ye({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:m-h})),pa(d.body??d,f),{response:d,options:s,controller:f,requestLogID:p,retryOfRequestLogID:n,startTime:h}}getAPIList(e,t,n){return this.requestAPIList(t,n&&"then"in n?n.then(s=>({method:"get",path:e,...s})):{method:"get",path:e,...n})}requestAPIList(e,t){const n=this.makeRequest(t,null,void 0);return new Yr(this,n,e)}async fetchWithTimeout(e,t,n,s,i,a){const{signal:c,method:l,...p}=t||{},g=this._makeAbort(s);c&&(c.addEventListener("abort",g,{once:!0}),fa(s,c,g));const h=globalThis.ReadableStream&&p.body instanceof globalThis.ReadableStream||typeof p.body=="object"&&p.body!==null&&Symbol.asyncIterator in p.body,f={signal:s.signal,...h?{duplex:"half"}:{},method:"GET",...p};l&&(f.method=l.toUpperCase());const d=this.fetch,m=async(k,R)=>{const T=setTimeout(g,n);try{return await d.call(void 0,k,R)}finally{clearTimeout(T)}},b=i===void 0?m:(async(k,R={})=>{const T=typeof k=="string"?k:k instanceof URL?k.href:k.url;return R.headers=R.headers instanceof Headers?R.headers:new Headers(R.headers),await this.prepareRequest(R,{url:T,options:i}),a&&P(this).debug(`[${a.requestLogID}] sending request`,ye({retryOfRequestLogID:a.retryOfRequestLogID,method:R.method,url:T,options:i,headers:R.headers})),m(k,R)}),v=i?.middleware,S=this.backendMiddleware(),y=v?.length||S.length?[...this.middleware,...v??[],...S]:this.middleware;return await Zs(b,y,i,this)(e,f)}async shouldRetry(e,t){const n=this._authFlags(t);if(e.status===401&&this._authState.tokenCache&&n.usedTokenCache&&!n.didRefreshFor401)return n.didRefreshFor401=!0,this._authState.tokenCache.invalidate(),!0;const s=e.headers.get("x-should-retry");return s==="true"?!0:s==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,s){let i;const a=s?.get("retry-after-ms");if(a){const l=parseFloat(a);Number.isNaN(l)||(i=l)}const c=s?.get("retry-after");if(c&&!i){const l=parseFloat(c);Number.isNaN(l)?i=Date.parse(c)-Date.now():i=l*1e3}if(i===void 0){const l=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,l)}return await Me(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){const i=t-e,a=Math.min(.5*Math.pow(2,i),8),c=1-Math.random()*.25;return a*c*1e3}calculateNonstreamingTimeout(e,t){if(36e5*e/128e3>6e5||t!=null&&e>t)throw new x("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 n={...e},{method:s,path:i,query:a,defaultBaseURL:c}=n;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(i,a,c);"timeout"in n&&oa("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:p,body:g}=this.buildBody({options:n}),h=await this.buildHeaders({options:e,method:s,bodyHeaders:p,retryCount:t});return{req:{method:s,headers:h,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&g instanceof globalThis.ReadableStream&&{duplex:"half"},...g&&{body:g},...this.fetchOptions??{},...n.fetchOptions??{}},url:l,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:s}){let i={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const a=u([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ps(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const n=u([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Pr(e)}:typeof e=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:o(this,gn,"f").call(this,{body:e,headers:n})}}Ls=F,gn=new WeakMap,rs=new WeakSet,ea=function(){return this.baseURL!=="https://api.anthropic.com"};F.Anthropic=Ls;F.HUMAN_PROMPT=ta;F.AI_PROMPT=na;F.DEFAULT_TIMEOUT=6e5;F.AnthropicError=x;F.APIError=q;F.APIConnectionError=Ge;F.APIConnectionTimeoutError=is;F.APIUserAbortError=se;F.NotFoundError=ls;F.ConflictError=ds;F.RateLimitError=hs;F.BadRequestError=as;F.AuthenticationError=os;F.InternalServerError=fs;F.PermissionDeniedError=cs;F.UnprocessableEntityError=us;F.toFile=ei;class xe extends F{constructor(){super(...arguments),this.completions=new Vi(this),this.messages=new Os(this),this.models=new Gi(this),this.files=new Ji(this),this.skills=new Cs(this),this.beta=new U(this)}}xe.Completions=Vi;xe.Messages=Os;xe.Models=Gi;xe.Files=Ji;xe.Skills=Cs;xe.Beta=U;new TextEncoder;const Ac=Object.freeze(Object.defineProperty({__proto__:null,AI_PROMPT:na,APIConnectionError:Ge,APIConnectionTimeoutError:is,APIError:q,APIPromise:At,APIUserAbortError:se,Anthropic:xe,AnthropicError:x,AuthenticationError:os,BadRequestError:as,BaseAnthropic:F,ConflictError:ds,HUMAN_PROMPT:ta,InternalServerError:fs,NotFoundError:ls,PagePromise:Yr,PermissionDeniedError:cs,RateLimitError:hs,RetryableError:Ar,UnprocessableEntityError:us,default:xe,toFile:ei},Symbol.toStringTag,{value:"Module"}));export{x as A,wc as D,pr as M,Ac as i};
@@ -0,0 +1 @@
1
+ import{A as s}from"./index-DQDuRMiM.js";import{D as R,M as B}from"./index-DQDuRMiM.js";import"./rr0-sighting-editor.mjs";function e(o){throw new s(`${o} requires Node.js or a Node-compatible runtime`)}const a=3e4,c=".anthropic-memory-store";class u extends s{constructor(t,r){super(t),this.name="SessionMemoryError",r!==void 0&&(this.cause=r)}}class l{constructor(t,r){e("SessionMemoryStores")}get roots(){return e("SessionMemoryStores")}get readOnlyRoots(){return e("SessionMemoryStores")}download(t){return e("SessionMemoryStores")}finish(){return e("SessionMemoryStores")}syncAll(t){return e("SessionMemoryStores")}syncIfDue(){return e("SessionMemoryStores")}flushWrites(t){return e("SessionMemoryStores")}dispose(){return e("SessionMemoryStores")}}function S(o){return e("setupSkills")}function _(o,t){return e("extractSkillArchive")}function m(o){return e("betaAgentToolset20260401")}function M(o,t){return e("resolvePath")}class h extends s{constructor(t){super(`bash command timed out after ${t}ms`),this.name="BashTimeoutError",this.timeoutMs=t}}class T{constructor(t,r){e("BashSession")}get closed(){return e("BashSession")}exec(t,r={}){return e("BashSession")}close(){e("BashSession")}}function d(o){return e("betaBashTool")}function f(o){return e("betaReadTool")}function b(o){return e("betaWriteTool")}function p(o){return e("betaEditTool")}function y(o){return e("betaGlobTool")}function x(o){return e("betaGrepTool")}export{T as BashSession,h as BashTimeoutError,R as DEFAULT_MEMORY_SYNC_INTERVAL_MS,c as MARKER_PATH,a as MEMORY_FLUSH_TIMEOUT_MS,B as MIN_MEMORY_SYNC_INTERVAL_MS,u as SessionMemoryError,l as SessionMemoryStores,m as betaAgentToolset20260401,d as betaBashTool,p as betaEditTool,y as betaGlobTool,x as betaGrepTool,f as betaReadTool,b as betaWriteTool,_ as extractSkillArchive,M as resolvePath,S as setupSkills};
@@ -0,0 +1 @@
1
+ import{A as o}from"./index-DQDuRMiM.js";import"./rr0-sighting-editor.mjs";function t(n){return new Proxy({},{get(r,e){if(typeof e!="symbol")throw new o(`\`${n}.${e}\` is not available in this environment; it needs a Node.js-compatible runtime`)}})}t("child_process");t("crypto");const a=t("fs");t("os");const c=t("path");t("stream");t("util");export{a as fs,c as path};