@hintergrund/ui 0.3.17 → 0.3.18

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.
@@ -1,2 +1,2 @@
1
- void 0===globalThis.process&&(globalThis.process={env:{},platform:"browser",version:"",versions:{},browser:!0,nextTick:function(e){return Promise.resolve().then(e)}});import{r as e,t}from"./rolldown-runtime-9urLBz53.js";import{A as s,C as n,D as r,O as i,c as o,d as a,j as c,k as l,l as h,s as d,u,v as p,w as f,x as g}from"./AssistantPane-DrJ9jlS4.js";import{a as m,i as _,n as w,o as y,r as b,t as v}from"./github-copilot-headers-EfqOaQ0F.js";import{n as k,t as S}from"./provider-retry-DNH2SSUZ.js";import{a as x,f as R,h as I,i as A,m as $,n as T,r as E,t as M}from"./transform-messages-DBW2TigX.js";function O(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var P=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{const t=Object.prototype.toString.call(e);if("[object Error]"===t||"[object DOMException]"===t){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)},C=/* @__PURE__ */(()=>{class e extends Error{}return e})(),L=class e extends C{constructor(t,s,n,r,i){super(`${e.makeMessage(t,s,n)}`),this.status=t,this.headers=r,this.requestID=r?.get("request-id"),this.workspaceID=r?.get("anthropic-workspace-id"),this.error=s,this.type=i??null}static makeMessage(e,t,s){const n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(t,s,n,r){if(!t||!r)return new q({message:n,cause:P(s)});const i=s,o=i?.error?.type;return 400===t?new U(t,i,n,r,o):401===t?new D(t,i,n,r,o):403===t?new H(t,i,n,r,o):404===t?new z(t,i,n,r,o):409===t?new F(t,i,n,r,o):422===t?new B(t,i,n,r,o):429===t?new K(t,i,n,r,o):t>=500?new J(t,i,n,r,o):new e(t,i,n,r,o)}},N=class extends L{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},q=class extends L{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},W=class extends q{constructor({message:e}={}){super({message:e??"Request timed out."})}},j=class extends C{constructor(e,{cause:t}={}){super(e??"Retryable error."),void 0!==t&&(this.cause=t)}},U=class extends L{},D=class extends L{},H=class extends L{},z=class extends L{},F=class extends L{},B=class extends L{},K=class extends L{},J=class extends L{},V=5e3;function X(e,t,s,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,s):r?r.value=s:t.set(e,s),s}function G(e,t,s,n){if("a"===s&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?n:"a"===s?n.call(e):n?n.value:t.get(e)}var Y=/^[a-z][a-z0-9+.-]*:/i,Q=e=>(Q=Array.isArray)(e),Z=Q;function ee(e){return"object"!=typeof e?{}:e??{}}function te(e){if(!e)return!0;for(const t in e)return!1;return!0}function se(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}var ne,re=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new C(`${e} must be an integer`);if(t<0)throw new C(`${e} must be a positive integer`);return t},ie=e=>{try{return JSON.parse(e)}catch(t){return}},oe=(e,t)=>new Promise(s=>{if(t?.aborted)return s();const n=()=>{clearTimeout(r),s()},r=setTimeout(()=>{t?.removeEventListener("abort",n),s()},e);t?.addEventListener("abort",n,{once:!0})}),ae="0.129.0",ce=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",le=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown",he=()=>ne??(ne=(()=>{const e="undefined"!=typeof Deno&&null!=Deno.build?"deno":"undefined"!=typeof EdgeRuntime?"edge":"[object process]"===Object.prototype.toString.call(void 0!==globalThis.process?globalThis.process:0)?"node":"unknown";if("deno"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ae,"X-Stainless-OS":le(Deno.build.os),"X-Stainless-Arch":ce(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ae,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process?.version??"unknown"};if("node"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ae,"X-Stainless-OS":le(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ce(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=function(){if("undefined"==typeof navigator||!navigator)return null;for(const{key:e,pattern:t}of[{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/}]){const s=t.exec(navigator.userAgent);if(s)return{browser:e,version:`${s[1]||0}.${s[2]||0}.${s[3]||0}`}}return null}();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ae,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ae,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}})()),de=/* @__PURE__ */new WeakMap,ue="function"==typeof globalThis.FinalizationRegistry?new globalThis.FinalizationRegistry(e=>pe(e)):null;function pe(e){const t=de.get(e);t&&(de.delete(e),ue?.unregister(e),t())}function fe(...e){const t=globalThis.ReadableStream;if(void 0===t)throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function ge(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return fe({start(){},async pull(e){const{done:s,value:n}=await t.next();s?e.close():e.enqueue(n)},async cancel(){await(t.return?.())}})}function me(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var _e=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),we="RFC3986",ye=e=>String(e),be={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:ye},ve=(e,t)=>(ve=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty))(e,t),ke=/* @__PURE__ */(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),Se=1024;function xe(e,t){if(Q(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}var Re,Ie={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},Ae=function(e,t){Array.prototype.push.apply(e,Q(t)?t:[t])},$e={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,s,n,r)=>{if(0===e.length)return e;let i=e;if("symbol"==typeof e?i=Symbol.prototype.toString.call(e):"string"!=typeof e&&(i=String(e)),"iso-8859-1"===s)return escape(i).replace(/%u[0-9a-f]{4}/gi,function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"});let o="";for(let a=0;a<i.length;a+=Se){const e=i.length>=Se?i.slice(a,a+Se):i,t=[];for(let s=0;s<e.length;++s){let n=e.charCodeAt(s);45===n||46===n||95===n||126===n||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||"RFC1738"===r&&(40===n||41===n)?t[t.length]=e.charAt(s):n<128?t[t.length]=ke[n]:n<2048?t[t.length]=ke[192|n>>6]+ke[128|63&n]:n<55296||n>=57344?t[t.length]=ke[224|n>>12]+ke[128|n>>6&63]+ke[128|63&n]:(s+=1,n=65536+((1023&n)<<10|1023&e.charCodeAt(s)),t[t.length]=ke[240|n>>18]+ke[128|n>>12&63]+ke[128|n>>6&63]+ke[128|63&n])}o+=t.join("")}return o},encodeValuesOnly:!1,format:we,formatter:ye,indices:!1,serializeDate:e=>(Re??(Re=Function.prototype.call.bind(Date.prototype.toISOString)))(e),skipNulls:!1,strictNullHandling:!1},Te={};function Ee(e,t,s,n,r,i,o,a,c,l,h,d,u,p,f,g,m,_){let w=e,y=_,b=0,v=!1;for(;void 0!==(y=y.get(Te))&&!v;){const t=y.get(e);if(b+=1,void 0!==t){if(t===b)throw new RangeError("Cyclic object value");v=!0}void 0===y.get(Te)&&(b=0)}if("function"==typeof l?w=l(t,w):w instanceof Date?w=u?.(w):"comma"===s&&Q(w)&&(w=xe(w,function(e){return e instanceof Date?u?.(e):e})),null===w){if(i)return c&&!g?c(t,$e.encoder,m,"key",p):t;w=""}if("string"==typeof(k=w)||"number"==typeof k||"boolean"==typeof k||"symbol"==typeof k||"bigint"==typeof k||function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))}(w)){if(c){const e=g?t:c(t,$e.encoder,m,"key",p);return[f?.(e)+"="+f?.(c(w,$e.encoder,m,"value",p))]}return[f?.(t)+"="+f?.(String(w))]}var k;const S=[];if(void 0===w)return S;let x;if("comma"===s&&Q(w))g&&c&&(w=xe(w,c)),x=[{value:w.length>0?w.join(",")||null:void 0}];else if(Q(l))x=l;else{const e=Object.keys(w);x=h?e.sort(h):e}const R=a?String(t).replace(/\./g,"%2E"):String(t),I=n&&Q(w)&&1===w.length?R+"[]":R;if(r&&Q(w)&&0===w.length)return I+"[]";for(let A=0;A<x.length;++A){const t=x[A],y="object"==typeof t&&void 0!==t.value?t.value:w[t];if(o&&null===y)continue;const v=d&&a?t.replace(/\./g,"%2E"):t,k=Q(w)?"function"==typeof s?s(I,v):I:I+(d?"."+v:"["+v+"]");_.set(e,b);const R=/* @__PURE__ */new WeakMap;R.set(Te,_),Ae(S,Ee(y,k,s,n,r,i,o,a,"comma"===s&&g&&Q(w)?null:c,l,h,d,u,p,f,g,m,R))}return S}var Me="/v1/oauth/token",Oe="oauth-2025-04-20",Pe=1<<20;function Ce(e){if(!e)return;let t;try{t=new URL(e)}catch(n){throw new De(`Invalid token endpoint base URL "${e}": ${n}`)}if("https:"===t.protocol)return;const s=t.hostname.toLowerCase().replace(/^\[|\]$/g,"");if("http:"!==t.protocol||"localhost"!==s&&"127.0.0.1"!==s&&"::1"!==s)throw new De(`Refusing to send credential over non-https token endpoint "${e}"`)}async function Le(e,t){const s=await async function(e){if(!e.body)return"";const t=e.body.getReader(),s=[];let n,r=0;for(;;){const{done:e,value:n}=await t.read();if(e)break;if(r+n.length>Pe){const e=Pe-r;e>0&&s.push(n.subarray(0,e)),await t.cancel();break}s.push(n),r+=n.length}if(1===s.length)n=s[0];else{n=new Uint8Array(s.reduce((e,t)=>e+t.length,0));let e=0;for(const t of s)n.set(t,e),e+=t.length}return new TextDecoder("utf-8").decode(n)}(e);let n;try{n=JSON.parse(s)}catch{throw new De(`Token endpoint returned non-JSON response (status ${e.status})`,e.status,We(s),t)}if(!n.access_token)throw new De(`Token endpoint response missing access_token: ${JSON.stringify(We(n))}`,e.status,We(n),t);if(n.token_type&&"bearer"!==n.token_type.toLowerCase())throw new De(`Token endpoint response: unsupported token_type "${n.token_type}" (want Bearer)`,e.status,We(n),t);return n}var Ne=2e3,qe=/* @__PURE__ */new Set(["error","error_description","error_uri"]);function We(e){if(null==e)return e;if("string"==typeof e){let t;try{t=JSON.parse(e)}catch{return e.length<=Ne?e:e.slice(0,Ne)+`... <${e.length-Ne} more chars>`}return JSON.stringify(We(t))}if("object"==typeof e&&!Array.isArray(e)){const t={};for(const[s,n]of Object.entries(e))qe.has(s)&&(t[s]=n);return t}return null}async function je(e,t=e=>{}){if("undefined"==typeof process)return;const{fs:s}=await(import("./node.browser-B4wGYm0x.js"));let n,r=e;try{r=await s.promises.realpath(e),n=await s.promises.stat(r)}catch{return}const i=511&n.mode;if(18&i)throw new De(`Credentials file at ${r} is group/world-writable (mode 0o${i.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${r}\`.`);if(36&i)throw new De(`Credentials file at ${r} is group/world-readable (mode 0o${i.toString(8)}); run \`chmod 600 ${r}\` before retrying.`);"function"==typeof process.getuid&&n.uid!==process.getuid()&&t(`credentials file at ${r} is owned by uid ${n.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function Ue(e,t){const{fs:s,path:n}=await(import("./node.browser-B4wGYm0x.js")),r=n.dirname(e);await s.promises.mkdir(r,{recursive:!0,mode:448});const i=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{const n=await s.promises.open(i,"w",384);try{await n.writeFile(JSON.stringify(t,null,2)),await n.sync()}finally{await n.close()}await s.promises.rename(i,e)}catch(o){throw await s.promises.unlink(i).catch(()=>{}),o}try{const e=await s.promises.open(r,"r");try{await e.sync()}finally{await e.close()}}catch{}}var De=class extends C{constructor(e,t=null,s=null,n=null){super(e),this.statusCode=t,this.body=s,this.requestId=n}};function He(){return Math.floor(Date.now()/1e3)}var ze,Fe,Be=class{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||null==t)return(await this.refresh(e)).token;if(null==t.expiresAt)return t.token;const s=t.expiresAt-He();return s>120?t.token:s>30?(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||He()-this.lastAdvisoryError<5||this.doRefresh().catch(e=>{this.lastAdvisoryError=He(),this.onAdvisoryRefreshError?.(e)})}doRefresh(e=!1){return this.pendingRefresh=this.provider(e?{forceRefresh:!0}:void 0).then(e=>(this.cached=e,this.pendingRefresh=null,e),e=>{throw this.pendingRefresh=null,e}),this.pendingRefresh}},Ke=e=>void 0!==globalThis.process?globalThis.process.env?.[e]?.trim()||void 0:void 0!==globalThis.Deno&&globalThis.Deno.env?.get?.(e)?.trim()||void 0;function Je(e){let t;return(ze??(t=new globalThis.TextEncoder,ze=t.encode.bind(t)))(e)}function Ve(e){let t;return(Fe??(t=new globalThis.TextDecoder,Fe=t.decode.bind(t)))(e)}var Xe={off:0,error:200,warn:300,info:400,debug:500},Ge=(e,t,s)=>{var n,r;if(e)return n=Xe,r=e,Object.prototype.hasOwnProperty.call(n,r)?e:void s.warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Xe))}`)};function Ye(){}function Qe(e,t,s){return!t||Xe[e]>Xe[s]?Ye:t[e].bind(t)}var Ze,et,tt={error:Ye,warn:Ye,info:Ye,debug:Ye},st=/* @__PURE__ */new WeakMap;function nt(e,t){const s=st.get(e);if(s&&s[0]===t)return s[1];const n={error:Qe("error",e,t),warn:Qe("warn",e,t),info:Qe("info",e,t),debug:Qe("debug",e,t)};return st.set(e,[t,n]),n}function rt(e){const t=e.logger,s=e.logLevel??"off";return t?nt(t,s):tt}function it(){const e=Ke("ANTHROPIC_LOG");return et&&e===Ze||(Ze=e,et=nt(console,Ge(e,"process.env['ANTHROPIC_LOG']",nt(console,"warn"))??"warn")),et}function ot(e,t,s){e.debug!==Ye&&e.debug(t,at(s))}var at=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,"authorization"===e.toLowerCase()||"api-key"===e.toLowerCase()||"x-api-key"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),ct=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return ct=e.randomUUID.bind(e),e.randomUUID();const t=/* @__PURE__ */new Uint8Array(1),s=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^s()&15>>+e/4).toString(16))},lt=/^[A-Za-z0-9_.-]+$/;function ht(e){if(!e)throw new Error("profile name is empty");if("."===e||".."===e)throw new Error(`profile name "${e}" is not allowed`);if(e.includes("/")||e.includes("\\"))throw new Error(`profile name "${e}" must not contain path separators`);if(!lt.test(e))throw new Error(`profile name "${e}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var dt,ut,pt=async(e,t)=>{if(e?.authentication.credentials_path)return e.authentication.credentials_path;const s=await ft();if(!s)return null;const n=t??await mt();if(!n)return null;ht(n);const{path:r}=await(import("./node.browser-B4wGYm0x.js"));return r.join(s,"credentials",`${n}.json`)},ft=async()=>{if(!gt())return null;const{path:e}=await(import("./node.browser-B4wGYm0x.js")),t=Ke("ANTHROPIC_CONFIG_DIR");if(t)return t;if("Windows"===he()["X-Stainless-OS"]){const t=Ke("APPDATA");if(t)return e.join(t,"Anthropic");const s=Ke("USERPROFILE");return s?e.join(s,"AppData","Roaming","Anthropic"):null}const s=Ke("XDG_CONFIG_HOME");if(s)return e.join(s,"anthropic");const n=Ke("HOME");return n?e.join(n,".config","anthropic"):null},gt=()=>{const e=he()["X-Stainless-Runtime"];return"node"===e||"deno"===e},mt=async()=>{const e=await ft();if(!e)return null;const t=Ke("ANTHROPIC_PROFILE");if(t)return t;const{fs:s,path:n}=await(import("./node.browser-B4wGYm0x.js")),r=n.join(e,"active_config");try{return(await s.promises.readFile(r,"utf-8")).trim()||"default"}catch(i){if("ENOENT"!==i?.code)throw new Error(`failed to read ${r}: ${i}`);return"default"}};function _t(e){if(!e)throw new C("Identity token file path is empty");return async()=>{const{fs:t}=await(import("./node.browser-B4wGYm0x.js"));let s;try{s=await t.promises.readFile(e,"utf-8")}catch(r){throw new C(`Failed to read identity token file at ${e}: ${r}`)}const n=s.trim();if(!n)throw new C(`Identity token file at ${e} is empty`);return n}}function wt(e,t){const s=function(e,t,s,n){switch(e.authentication.type){case"oidc_federation":{const r=e.authentication,i=function(e){if(e.identity_token){const t=e.identity_token.source;if("file"!==t)throw new De(`identity_token.source "${t}" is not supported by this SDK version (only "file")`);if(!e.identity_token.path)throw new De('identity_token.source "file" requires a non-empty path');return _t(e.identity_token.path)}const t=Ke("ANTHROPIC_IDENTITY_TOKEN_FILE");if(t)return _t(t);const s=Ke("ANTHROPIC_IDENTITY_TOKEN");return s?function(e){if(!e)throw new C("Identity token value is empty");return()=>e}(s):null}(r);if(!i)throw new De("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)");if(!r.federation_rule_id)throw new De("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(!e.organization_id)throw new De("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");const o=function(e){return async()=>{Ce(e.baseURL);const t=await e.identityTokenProvider();if(t.length>16384)throw new De(`Identity token is ${Math.ceil(t.length/1024)} KiB, exceeds the 16 KiB assertion limit`);const s={grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:t,federation_rule_id:e.federationRuleId,organization_id:e.organizationId};e.serviceAccountId&&(s.service_account_id=e.serviceAccountId),e.workspaceId&&(s.workspace_id=e.workspaceId);const n=`${e.baseURL}${Me}`;let r;try{r=await e.fetch(n,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${Oe},oidc-federation-2026-04-01`,"User-Agent":e.userAgent||"anthropic-sdk-typescript/0.129.0 oidcFederationProvider"},body:JSON.stringify(s)})}catch(c){throw new De(`Failed to reach token endpoint ${n}: ${c}`)}const i=r.headers.get("Request-Id");if(!r.ok){const t=We(await r.text().catch(()=>""));let s="";throw 401===r.status&&(s=` Ensure your federation rule matches your identity token. ${e.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 De(`Token exchange failed with status ${r.status}${i?` (request-id ${i})`:""}: ${t}${s}`,r.status,t,i)}const o=await Le(r,i),a=Number(o.expires_in);if(!Number.isFinite(a))throw new De(`Token endpoint response missing required fields: ${JSON.stringify(We(o))}`,r.status,We(o),i);return{token:o.access_token,expiresAt:He()+a}}}({identityTokenProvider:i,federationRuleId:r.federation_rule_id,organizationId:e.organization_id,serviceAccountId:r.service_account_id,workspaceId:e.workspace_id,baseURL:s,fetch:n.fetch,userAgent:n.userAgent});return t?function(e,t,s,n){return async r=>{const{fs:i}=await(import("./node.browser-B4wGYm0x.js"));let o;await je(t,n);try{const e=await i.promises.readFile(t,"utf-8");o=JSON.parse(e);const s=o?.access_token;if(s&&!r?.forceRefresh){const e=o?.expires_at;if(null==e||He()<e-30)return{token:s,expiresAt:e??null}}}catch(c){"ENOENT"===c?.code||c instanceof SyntaxError||s?.(c)}const a=await e(r);try{await Ue(t,{...o??{},version:"1.0",type:"oauth_token",access_token:a.token,expires_at:a.expiresAt})}catch(c){s?.(c)}return a}}(o,t,n.onCacheWriteError,n.onSafetyWarning):o}case"user_oauth":if(!t)throw new De("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return function(e){return async t=>{const{fs:s}=await(import("./node.browser-B4wGYm0x.js"));let n,r;await je(e.credentialsPath,e.onSafetyWarning);try{n=await s.promises.readFile(e.credentialsPath,"utf-8")}catch(m){throw new De(`Credentials file not found at ${e.credentialsPath}: ${m}`)}try{r=JSON.parse(n)}catch(m){throw new De(`Credentials file at ${e.credentialsPath} is not valid JSON: ${m}`)}const i=r.access_token;if(!i)throw new De(`Credentials file at ${e.credentialsPath} must include 'access_token'`);const o=r.expires_at;if(!t?.forceRefresh&&(null==o||He()<o-30))return{token:i,expiresAt:o??null};const a=r.refresh_token;if(!e.clientId||!a)throw new De(`Access token at ${e.credentialsPath} has expired and no refresh is available (client_id ${e.clientId?"set":"empty"}, refresh_token ${a?"set":"empty"})`);Ce(e.baseURL);const c={grant_type:"refresh_token",refresh_token:a,client_id:e.clientId},l=`${e.baseURL}${Me}`;let h;try{h=await e.fetch(l,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":Oe,"User-Agent":e.userAgent||"anthropic-sdk-typescript/0.129.0 userOAuthProvider"},body:JSON.stringify(c)})}catch(m){throw new De(`User OAuth refresh failed to reach token endpoint: ${m}`)}const d=h.headers.get("Request-Id");if(!h.ok){const e=await h.text().catch(()=>"");throw new De(`User OAuth refresh failed (HTTP ${h.status}): ${We(e)}`,h.status,We(e),d)}const u=await Le(h,d),p=Number(u.expires_in);if(!Number.isFinite(p))throw new De(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(We(u))}`,h.status,We(u),d);const f=He()+p,g=u.refresh_token||a;return await Ue(e.credentialsPath,{...r,version:"1.0",type:"oauth_token",access_token:u.access_token,expires_at:f,refresh_token:g}),{token:u.access_token,expiresAt:f}}}({credentialsPath:t,clientId:e.authentication.client_id,baseURL:s,fetch:n.fetch,userAgent:n.userAgent,onSafetyWarning:n.onSafetyWarning});default:{const t=e.authentication.type;throw new De(`authentication.type "${t}" is not a known authentication type`)}}}(e,e.authentication.credentials_path??null,(e.base_url||t.baseURL).replace(/\/+$/,""),t),n={};return e.workspace_id&&"user_oauth"===e.authentication.type&&(n["anthropic-workspace-id"]=e.workspace_id),{provider:s,extraHeaders:n,baseURL:e.base_url||void 0}}var yt,bt=/* @__PURE__ */(()=>{class e{constructor(){dt.set(this,void 0),ut.set(this,void 0),X(this,dt,/* @__PURE__ */new Uint8Array,"f"),X(this,ut,null,"f")}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?Je(e):e;X(this,dt,function(e){let t=0;for(const r of e)t+=r.length;const s=new Uint8Array(t);let n=0;for(const r of e)s.set(r,n),n+=r.length;return s}([G(this,dt,"f"),t]),"f");const s=[];let n;for(;null!=(n=vt(G(this,dt,"f"),G(this,ut,"f")));){if(n.carriage&&null==G(this,ut,"f")){X(this,ut,n.index,"f");continue}if(null!=G(this,ut,"f")&&(n.index!==G(this,ut,"f")+1||n.carriage)){s.push(Ve(G(this,dt,"f").subarray(0,G(this,ut,"f")-1))),X(this,dt,G(this,dt,"f").subarray(G(this,ut,"f")),"f"),X(this,ut,null,"f");continue}const e=null!==G(this,ut,"f")?n.preceding-1:n.preceding,t=Ve(G(this,dt,"f").subarray(0,e));s.push(t),X(this,dt,G(this,dt,"f").subarray(n.index),"f"),X(this,ut,null,"f")}return s}flush(){return G(this,dt,"f").length?this.decode("\n"):[]}}return dt=/* @__PURE__ */new WeakMap,ut=/* @__PURE__ */new WeakMap,e.NEWLINE_CHARS=/* @__PURE__ */new Set(["\n","\r"]),e.NEWLINE_REGEXP=/\r\n|[\n\r]/g,e})();function vt(e,t){for(let s=t??0;s<e.length;s++){if(10===e[s])return{preceding:s,index:s+1,carriage:!1};if(13===e[s])return{preceding:s,index:s+1,carriage:!0}}return null}var kt=/* @__PURE__ */(()=>{class e{constructor(e,t,s){this.iterator=e,yt.set(this,void 0),this.controller=t,X(this,yt,s,"f")}static rawEvents(e,t=new AbortController){return St(e,t)}static fromSSEResponse(t,s,n){let r=!1;const i=n?rt(n):console;return new e(async function*(){if(r)throw new C("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let e=!1;try{for await(const e of St(t,s)){if("completion"===e.event)try{yield JSON.parse(e.data)}catch(n){throw i.error("Could not parse message into JSON:",e.data),i.error("From chunk:",e.raw),n}if("message_start"===e.event||"message_delta"===e.event||"message_stop"===e.event||"content_block_start"===e.event||"content_block_delta"===e.event||"content_block_stop"===e.event||"message"===e.event||"user.message"===e.event||"user.interrupt"===e.event||"user.tool_confirmation"===e.event||"user.custom_tool_result"===e.event||"user.tool_result"===e.event||"agent.message"===e.event||"agent.thinking"===e.event||"agent.tool_use"===e.event||"agent.tool_result"===e.event||"agent.mcp_tool_use"===e.event||"agent.mcp_tool_result"===e.event||"agent.custom_tool_use"===e.event||"agent.thread_context_compacted"===e.event||"session.status_running"===e.event||"session.status_idle"===e.event||"session.status_rescheduled"===e.event||"session.status_terminated"===e.event||"session.error"===e.event||"session.deleted"===e.event||"session.updated"===e.event||"span.model_request_start"===e.event||"span.model_request_end"===e.event||"span.outcome_evaluation_start"===e.event||"span.outcome_evaluation_ongoing"===e.event||"span.outcome_evaluation_end"===e.event||"user.define_outcome"===e.event||"agent.thread_message_received"===e.event||"agent.thread_message_sent"===e.event||"agent.session_thread_message_received"===e.event||"agent.session_thread_message_sent"===e.event||"session.thread_created"===e.event||"session.thread_status_created"===e.event||"session.thread_status_running"===e.event||"session.thread_status_idle"===e.event||"session.thread_status_rescheduled"===e.event||"session.thread_status_terminated"===e.event||"event_start"===e.event||"event_delta"===e.event||"system.message"===e.event)try{yield JSON.parse(e.data)}catch(n){throw i.error("Could not parse message into JSON:",e.data),i.error("From chunk:",e.raw),n}if("ping"!==e.event&&"error"===e.event){const s=ie(e.data)??e.data,n=s?.error?.type;throw new L(void 0,s,void 0,t.headers,n)}}e=!0}catch(n){if(O(n))return;throw n}finally{e||s.abort(),pe(s)}},s,n)}static fromReadableStream(t,s,n){let r=!1;return new e(async function*(){if(r)throw new C("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let e=!1;try{for await(const s of async function*(){const e=new bt,s=me(t);for await(const t of s)for(const s of e.decode(t))yield s;for(const t of e.flush())yield t}())e||s&&(yield JSON.parse(s));e=!0}catch(n){if(O(n))return;throw n}finally{e||s.abort(),pe(s)}},s,n)}[(yt=/* @__PURE__ */new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const t=[],s=[],n=this.iterator(),r=e=>({next:()=>{if(0===e.length){const e=n.next();t.push(e),s.push(e)}return e.shift()}});return[new e(()=>r(t),this.controller,G(this,yt,"f")),new e(()=>r(s),this.controller,G(this,yt,"f"))]}toReadableStream(){const e=this;let t;return fe({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:s,done:n}=await t.next();if(n)return e.close();const r=Je(JSON.stringify(s)+"\n");e.enqueue(r)}catch(s){e.error(s)}},async cancel(){await(t.return?.())}})}}return e})();async function*St(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new C("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new C("Attempted to iterate over a response with no body")}const s=new xt,n=new bt,r=me(e.body);for await(const i of r)for(const e of n.decode(i)){const t=s.decode(e);t&&(yield t)}for(const i of n.flush()){const e=s.decode(i);e&&(yield e)}}var xt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,n]=function(e){const t=e.indexOf(":");return-1!==t?[e.substring(0,t),":",e.substring(t+1)]:[e,"",""]}(e);return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}};async function Rt(e,t){const{response:s,requestLogID:n,retryOfRequestLogID:r,startTime:i}=t,o=await(async()=>{if(t.options.stream)return rt(e).debug("response",s.status,s.url,s.headers,s.body),kt.fromSSEResponse(s,t.controller,e);if(204===s.status)return null;if(t.options.__binaryResponse)return s;const n=s.headers.get("content-type")?.split(";")[0]?.trim();if(n?.includes("application/json")||n?.endsWith("+json")){if("0"===s.headers.get("content-length"))return;return It(await s.json(),s)}return await s.text()})().finally(()=>{t.options.stream||t.options.__binaryResponse||pe(t.controller)});return ot(rt(e),`[${n}] response parsed`,{retryOfRequestLogID:r,url:s.url,status:s.status,body:o,durationMs:Date.now()-i}),o}function It(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperties(e,{_request_id:{value:t.headers.get("request-id"),enumerable:!1},_workspace_id:{value:t.headers.get("anthropic-workspace-id"),enumerable:!1}})}var At,$t=/* @__PURE__ */new WeakSet;function Tt(e){return"object"==typeof e&&null!==e&&$t.has(e)}function Et(e,t,s,n){return async(r,i={})=>{if(0===t.length)return e.call(void 0,r,i);const o=i.headers instanceof Headers?i.headers:new Headers(i.headers),a=await function(e,t,s,n){let r=async({url:t,...s})=>{try{return await e.call(void 0,t,s)}catch(n){const e=P(n);throw $t.add(e),e}};const i=function(e,t){const s=/* @__PURE__ */new WeakMap;return{options:e,logger:t?rt(t):it(),parse(n){if(e?.stream&&n.ok)return Mt(n,e,t);let r=s.get(n);return r||(r=Mt(n,e,t),s.set(n,r)),r}}}(s,n);for(let o=t.length-1;o>=0;o--){const e=t[o],s=r;r=async t=>e(t,s,i)}return r}(e,t,s,n)({...i,headers:o,url:"string"==typeof r?r:r instanceof URL?r.href:r.url});if(a.bodyUsed||a.body?.locked)throw new C("middleware consumed the response body; use response.clone() to inspect it, or return new Response(body, response) to consume and replace it");return a}}async function Mt(e,t,s){if(e.bodyUsed||e.body?.locked)throw new C("cannot ctx.parse() a response whose body was already consumed; call ctx.parse() instead of reading the body, or read via response.clone()");if(t?.stream&&e.ok)return kt.fromSSEResponse(e.clone(),new AbortController,s);if(204===e.status)return null;if(t?.__binaryResponse)return e;const n=e.headers.get("content-type")?.split(";")[0]?.trim();if(n?.includes("application/json")||n?.endsWith("+json")){if("0"===e.headers.get("content-length"))return;return It(await e.clone().json(),e)}return await e.clone().text()}var Ot,Pt=/* @__PURE__ */(()=>{class e extends Promise{constructor(e,t,s=Rt){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=s,At.set(this,void 0),X(this,At,e,"f")}_thenUnwrap(t){return new e(G(this,At,"f"),this.responsePromise,async(e,s)=>It(t(await this.parseResponse(e,s),s),s.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id"),workspace_id:t.headers.get("anthropic-workspace-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(G(this,At,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}return At=/* @__PURE__ */new WeakMap,e})(),Ct=/* @__PURE__ */(()=>{class e{constructor(e,t,s,n){Ot.set(this,void 0),X(this,Ot,e,"f"),this.options=n,this.response=t,this.body=s}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageRequestOptions()}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new C("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await G(this,Ot,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ot=/* @__PURE__ */new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}return e})(),Lt=/* @__PURE__ */(()=>{class e extends Pt{constructor(e,t,s){super(e,t,async(e,t)=>new s(e,t.response,await Rt(e,t),t.options))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}return e})(),Nt=class extends Ct{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1,this.first_id=s.first_id||null,this.last_id=s.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){const e=this.first_id;return e?{...this.options,query:{...ee(this.options.query),before_id:e}}:null}const e=this.last_id;return e?{...this.options,query:{...ee(this.options.query),after_id:e}}:null}},qt=class extends Ct{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.next_page=s.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){const e=this.next_page;return e?{...this.options,query:{...ee(this.options.query),page:e}}:null}},Wt=class extends Ct{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.next_page=s.next_page||null,this.prev_page=s.prev_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){const e=this.next_page;return e?{...this.options,query:{...ee(this.options.query),page:e}}:null}},jt=()=>{if("undefined"==typeof File){const{process:e}=globalThis,t="string"==typeof e?.versions?.node&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Ut(e,t,s){return jt(),new File(e,t??"",s)}function Dt(e,t){const s="object"==typeof e&&null!==e&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"";return t?s.split(/[\\/]/).pop()||void 0:s}var Ht=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],zt=async(e,t,s=!0)=>({...e,body:await Bt(e.body,t,s)}),Ft=/* @__PURE__ */new WeakMap,Bt=async(e,t,s=!0)=>{if(!(await function(e){const t="function"==typeof e?e:e.fetch,s=Ft.get(t);if(s)return s;const n=(async()=>{try{const e="Response"in t?t.Response:(await t("data:,")).constructor,s=new FormData;return s.toString()!==await new e(s).text()}catch{return!0}})();return Ft.set(t,n),n}(t)))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(e||{}).map(([e,t])=>Kt(n,e,t,s))),n},Kt=async(e,t,s,n)=>{if(void 0!==s){if(null==s)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof s||"number"==typeof s||"boolean"==typeof s)e.append(t,String(s));else if(s instanceof Response){let r={};const i=s.headers.get("Content-Type");i&&(r={type:i}),e.append(t,Ut([await s.blob()],Dt(s,n),r))}else if(Ht(s))e.append(t,Ut([await new Response(ge(s)).blob()],Dt(s,n)));else if(s instanceof Blob){const r="undefined"!=typeof File&&s instanceof File?s.name:Dt(s,n);e.append(t,Ut([s],r,{type:s.type}))}else if(Array.isArray(s))await Promise.all(s.map(s=>Kt(e,t+"[]",s,n)));else{if("function"==typeof s.then)throw new TypeError(`Received a Promise for "${t}"; await it first, e.g. \`await toFile(...)\``);if(s instanceof ArrayBuffer||ArrayBuffer.isView(s))throw new TypeError(`Received ${s.constructor.name} for "${t}"; to upload raw bytes, wrap them with \`await toFile(bytes, 'filename')\``);if("object"!=typeof s)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${s} instead`);await Promise.all(Object.entries(s).map(([s,r])=>Kt(e,`${t}[${s}]`,r,n)))}}},Jt=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function Vt(e,t,s){if(jt(),e=await e,t||(t=e instanceof File?e.name:Dt(e,!0)),(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&Jt(e))(e))return e instanceof File&&null==t&&null==s?e:Ut([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...s});if((e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob)(e)){const n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Ut(await Xt(n),t,s)}const n=await Xt(e);if(!s?.type){const e=n.find(e=>"object"==typeof e&&"type"in e&&e.type);"string"==typeof e&&(s={...s,type:e})}return Ut(n,t,s)}async function Xt(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Jt(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else{if(!Ht(e)){const t=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){return"object"!=typeof e||null===e?"":`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(", ")}]`}(e)}`)}for await(const s of e)t.push(...await Xt(s))}return t}var Gt=class{constructor(e){this._client=e}},Yt=Symbol.for("brand.privateNullableHeaders");function*Qt(e){if(!e)return;if(Yt in e){const{values:t,nulls:s}=e;yield*t.entries();for(const e of s)yield[e,null];return}let t,s=!1;e instanceof Headers?t=e.entries():Z(e)?t=e:(s=!0,t=Object.entries(e??{}));for(let n of t){const e=n[0];if("string"!=typeof e)throw new TypeError("expected header name to be a string");const t=Z(n[1])?n[1]:[n[1]];let r=!1;for(const n of t)void 0!==n&&(s&&!r&&(r=!0,yield[e,Zt]),yield[e,n])}}var Zt=Symbol("clear"),es=/* @__PURE__ */new Set(["x-stainless-helper"]),ts=(e,t)=>{const s=e?e.split(",").map(e=>e.trim()).filter(Boolean):[];for(const n of t.split(",").map(e=>e.trim()))n&&!s.includes(n)&&s.push(n);return s.join(", ")},ss=e=>{const t=new Headers,s=/* @__PURE__ */new Set;for(const n of e){const e=/* @__PURE__ */new Set;for(const[r,i]of Qt(n)){const n=r.toLowerCase();if(es.has(n)){if(i===Zt)continue;null===i?(t.delete(r),s.add(n)):(t.set(r,ts(t.get(r),i)),s.delete(n))}else(i!==Zt&&e.has(n)||(t.delete(r),e.add(n),i!==Zt))&&(null===i?(t.delete(r),s.add(n)):(t.append(r,i),s.delete(n)))}}return{[Yt]:!0,values:t,nulls:s}};function ns(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var rs=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.create(null)),is=(e=ns)=>function(t,...s){if(1===t.length)return t[0];let n=!1;const r=[],i=t.reduce((t,i,o)=>{/[?#]/.test(i)&&(n=!0);const a=s[o];let c=(n?encodeURIComponent:e)(""+a);return o!==s.length&&(null==a||"object"==typeof a&&a.toString===Object.getPrototypeOf(Object.getPrototypeOf(a.hasOwnProperty??rs)??rs)?.toString)&&(c=a+"",r.push({start:t.length+i.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(a).slice(8,-1)} is not a valid path parameter`})),t+i+(o===s.length?"":c)},""),o=i.split(/[?#]/,1)[0],a=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let c;for(;null!==(c=a.exec(o));)r.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(r.sort((e,t)=>e.start-t.start),r.length>0){let e=0;const t=r.reduce((t,s)=>{const n=" ".repeat(s.start-e),r="^".repeat(s.length);return e=s.start+s.length,t+n+r},"");throw new C(`Path parameters result in path with invalid segments:\n${r.map(e=>e.error).join("\n")}\n${i}\n${t}`)}return i},os=/* @__PURE__ */is(ns),as=class extends Gt{retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/deployment_runs/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/deployment_runs?beta=true",qt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}},cs=class extends Gt{create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/deployments?beta=true",{body:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/deployments/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}update(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/deployments/${e}?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/deployments?beta=true",qt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}archive(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/deployments/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}pause(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/deployments/${e}/pause?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}run(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/deployments/${e}/run?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}unpause(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/deployments/${e}/unpause?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},ls=class extends Gt{create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/dreams?beta=true",{body:r,...t,headers:ss([{"anthropic-beta":[...s??[],"dreaming-2026-04-21"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/dreams/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"dreaming-2026-04-21"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/dreams?beta=true",qt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"dreaming-2026-04-21"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}archive(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/dreams/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"dreaming-2026-04-21"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}cancel(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/dreams/${e}/cancel?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"dreaming-2026-04-21"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},hs="x-stainless-helper",ds="x-stainless-helper-method";function us(e){return{[hs]:e}}var ps=Symbol("anthropic.sdk.stainlessHelper");function fs(e){return"object"==typeof e&&null!==e&&ps in e}function gs(e,t){const s=/* @__PURE__ */new Set;if(e)for(const n of e)fs(n)&&s.add(n[ps]);if(t)for(const n of t){fs(n)&&s.add(n[ps]);const e=n.content;if(Array.isArray(e))for(const t of e){fs(t)&&s.add(t[ps]);const e=t?.tool?.definition;fs(e)&&s.add(e[ps])}}return Array.from(s)}function ms(e,t){const s=gs(e,t);return 0===s.length?{}:{[hs]:s.join(", ")}}function _s(e){return fs(e)?{[hs]:e[ps]}:{}}var ws,ys,bs,vs,ks,Ss,xs,Rs,Is,As,$s,Ts,Es,Ms=class extends Gt{list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/files?beta=true",qt,{query:r,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}delete(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.delete(os`/v1/files/${e}?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}download(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/files/${e}/content?beta=true`,{...s,headers:ss([{Accept:"application/binary",...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/files/${e}?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}upload(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/files?beta=true",zt({body:r,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},_s(r.file),t?.headers])},this._client))}},Os=class extends Gt{retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/models/${e}?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/models?beta=true",Nt,{query:r,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}},Ps=class extends Gt{create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/user_profiles?beta=true",{body:r,...t,headers:ss([{"anthropic-beta":[...s??[],"user-profiles-2026-08-18"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/user_profiles/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"user-profiles-2026-08-18"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}update(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/user_profiles/${e}?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"user-profiles-2026-08-18"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/user_profiles?beta=true",qt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"user-profiles-2026-08-18"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}createEnrollmentURL(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"user-profiles-2026-08-18"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},Cs=/* @__PURE__ */t(e=>{var t,s=e&&e.__extends||(t=function(e,s){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var s in t)t.hasOwnProperty(s)&&(e[s]=t[s])},t(e,s)},function(e,s){function n(){this.constructor=e}t(e,s),e.prototype=null===s?Object.create(s):(n.prototype=s.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var n=256,r=function(){function e(e){void 0===e&&(e="="),this._paddingCharacter=e}return e.prototype.encodedLength=function(e){return this._paddingCharacter?(e+2)/3*4|0:(8*e+5)/6|0},e.prototype.encode=function(e){for(var t="",s=0;s<e.length-2;s+=3){var n=e[s]<<16|e[s+1]<<8|e[s+2];t+=this._encodeByte(n>>>18&63),t+=this._encodeByte(n>>>12&63),t+=this._encodeByte(n>>>6&63),t+=this._encodeByte(n>>>0&63)}var r=e.length-s;return r>0&&(n=e[s]<<16|(2===r?e[s+1]<<8:0),t+=this._encodeByte(n>>>18&63),t+=this._encodeByte(n>>>12&63),t+=2===r?this._encodeByte(n>>>6&63):this._paddingCharacter||"",t+=this._paddingCharacter||""),t},e.prototype.maxDecodedLength=function(e){return this._paddingCharacter?e/4*3|0:(6*e+7)/8|0},e.prototype.decodedLength=function(e){return this.maxDecodedLength(e.length-this._getPaddingLength(e))},e.prototype.decode=function(e){if(0===e.length)/* @__PURE__ */return new Uint8Array(0);for(var t=this._getPaddingLength(e),s=e.length-t,r=new Uint8Array(this.maxDecodedLength(s)),i=0,o=0,a=0,c=0,l=0,h=0,d=0;o<s-4;o+=4)c=this._decodeChar(e.charCodeAt(o+0)),l=this._decodeChar(e.charCodeAt(o+1)),h=this._decodeChar(e.charCodeAt(o+2)),d=this._decodeChar(e.charCodeAt(o+3)),r[i++]=c<<2|l>>>4,r[i++]=l<<4|h>>>2,r[i++]=h<<6|d,a|=c&n,a|=l&n,a|=h&n,a|=d&n;if(o<s-1&&(c=this._decodeChar(e.charCodeAt(o)),l=this._decodeChar(e.charCodeAt(o+1)),r[i++]=c<<2|l>>>4,a|=c&n,a|=l&n),o<s-2&&(h=this._decodeChar(e.charCodeAt(o+2)),r[i++]=l<<4|h>>>2,a|=h&n),o<s-3&&(d=this._decodeChar(e.charCodeAt(o+3)),r[i++]=h<<6|d,a|=d&n),0!==a)throw new Error("Base64Coder: incorrect characters for decoding");return r},e.prototype._encodeByte=function(e){var t=e;return t+=65,t+=25-e>>>8&6,t+=51-e>>>8&-75,t+=61-e>>>8&-15,t+=62-e>>>8&3,String.fromCharCode(t)},e.prototype._decodeChar=function(e){var t=n;return t+=(42-e&e-44)>>>8&-256+e-43+62,t+=(46-e&e-48)>>>8&-256+e-47+63,t+=(47-e&e-58)>>>8&-256+e-48+52,(t+=(64-e&e-91)>>>8&-256+e-65+0)+((96-e&e-123)>>>8&-256+e-97+26)},e.prototype._getPaddingLength=function(e){var t=0;if(this._paddingCharacter){for(var s=e.length-1;s>=0&&e[s]===this._paddingCharacter;s--)t++;if(e.length<4||t>2)throw new Error("Base64Coder: incorrect padding")}return t},e}();e.Coder=r;var i=new r;e.encode=function(e){return i.encode(e)},e.decode=function(e){return i.decode(e)};var o=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return s(t,e),t.prototype._encodeByte=function(e){var t=e;return t+=65,t+=25-e>>>8&6,t+=51-e>>>8&-75,t+=61-e>>>8&-13,t+=62-e>>>8&49,String.fromCharCode(t)},t.prototype._decodeChar=function(e){var t=n;return t+=(44-e&e-46)>>>8&-256+e-45+62,t+=(94-e&e-96)>>>8&-256+e-95+63,t+=(47-e&e-58)>>>8&-256+e-48+52,(t+=(64-e&e-91)>>>8&-256+e-65+0)+((96-e&e-123)>>>8&-256+e-97+26)},t}(r);e.URLSafeCoder=o;var a=new o;e.encodeURLSafe=function(e){return a.encode(e)},e.decodeURLSafe=function(e){return a.decode(e)},e.encodedLength=function(e){return i.encodedLength(e)},e.maxDecodedLength=function(e){return i.maxDecodedLength(e)},e.decodedLength=function(e){return i.decodedLength(e)}}),Ls=/* @__PURE__ */t((e,t)=>{!function(e){var s={};!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 s(e,s,n,r,i){for(var o,a,c,l,h,d,u,p,f,g,m,_,w;i>=64;){for(o=s[0],a=s[1],c=s[2],l=s[3],h=s[4],d=s[5],u=s[6],p=s[7],g=0;g<16;g++)m=r+4*g,e[g]=(255&n[m])<<24|(255&n[m+1])<<16|(255&n[m+2])<<8|255&n[m+3];for(g=16;g<64;g++)_=((f=e[g-2])>>>17|f<<15)^(f>>>19|f<<13)^f>>>10,w=((f=e[g-15])>>>7|f<<25)^(f>>>18|f<<14)^f>>>3,e[g]=(_+e[g-7]|0)+(w+e[g-16]|0);for(g=0;g<64;g++)_=(((h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7))+(h&d^~h&u)|0)+(p+(t[g]+e[g]|0)|0)|0,w=((o>>>2|o<<30)^(o>>>13|o<<19)^(o>>>22|o<<10))+(o&a^o&c^a&c)|0,p=u,u=d,d=h,h=l+_|0,l=c,c=a,a=o,o=_+w|0;s[0]+=o,s[1]+=a,s[2]+=c,s[3]+=l,s[4]+=h,s[5]+=d,s[6]+=u,s[7]+=p,r+=64,i-=64}return r}var n=function(){function t(){this.digestLength=e.digestLength,this.blockSize=e.blockSize,this.state=/* @__PURE__ */new Int32Array(8),this.temp=/* @__PURE__ */new Int32Array(64),this.buffer=/* @__PURE__ */new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return t.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},t.prototype.clean=function(){for(var e=0;e<this.buffer.length;e++)this.buffer[e]=0;for(e=0;e<this.temp.length;e++)this.temp[e]=0;this.reset()},t.prototype.update=function(e,t){if(void 0===t&&(t=e.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");var n=0;if(this.bytesHashed+=t,this.bufferLength>0){for(;this.bufferLength<64&&t>0;)this.buffer[this.bufferLength++]=e[n++],t--;64===this.bufferLength&&(s(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(t>=64&&(n=s(this.temp,this.state,e,n,t),t%=64);t>0;)this.buffer[this.bufferLength++]=e[n++],t--;return this},t.prototype.finish=function(e){if(!this.finished){var t=this.bytesHashed,n=this.bufferLength,r=t/536870912|0,i=t<<3,o=t%64<56?64:128;this.buffer[n]=128;for(var a=n+1;a<o-8;a++)this.buffer[a]=0;this.buffer[o-8]=r>>>24&255,this.buffer[o-7]=r>>>16&255,this.buffer[o-6]=r>>>8&255,this.buffer[o-5]=r>>>0&255,this.buffer[o-4]=i>>>24&255,this.buffer[o-3]=i>>>16&255,this.buffer[o-2]=i>>>8&255,this.buffer[o-1]=i>>>0&255,s(this.temp,this.state,this.buffer,0,o),this.finished=!0}for(a=0;a<8;a++)e[4*a+0]=this.state[a]>>>24&255,e[4*a+1]=this.state[a]>>>16&255,e[4*a+2]=this.state[a]>>>8&255,e[4*a+3]=this.state[a]>>>0&255;return this},t.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},t.prototype._saveState=function(e){for(var t=0;t<this.state.length;t++)e[t]=this.state[t]},t.prototype._restoreState=function(e,t){for(var s=0;s<this.state.length;s++)this.state[s]=e[s];this.bytesHashed=t,this.finished=!1,this.bufferLength=0},t}();e.Hash=n;var r=function(){function e(e){this.inner=new n,this.outer=new n,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var t=new Uint8Array(this.blockSize);if(e.length>this.blockSize)(new n).update(e).finish(t).clean();else for(var s=0;s<e.length;s++)t[s]=e[s];for(s=0;s<t.length;s++)t[s]^=54;for(this.inner.update(t),s=0;s<t.length;s++)t[s]^=106;for(this.outer.update(t),this.istate=/* @__PURE__ */new Uint32Array(8),this.ostate=/* @__PURE__ */new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate),s=0;s<t.length;s++)t[s]=0}return e.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},e.prototype.clean=function(){for(var e=0;e<this.istate.length;e++)this.ostate[e]=this.istate[e]=0;this.inner.clean(),this.outer.clean()},e.prototype.update=function(e){return this.inner.update(e),this},e.prototype.finish=function(e){return this.outer.finished?this.outer.finish(e):(this.inner.finish(e),this.outer.update(e,this.digestLength).finish(e)),this},e.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},e}();function i(e){var t=(new n).update(e),s=t.digest();return t.clean(),s}function o(e,t){var s=new r(e).update(t),n=s.digest();return s.clean(),n}function a(e,t,s,n){var r=n[0];if(0===r)throw new Error("hkdf: cannot expand more");t.reset(),r>1&&t.update(e),s&&t.update(s),t.update(n),t.finish(e),n[0]++}e.HMAC=r,e.hash=i,e.default=i,e.hmac=o;var c=new Uint8Array(e.digestLength);e.hkdf=function(e,t,s,n){void 0===t&&(t=c),void 0===n&&(n=32);for(var i=new Uint8Array([1]),l=new r(o(t,e)),h=new Uint8Array(l.digestLength),d=h.length,u=new Uint8Array(n),p=0;p<n;p++)d===h.length&&(a(h,l,s,i),d=0),u[p]=h[d++];return l.clean(),h.fill(0),i.fill(0),u},e.pbkdf2=function(e,t,s,n){for(var i=new r(e),o=i.digestLength,a=/* @__PURE__ */new Uint8Array(4),c=new Uint8Array(o),l=new Uint8Array(o),h=new Uint8Array(n),d=0;d*o<n;d++){var u=d+1;a[0]=u>>>24&255,a[1]=u>>>16&255,a[2]=u>>>8&255,a[3]=u>>>0&255,i.reset(),i.update(t),i.update(a),i.finish(l);for(var p=0;p<o;p++)c[p]=l[p];for(p=2;p<=s;p++){i.reset(),i.update(l).finish(l);for(var f=0;f<o;f++)c[f]^=l[f]}for(p=0;p<o&&d*o+p<n;p++)h[d*o+p]=c[p]}for(d=0;d<o;d++)c[d]=l[d]=0;for(d=0;d<4;d++)a[d]=0;return i.clean(),h}}(s);var n=s.default;for(var r in s)n[r]=s[r];"object"==typeof t&&"object"==typeof t.exports?t.exports=n:"function"==typeof define&&define.amd?define(function(){return n}):e.sha256=n}(e)}),Ns=/* @__PURE__ */t(e=>{function t(e,t=""){if(!e)throw new Error(t)}Object.defineProperty(e,"__esModule",{value:!0}),e.timingSafeEqual=function(e,s){if(e.byteLength!==s.byteLength)return!1;e instanceof DataView||(e=new DataView(ArrayBuffer.isView(e)?e.buffer:e)),s instanceof DataView||(s=new DataView(ArrayBuffer.isView(s)?s.buffer:s)),t(e instanceof DataView),t(s instanceof DataView);const n=e.byteLength;let r=0,i=-1;for(;++i<n;)r|=e.getUint8(i)^s.getUint8(i);return 0===r}}),qs=/* @__PURE__ */t(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Webhook=e.WebhookVerificationError=void 0;var t=Cs(),s=Ls(),n=Ns(),r=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype),this.name="ExtendableError",this.stack=new Error(t).stack}},i=class e extends r{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype),this.name="WebhookVerificationError"}};e.WebhookVerificationError=i;var o=class e{constructor(s,n){if("raw"===(null==n?void 0:n.format))s instanceof Uint8Array?this.key=s:this.key=Uint8Array.from(s,e=>e.charCodeAt(0));else{if("string"!=typeof s)throw new Error("Expected secret to be of type string");s.startsWith(e.prefix)&&(s=s.substring(e.prefix.length)),this.key=t.decode(s)}if(0===this.key.length)throw new Error("Secret can't be empty.")}verify(e,t,s){var r;const o=null===(r=null==s?void 0:s.jsonParse)||void 0===r||r,a={};for(const n of Object.keys(t))a[n.toLowerCase()]=t[n];const c=a["webhook-id"],l=a["webhook-signature"],h=a["webhook-timestamp"];if(!l||!c||!h)throw new i("Missing required headers");const d=this.verifyTimestamp(h),u=this.sign(c,d,e).split(",")[1],p=l.split(" "),f=new globalThis.TextEncoder;for(const i of p){const[t,s]=i.split(",");if("v1"===t&&(0,n.timingSafeEqual)(f.encode(s),f.encode(u))){const t=e.toString();if(""===t)return;return o?JSON.parse(t):void 0}}throw new i("No matching signature found")}sign(e,n,r){if("string"==typeof r);else{if("Buffer"!==r.constructor.name)throw new Error("Expected payload to be of type string or Buffer.");r=r.toString()}const i=new TextEncoder,o=Math.floor(n.getTime()/1e3),a=i.encode(`${e}.${o}.${r}`);return`v1,${t.encode(s.hmac(this.key,a))}`}verifyTimestamp(e){const t=Math.floor(Date.now()/1e3),s=parseInt(e,10);if(Number.isNaN(s))throw new i("Invalid Signature Headers");if(t-s>300)throw new i("Message timestamp too old");if(s>t+300)throw new i("Message timestamp too new");/* @__PURE__ */
2
- return new Date(1e3*s)}};e.Webhook=o,o.prefix="whsec_"}),Ws=qs(),js=class extends Gt{parseUnverified(e){return JSON.parse(e)}unwrap(e,t){const s=t?.headers;if(null==s)throw new Error("Webhook headers are required in order to verify the signature");const n=void 0===t.key?this._client.webhookKey:t.key;if(!n)throw new Error("Webhook key must not be null or empty in order to unwrap");return new Ws.Webhook(n).verify(e,s),JSON.parse(e)}},Us=class extends Gt{list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(os`/v1/agents/${e}/versions?beta=true`,qt,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},Ds=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.versions=new Us(this._client)}create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/agents?beta=true",{body:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.get(os`/v1/agents/${e}?beta=true`,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}update(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/agents/${e}?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/agents?beta=true",qt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}archive(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/agents/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Versions=Us,e})();function Hs(e,t){if(!e)return()=>{};if(e.aborted)return t.abort(),()=>{};const s=()=>t.abort();return e.addEventListener("abort",s),()=>e.removeEventListener("abort",s)}function zs(e,t){return e instanceof L&&e.status===t}function Fs(e){return function(e){return e instanceof L&&"number"==typeof e.status&&e.status>=400&&e.status<500}(e)&&!zs(e,408)&&!zs(e,409)&&!zs(e,429)}function Bs(e,t,s){return Math.min(t*2**e,s)}function Ks(e,t){return e+Math.random()*(t-e)}function Js(e){return e*(1-.25*Math.random())}function Vs(e,{authToken:t,helper:s}){if(!t)throw new C(`copyClientForHelper: expected a non-empty authToken but received ${JSON.stringify(t)}`);const n=e,r=n._options.defaultHeaders,i=n._authState?.extraHeaders,o=i?Object.fromEntries(Object.entries(i).filter(([e])=>{const t=e.toLowerCase();return"authorization"!==t&&"x-api-key"!==t})):void 0,a=ss([o,r,{[hs]:s}]);return e.withOptions({apiKey:null,authToken:t,baseURL:e.baseURL,credentials:void 0,defaultHeaders:a})}var Xs=/* @__PURE__ */(()=>{class e{constructor(e){ws.set(this,void 0),ys.set(this,!1),bs.set(this,void 0),vs.set(this,void 0),ks.set(this,void 0),Ss.set(this,void 0),xs.set(this,void 0),Rs.set(this,void 0),Is.set(this,void 0),this.client=e.client,this.environmentId=e.environmentId,this.environmentKey=e.environmentKey,this.workerId=e.workerId??function(){const e=(globalThis.process?.env)?.HOSTNAME;return e?`${e}-${ct()}`:ct()}(),X(this,ws,Vs(e.client,{authToken:e.environmentKey,helper:"environments-work-poller"}),"f"),X(this,ks,e.autoStop??!0,"f"),X(this,Ss,e.drain??!1,"f"),X(this,xs,void 0===e.blockMs?999:e.blockMs,"f"),X(this,Rs,e.reclaimOlderThanMs??null,"f"),X(this,Is,e.requestOptions,"f"),X(this,bs,new AbortController,"f"),X(this,vs,Hs(e.signal,G(this,bs,"f")),"f")}get signal(){return G(this,bs,"f").signal}abort(){G(this,bs,"f").abort()}async*[(ws=/* @__PURE__ */new WeakMap,ys=/* @__PURE__ */new WeakMap,bs=/* @__PURE__ */new WeakMap,vs=/* @__PURE__ */new WeakMap,ks=/* @__PURE__ */new WeakMap,Ss=/* @__PURE__ */new WeakMap,xs=/* @__PURE__ */new WeakMap,Rs=/* @__PURE__ */new WeakMap,Is=/* @__PURE__ */new WeakMap,Symbol.asyncIterator)](){if(G(this,ys,"f"))throw new C("Cannot iterate over a consumed WorkPoller");X(this,ys,!0,"f");const e=rt(this.client);e.info("poller starting",{component:"work-poller",environment_id:this.environmentId});const t=new Cn(e,this.environmentId);try{let n=0;for(;!G(this,bs,"f").signal.aborted;){let r;try{r=await G(this,ws,"f").beta.environments.work.poll(this.environmentId,{"Anthropic-Worker-ID":this.workerId,...null!==G(this,xs,"f")?{block_ms:G(this,xs,"f")}:{},...null!==G(this,Rs,"f")?{reclaim_older_than_ms:G(this,Rs,"f")}:{}},{headers:ss([G(this,Is,"f")?.headers]),signal:G(this,bs,"f").signal})}catch(s){if(G(this,bs,"f").signal.aborted)return;if(Fs(s))throw e.error("poll failed permanently, stopping poller",{error:String(s)}),s;const t=Js(Gs(n));e.warn("poll failed, backing off",{error:String(s),backoff_ms:t}),n++,await oe(t,G(this,bs,"f").signal);continue}if(n=0,null!=r){t.onClaim(),e.info("claimed work",{component:"work-poller",environment_id:this.environmentId,work_id:r.id,work_type:r.data.type});try{await G(this,ws,"f").beta.environments.work.ack(r.id,{environment_id:r.environment_id},{headers:ss([G(this,Is,"f")?.headers]),signal:G(this,bs,"f").signal})}catch(s){e.error("ack failed",{work_id:r.id,error:String(s)});continue}try{yield r}finally{if(G(this,ks,"f"))try{await G(this,ws,"f").beta.environments.work.stop(r.id,{environment_id:r.environment_id},{headers:ss([G(this,Is,"f")?.headers])})}catch(s){zs(s,409)||e.warn("stop failed",{work_id:r.id,error:String(s)})}}}else{if(G(this,Ss,"f"))return;t.onEmptyPoll(),await oe(Ks(1e3,3e3),G(this,bs,"f").signal)}}}finally{G(this,vs,"f").call(this)}}}return e})();function Gs(e){return Bs(e,1e3,6e4)}var Ys,Qs,Zs,en,tn,sn,nn,rn,on,an,cn,ln,hn,dn,un,pn,fn,gn,mn,_n,wn,yn,bn,vn,kn,Sn,xn,Rn,In,An,$n,Tn,En,Mn,On,Pn,Cn=/* @__PURE__ */(()=>(As=/* @__PURE__ */new WeakMap,$s=/* @__PURE__ */new WeakMap,Ts=/* @__PURE__ */new WeakMap,Es=/* @__PURE__ */new WeakMap,class{constructor(e,t){As.set(this,void 0),$s.set(this,void 0),Ts.set(this,void 0),Es.set(this,0),X(this,As,e,"f"),X(this,$s,t,"f")}onEmptyPoll(){const e=Date.now(),t={component:"work-poller",environment_id:G(this,$s,"f")};void 0===G(this,Ts,"f")?(X(this,Ts,X(this,Es,e,"f"),"f"),G(this,As,"f").info("idle; polling for work",t)):e-G(this,Es,"f")>=3e5?(X(this,Es,e,"f"),G(this,As,"f").info(`still polling; idle for ${Math.round((e-G(this,Ts,"f"))/1e3)}s`,t)):G(this,As,"f").debug("poll returned no work",t)}onClaim(){X(this,Ts,void 0,"f")}}))(),Ln=/* @__PURE__ */(()=>(Ys=/* @__PURE__ */new WeakMap,Qs=/* @__PURE__ */new WeakMap,Zs=/* @__PURE__ */new WeakMap,class{constructor(){Ys.set(this,[]),Qs.set(this,[]),Zs.set(this,!1)}push(e){if(G(this,Zs,"f"))return!1;const t=G(this,Qs,"f").shift();return t?t({done:!1,value:e}):G(this,Ys,"f").push(e),!0}close(){if(!G(this,Zs,"f"))for(X(this,Zs,!0,"f");G(this,Qs,"f").length>0;)G(this,Qs,"f").shift()({done:!0,value:void 0})}next(e){return G(this,Ys,"f").length>0?Promise.resolve({done:!1,value:G(this,Ys,"f").shift()}):G(this,Zs,"f")||e?.aborted?Promise.resolve({done:!0,value:void 0}):new Promise(t=>{const s=s=>{e?.removeEventListener("abort",n),t(s)},n=()=>{const e=G(this,Qs,"f").indexOf(s);e>=0&&G(this,Qs,"f").splice(e,1),t({done:!0,value:void 0})};G(this,Qs,"f").push(s),e?.addEventListener("abort",n,{once:!0})})}tryShift(){return G(this,Ys,"f").shift()}}))(),Nn=/* @__PURE__ */(()=>{class e extends Error{constructor(e){super("string"==typeof e?e:e.map(e=>"text"===e.type?e.text:`[${e.type}]`).join(" ")),this.name="ToolError",this.content=e}}return e})();function qn(e){return"name"in e?e.name:"mcp_server_name"in e?e.mcp_server_name:e.type}function Wn(e){return e instanceof Nn?e.content:`Error: ${e instanceof Error?e.message:String(e)}`}function jn(e){return"session.status_idle"===e.type&&"end_turn"===e.stop_reason?.type}var Un,Dn,Hn,zn,Fn,Bn=/* @__PURE__ */(()=>(en=/* @__PURE__ */new WeakMap,tn=/* @__PURE__ */new WeakMap,sn=/* @__PURE__ */new WeakMap,nn=/* @__PURE__ */new WeakMap,rn=/* @__PURE__ */new WeakMap,class{constructor(e,t){en.set(this,void 0),tn.set(this,void 0),sn.set(this,/* @__PURE__ */new Set),nn.set(this,!1),rn.set(this,void 0),X(this,en,e,"f"),X(this,tn,t,"f")}noteEvent(e){"user.tool_confirmation"!==e.type&&(jn(e)?this.arm():this.disarm())}block(e){G(this,sn,"f").add(e),void 0!==G(this,rn,"f")&&(X(this,nn,!0,"f"),clearTimeout(G(this,rn,"f")),X(this,rn,void 0,"f"))}unblock(e){G(this,sn,"f").delete(e),0===G(this,sn,"f").size&&G(this,nn,"f")&&this.arm()}arm(){G(this,en,"f")<=0||(G(this,sn,"f").size>0?X(this,nn,!0,"f"):(X(this,nn,!1,"f"),void 0!==G(this,rn,"f")&&clearTimeout(G(this,rn,"f")),X(this,rn,setTimeout(G(this,tn,"f"),G(this,en,"f")),"f")))}disarm(){X(this,nn,!1,"f"),void 0!==G(this,rn,"f")&&(clearTimeout(G(this,rn,"f")),X(this,rn,void 0,"f"))}}))(),Kn=/* @__PURE__ */(()=>{class e{constructor(e,t){on.add(this),an.set(this,!1),cn.set(this,void 0),ln.set(this,void 0),hn.set(this,void 0),dn.set(this,void 0),un.set(this,void 0),pn.set(this,/* @__PURE__ */new Set),fn.set(this,/* @__PURE__ */new Set),gn.set(this,/* @__PURE__ */new Map),mn.set(this,/* @__PURE__ */new Map),_n.set(this,new Ln),wn.set(this,0),yn.set(this,3e5),bn.set(this,null),vn.set(this,void 0),this.client=t.client,this.sessionId=e,this.tools=t.tools,this.maxIdleMs=t.maxIdleMs??6e4,X(this,un,rt(t.client),"f"),X(this,dn,new Map(t.tools.map(e=>[qn(e),e])),"f"),X(this,cn,new AbortController,"f"),X(this,ln,Hs(t.signal,G(this,cn,"f")),"f"),X(this,hn,t.requestOptions,"f"),X(this,vn,new Bn(this.maxIdleMs,()=>{G(this,un,"f").info("session idle after end_turn; stopping",{component:"session-tool-runner",session_id:this.sessionId,max_idle_ms:this.maxIdleMs}),G(this,cn,"f").abort()}),"f")}get signal(){return G(this,cn,"f").signal}abort(){G(this,cn,"f").abort()}_setSendRetryWindow(e){X(this,yn,e,"f")}async*[(an=/* @__PURE__ */new WeakMap,cn=/* @__PURE__ */new WeakMap,ln=/* @__PURE__ */new WeakMap,hn=/* @__PURE__ */new WeakMap,dn=/* @__PURE__ */new WeakMap,un=/* @__PURE__ */new WeakMap,pn=/* @__PURE__ */new WeakMap,fn=/* @__PURE__ */new WeakMap,gn=/* @__PURE__ */new WeakMap,mn=/* @__PURE__ */new WeakMap,_n=/* @__PURE__ */new WeakMap,wn=/* @__PURE__ */new WeakMap,yn=/* @__PURE__ */new WeakMap,bn=/* @__PURE__ */new WeakMap,vn=/* @__PURE__ */new WeakMap,on=/* @__PURE__ */new WeakSet,Symbol.asyncIterator)](){if(G(this,an,"f"))throw new C("Cannot iterate over a consumed SessionToolRunner");X(this,an,!0,"f"),G(this,un,"f").info("session tool runner starting",{component:"session-tool-runner",session_id:this.sessionId});const e=G(this,on,"m",Sn).call(this).catch(e=>{G(this,cn,"f").signal.aborted||G(this,un,"f").error("stream loop failed",{error:String(e)}),G(this,cn,"f").abort()});try{for(;;){const e=await G(this,_n,"f").next(G(this,cn,"f").signal);if(e.done)break;yield e.value}let t;for(await e;void 0!==(t=G(this,_n,"f").tryShift());)yield t}finally{G(this,cn,"f").abort(),G(this,vn,"f").disarm(),await e;try{await G(this,on,"m",Pn).call(this)}catch(t){G(this,un,"f").warn("drain failed",{error:String(t)})}G(this,_n,"f").close();for(const e of this.tools)try{await(e.close?.())}catch(t){G(this,un,"f").warn("tool.close failed",{tool:qn(e),error:String(t)})}G(this,ln,"f").call(this)}}}return kn=function(){return{...G(this,hn,"f"),headers:ss([us("session-tool-runner"),G(this,hn,"f")?.headers]),signal:G(this,cn,"f").signal}},Sn=async function(){const e=G(this,cn,"f");let t=500;for(;!e.signal.aborted;){try{const e=await this.client.beta.sessions.events.stream(this.sessionId,{},G(this,on,"m",kn).call(this));await G(this,on,"m",xn).call(this);for await(const s of e)if(t=500,await G(this,on,"m",In).call(this,s))return}catch(s){if(e.signal.throwIfAborted(),Fs(s))throw G(this,un,"f").error("permanent stream failure, shutting down",{error:String(s)}),e.abort(),s;G(this,un,"f").warn("stream disconnected, reconnecting",{error:String(s),backoff_ms:t})}e.signal.throwIfAborted(),await oe(t,e.signal),t=Math.min(2*t,1e4)}},xn=async function(){const e=G(this,cn,"f"),t=[];let s=!1;try{for await(const e of this.client.beta.sessions.events.list(this.sessionId,{limit:1e3},G(this,on,"m",kn).call(this)))G(this,on,"m",Rn).call(this,e,t),s=jn(e)}catch(i){e.signal.throwIfAborted(),G(this,un,"f").warn("reconcile list failed",{error:String(i)});for(const e of t)G(this,pn,"f").delete(e.id);return}const n=t.filter(e=>!G(this,fn,"f").has(e.id));G(this,vn,"f").disarm();for(const o of n)await G(this,on,"m",An).call(this,o);for(const o of[...G(this,mn,"f").values()]){const e=G(this,gn,"f").get(o.id);void 0!==e&&await G(this,on,"m",Tn).call(this,o,e)}const r=n.filter(e=>!G(this,fn,"f").has(e.id)&&!G(this,mn,"f").has(e.id));s&&0===r.length?G(this,vn,"f").arm():G(this,vn,"f").disarm()},Rn=function(e,t){"agent.tool_use"===e.type||"agent.custom_tool_use"===e.type?(G(this,pn,"f").add(e.id),G(this,fn,"f").has(e.id)||t.push(e)):"user.tool_result"===e.type?G(this,fn,"f").add(e.tool_use_id):"user.custom_tool_result"===e.type?G(this,fn,"f").add(e.custom_tool_use_id):"user.tool_confirmation"===e.type&&(G(this,fn,"f").has(e.tool_use_id)||G(this,gn,"f").set(e.tool_use_id,e.result))},In=async function(e){switch(G(this,vn,"f").noteEvent(e),e.type){case"agent.tool_use":case"agent.custom_tool_use":return G(this,pn,"f").has(e.id)||(G(this,pn,"f").add(e.id),await G(this,on,"m",An).call(this,e)),!1;case"user.tool_confirmation":return await G(this,on,"m",$n).call(this,e),!1;case"user.tool_result":return G(this,fn,"f").add(e.tool_use_id),!1;case"user.custom_tool_result":return G(this,fn,"f").add(e.custom_tool_use_id),!1;case"session.status_terminated":case"session.deleted":return G(this,un,"f").info("session terminated",{component:"session-tool-runner",session_id:this.sessionId}),G(this,cn,"f").abort(),!0;default:return!1}},An=async function(e){const t=e.evaluated_permission,s="deny"===t?"deny":G(this,gn,"f").get(e.id);void 0!==s?await G(this,on,"m",Tn).call(this,e,s):void 0===t||"allow"===t?await G(this,on,"m",Mn).call(this,e,void 0):G(this,mn,"f").has(e.id)||(G(this,un,"f").info("tool call awaiting confirmation; holding",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),G(this,mn,"f").set(e.id,e),G(this,vn,"f").block(e.id))},$n=async function(e){G(this,gn,"f").set(e.tool_use_id,e.result);const t=G(this,mn,"f").get(e.tool_use_id);void 0!==t&&await G(this,on,"m",Tn).call(this,t,e.result)},Tn=async function(e,t){const s=G(this,mn,"f").delete(e.id);if("allow"!==t)s&&G(this,vn,"f").unblock(e.id),G(this,fn,"f").add(e.id),G(this,un,"f").info("tool call denied; not executing",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),G(this,on,"m",En).call(this,{event:e,toolUseId:e.id,name:e.name,isError:!1,posted:!1,confirmation:"deny"});else{G(this,un,"f").info("tool call confirmed",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),s||G(this,vn,"f").block(e.id);try{await G(this,on,"m",Mn).call(this,e,"allow")}finally{G(this,vn,"f").unblock(e.id)}}},En=function(e){G(this,_n,"f").push(e)},Mn=async function(e,t){var s,n;if(!G(this,fn,"f").has(e.id)){G(this,un,"f").info("executing tool",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),X(this,wn,(s=G(this,wn,"f"),++s),"f");try{const s=G(this,dn,"f").get(e.name);if(!s)return G(this,un,"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}),void G(this,on,"m",En).call(this,{event:e,toolUseId:e.id,name:e.name,isError:!1,posted:!1,confirmation:t});let n,r;const i=new AbortController,o=Hs(G(this,cn,"f").signal,i),a=setTimeout(()=>i.abort(),12e4);try{const t=await async function(e,t,s){try{const n=e.parse?e.parse(t):t;return{content:await e.run(n,s),isError:!1}}catch(n){return{content:Wn(n),isError:!0}}}(s,e.input,{toolUse:e,toolUseBlock:e,signal:i.signal});n=t.content,r=t.isError}finally{clearTimeout(a),o()}const c=function(e,t,s){return"agent.custom_tool_use"===e.type?{type:"user.custom_tool_result",custom_tool_use_id:e.id,is_error:t,content:s}:{type:"user.tool_result",tool_use_id:e.id,is_error:t,content:s}}(e,r,function(e){if("string"==typeof e)return[{type:"text",text:e||"(no output)"}];const t=e.map(e=>"text"===e.type?{type:"text",text:e.text||"(no output)"}:"image"===e.type||"document"===e.type?e:"search_result"===e.type?{type:"search_result",source:e.source,title:e.title,content:e.content.map(e=>({type:"text",text:e.text})),citations:{enabled:e.citations?.enabled??!1}}:{type:"text",text:JSON.stringify(e)});return t.length>0?t:[{type:"text",text:"(no output)"}]}(n)),l=await G(this,on,"m",On).call(this,c,e.id);G(this,on,"m",En).call(this,{event:e,result:c,toolUseId:e.id,name:e.name,isError:r,posted:l,confirmation:t})}finally{X(this,wn,(n=G(this,wn,"f"),--n),"f"),0===G(this,wn,"f")&&G(this,bn,"f")?.call(this)}}},On=async function(e,t){const s=G(this,cn,"f"),n=Date.now();let r,i=0;for(;;){i++,s.signal.throwIfAborted();try{return await this.client.beta.sessions.events.send(this.sessionId,{events:[e]},G(this,on,"m",kn).call(this)),G(this,fn,"f").add(t),!0}catch(o){if(r=o,Fs(o))break;const e=G(this,yn,"f")-(Date.now()-n);if(e<=0)break;const a=Math.min(Js(Bs(i-1,1e3,3e4)),e);G(this,un,"f").warn("tool result send failed; retrying",{tool_use_id:t,attempt:i,backoff_ms:a,error:String(o)}),await oe(a,s.signal)}}return G(this,un,"f").error("failed to send tool result",{tool_use_id:t,attempts:i,error:String(r)}),!1},Pn=async function(){0!==G(this,wn,"f")&&(await Promise.race([new Promise(e=>X(this,bn,e,"f")),oe(3e4)]),X(this,bn,null,"f"),G(this,wn,"f")>0&&G(this,un,"f").warn("drain timeout exceeded"))},e})();var Jn=/* @__PURE__ */(()=>(Dn=/* @__PURE__ */new WeakMap,Un=/* @__PURE__ */new WeakSet,Hn=async function(e,t,s){const n=rt(this.client),r=function(e){if(!e)return null;let t;try{const s=e.replace(/-/g,"+").replace(/_/g,"/"),n=s.padEnd(4*Math.ceil(s.length/4),"=");t=JSON.parse(Ve((e=>{if(void 0!==globalThis.Buffer){const t=globalThis.Buffer.from(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}if("undefined"!=typeof atob){const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s}throw new C("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")})(n)))}catch{return null}if(null===t||"object"!=typeof t||Array.isArray(t))return null;const s=t.sessions_token;return"string"==typeof s&&""!==s?s:null}(e.secret),i=r??t;if(void 0===i)throw new C("handleItem: the work item carried a secret payload but no sessions token could be extracted, and there is no environment key to fall back to; the poller must issue a secret whose payload carries `sessions_token`, or provide the environment key (pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY)");e.secret&&null===r&&n.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 o=Vs(this.client,{authToken:i,helper:"environments-worker"}),a=e.data.id,c=new AbortController,l=Hs(s,c),h=new Xn(c),d=await(import("./node.browser-DyPu4LvH.js"));let u,p;const f=async function(e,t,s,n,r){let i=3e4,o=9e4,a=Date.now(),c="NO_HEARTBEAT";const l=async()=>{const l=new AbortController,h=Hs(s.signal,l),d=setTimeout(()=>l.abort(),i);try{const h=await e.beta.environments.work.heartbeat(t.id,{environment_id:t.environment_id,expected_last_heartbeat:c},{...r,headers:ss([r?.headers]),signal:l.signal});a=Date.now(),c=h.last_heartbeat,h.ttl_seconds>0&&(o=1e3*h.ttl_seconds,i=Math.max(1e3,Math.min(o/2,3e4)),(e=>{u=e,p?._setSendRetryWindow(e)})?.(o)),"stopping"!==h.state&&"stopped"!==h.state||(n.info("heartbeat signals shutdown",{work_id:t.id,state:h.state}),s.finish("control_plane_stop")),h.lease_extended||(n.warn("lease not extended, shutting down",{work_id:t.id}),s.finish("control_plane_stop"))}catch(f){if(s.signal.throwIfAborted(),zs(f,412)){const e=function(e){let t=e instanceof L?e.error:void 0;for(const s of["error","details","current_state"]){if(!se(t))return{};t=t[s]}return se(t)?t:{}}(f);return n.error("lease lost: heartbeat precondition failed",{work_id:t.id,server_state:e.state,server_ttl_seconds:e.ttl_seconds,server_last_heartbeat:e.last_heartbeat}),void s.finish("lease_lost")}if(Fs(f))throw n.error("permanent heartbeat failure",{work_id:t.id,error:String(f)}),s.finish("heartbeat_rejected"),f;if(Date.now()-a>o)return n.error("lease assumed lost: no successful heartbeat in ttl",{work_id:t.id,ttl_ms:o,error:String(f)}),void s.finish("assumed_lost");n.warn("transient heartbeat failure",{work_id:t.id,error:String(f)})}finally{clearTimeout(d),h()}};for(await l();!s.signal.aborted;)await oe(i,s.signal),s.signal.throwIfAborted(),await l()}(o,e,h,n,this.requestOptions).catch(t=>{c.signal.aborted||n.error("heartbeat loop failed",{work_id:e.id,error:String(t)}),c.abort()});let g,m=async()=>{},_=!1;try{if("session"!==e.data.type)return void n.debug("skipping non-session work item",{work_id:e.id,type:e.data.type});const t=await o.beta.sessions.retrieve(a);if(null===r&&null!==this.memorySyncIntervalMs&&function(e){return e.resources.some(e=>"memory_store"===e.type)}(t))throw new d.SessionMemoryError(`cannot mount the session's memories: the work item carried no sessions token (work_id=${e.id}, session_id=${a}); 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 s={workdir:this.workdir,client:o,session:t,...void 0!==this.maxFileBytes?{maxFileBytes:this.maxFileBytes}:{}};try{m=await d.setupSkills(s)}catch(w){n.warn("skill setup failed",{session_id:a,work_id:e.id,error:String(w)})}null!==r&&null!==this.memorySyncIntervalMs?(g=new d.SessionMemoryStores(o,{workdir:this.workdir,...void 0!==this.memorySyncIntervalMs?{syncIntervalMs:this.memorySyncIntervalMs}:{},syncDeletions:this.memorySyncDeletions}),await g.download(t),s.allowedRoots=g.roots,s.readOnlyRoots=g.readOnlyRoots):n.debug("memory stores disabled for this item",{work_id:e.id});const i="function"==typeof this.tools?this.tools(s):this.tools??d.betaAgentToolset20260401(s);p=new Kn(a,{client:o,tools:i,...void 0!==this.maxIdleMs?{maxIdleMs:this.maxIdleMs}:{},...void 0!==this.requestOptions?{requestOptions:this.requestOptions}:{},signal:c.signal}),void 0!==u&&p._setSendRetryWindow(u);for await(const e of p)g&&await g.syncIfDue();_=!c.signal.aborted}finally{try{await m().catch(t=>{n.warn("skill cleanup failed",{session_id:a,work_id:e.id,error:String(t)})})}finally{if(g){const t=d.MEMORY_FLUSH_TIMEOUT_MS;_&&await Vn(g.finish(),t)&&n.warn(`final memory sync cut off after ${t}ms; the flush that follows still uploads changed files`,{session_id:a,work_id:e.id});const s=new AbortController;await Vn(g.flushWrites(s.signal),t)&&(s.abort(),n.warn(`memory flush cut off after ${t}ms; changed files it had not uploaded yet are not saved`,{session_id:a,work_id:e.id})),await g.dispose().catch(t=>{n.warn("memory store cleanup failed",{session_id:a,work_id:e.id,error:String(t)})})}}h.finish("runner_done"),l(),await f,h.lost?n.info("lease lost; released without stopping it",{session_id:a,work_id:e.id}):await async function(e,t,s,n){try{await e.beta.environments.work.stop(t.id,{environment_id:t.environment_id,force:!0},{...n,headers:ss([n?.headers])})}catch(w){zs(w,409)||s.error("force-stop on exit failed",{work_id:t.id,error:String(w)})}}(o,e,n,this.requestOptions)}},class{constructor(e){if(Un.add(this),Dn.set(this,void 0),void 0!==e.unrestrictedPaths)throw new C("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,null!=e.memorySyncIntervalMs&&function(e){if(!(e>=5e3))throw new C(`memorySyncIntervalMs must be at least 5000ms (got ${e}); to run without memory sync, pass \`memorySyncIntervalMs: null\` to the worker instead`)}(e.memorySyncIntervalMs),this.memorySyncIntervalMs=e.memorySyncIntervalMs,this.memorySyncDeletions=e.memorySyncDeletions??"enabled",this.workerId=e.workerId,this.requestOptions=e.requestOptions,X(this,Dn,e.signal,"f")}async run(e){const{environmentId:t,environmentKey:s}=this;if(void 0===t||void 0===s)throw new C("EnvironmentWorker.run: environmentId and environmentKey are required to poll for work");const n=e??G(this,Dn,"f"),r=new Xs({client:this.client,environmentId:t,environmentKey:s,...void 0!==this.workerId?{workerId:this.workerId}:{},...n?{signal:n}:{},...void 0!==this.requestOptions?{requestOptions:this.requestOptions}:{},autoStop:!1});for await(const o of r)try{await G(this,Un,"m",Hn).call(this,o,s,r.signal)}catch(i){if(r.signal?.aborted)throw i;rt(this.client).error("work item failed",{work_id:o.id,error:String(i)})}}async handleItem(e){const t=e?.workId??Ke("ANTHROPIC_WORK_ID"),s=e?.environmentId??Ke("ANTHROPIC_ENVIRONMENT_ID"),n=e?.sessionId??Ke("ANTHROPIC_SESSION_ID"),r=(e?.environmentKey??this.environmentKey??Ke("ANTHROPIC_ENVIRONMENT_KEY"))||void 0,i=e?.workSecret||Ke("ANTHROPIC_WORK_SECRET")||null;if(!t)throw new C("handleItem: workId is required — pass it or set ANTHROPIC_WORK_ID");if(!s)throw new C("handleItem: environmentId is required — pass it or set ANTHROPIC_ENVIRONMENT_ID");if(!n)throw new C("handleItem: sessionId is required — pass it or set ANTHROPIC_SESSION_ID");if(!r&&!i)throw new C("handleItem: environmentKey is required when there is no work secret — pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY");const o={id:t,environment_id:s,secret:i,data:{type:"session",id:n}};await G(this,Un,"m",Hn).call(this,o,r,e?.signal??G(this,Dn,"f"))}}))();async function Vn(e,t){let s;try{return await Promise.race([e.then(()=>!1,()=>!1),new Promise(e=>{s=setTimeout(()=>e(!0),t)})])}finally{void 0!==s&&clearTimeout(s)}}var Xn=/* @__PURE__ */(()=>(zn=/* @__PURE__ */new WeakMap,Fn=/* @__PURE__ */new WeakMap,class{constructor(e){zn.set(this,void 0),Fn.set(this,void 0),X(this,zn,e,"f")}get signal(){return G(this,zn,"f").signal}finish(e){X(this,Fn,G(this,Fn,"f")??e,"f"),G(this,zn,"f").abort()}get lost(){return"lease_lost"===G(this,Fn,"f")||"assumed_lost"===G(this,Fn,"f")}}))(),Gn=/* @__PURE__ */(()=>{class e extends Gt{retrieve(e,t,s){const{environment_id:n,betas:r,workspace_id:i}=t;return this._client.get(os`/v1/environments/${n}/work/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}update(e,t,s){const{environment_id:n,betas:r,workspace_id:i,...o}=t;return this._client.post(os`/v1/environments/${n}/work/${e}?beta=true`,{body:o,...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}list(e,t={},s){const{betas:n,...r}=t??{};return this._client.getAPIList(os`/v1/environments/${e}/work?beta=true`,qt,{query:r,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}ack(e,t,s){const{environment_id:n,betas:r}=t;return this._client.post(os`/v1/environments/${n}/work/${e}/ack?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}heartbeat(e,t,s){const{environment_id:n,desired_ttl_seconds:r,expected_last_heartbeat:i,betas:o}=t;return this._client.post(os`/v1/environments/${n}/work/${e}/heartbeat?beta=true`,{query:{desired_ttl_seconds:r,expected_last_heartbeat:i},...s,headers:ss([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}poll(e,t={},s){const{betas:n,"Anthropic-Worker-ID":r,...i}=t??{};return this._client.get(os`/v1/environments/${e}/work/poll?beta=true`,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"Anthropic-Worker-ID":r}:void 0},s?.headers])})}stats(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/environments/${e}/work/stats?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}stop(e,t,s){const{environment_id:n,betas:r,workspace_id:i,...o}=t;return this._client.post(os`/v1/environments/${n}/work/${e}/stop?beta=true`,{body:o,...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}poller(e){return new Xs({...e,client:this._client})}worker(e){return new Jn({...e,client:this._client})}}return e.WorkPoller=Xs,e.EnvironmentWorker=Jn,e})(),Yn=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.work=new Gn(this._client)}create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/environments?beta=true",{body:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/environments/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}update(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/environments/${e}?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/environments?beta=true",qt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}delete(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.delete(os`/v1/environments/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}archive(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/environments/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Work=Gn,e})(),Qn=class extends Gt{create(e,t,s){const{view:n,betas:r,workspace_id:i,...o}=t;return this._client.post(os`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:n},body:o,...s,headers:ss([{"anthropic-beta":[...r??[],"agent-memory-2026-07-22"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}retrieve(e,t,s){const{memory_store_id:n,betas:r,workspace_id:i,...o}=t;return this._client.get(os`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:o,...s,headers:ss([{"anthropic-beta":[...r??[],"agent-memory-2026-07-22"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}update(e,t,s){const{memory_store_id:n,view:r,betas:i,workspace_id:o,...a}=t;return this._client.post(os`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:{view:r},body:a,...s,headers:ss([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...null!=o?{"anthropic-workspace-id":o}:void 0},s?.headers])})}list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(os`/v1/memory_stores/${e}/memories?beta=true`,qt,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"agent-memory-2026-07-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}delete(e,t,s){const{memory_store_id:n,expected_content_sha256:r,betas:i,workspace_id:o}=t;return this._client.delete(os`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:{expected_content_sha256:r},...s,headers:ss([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...null!=o?{"anthropic-workspace-id":o}:void 0},s?.headers])})}},Zn=class extends Gt{retrieve(e,t,s){const{memory_store_id:n,betas:r,workspace_id:i,...o}=t;return this._client.get(os`/v1/memory_stores/${n}/memory_versions/${e}?beta=true`,{query:o,...s,headers:ss([{"anthropic-beta":[...r??[],"agent-memory-2026-07-22"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(os`/v1/memory_stores/${e}/memory_versions?beta=true`,qt,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"agent-memory-2026-07-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}redact(e,t,s){const{memory_store_id:n,betas:r,workspace_id:i}=t;return this._client.post(os`/v1/memory_stores/${n}/memory_versions/${e}/redact?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"agent-memory-2026-07-22"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}},er=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.memories=new Qn(this._client),this.memoryVersions=new Zn(this._client)}create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/memory_stores?beta=true",{body:r,...t,headers:ss([{"anthropic-beta":[...s??[],"agent-memory-2026-07-22"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/memory_stores/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"agent-memory-2026-07-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}update(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/memory_stores/${e}?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"agent-memory-2026-07-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/memory_stores?beta=true",qt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"agent-memory-2026-07-22"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}delete(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.delete(os`/v1/memory_stores/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"agent-memory-2026-07-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}archive(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/memory_stores/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"agent-memory-2026-07-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Memories=Qn,e.MemoryVersions=Zn,e})(),tr=/* @__PURE__ */(()=>{class e{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new bt;for await(const t of this.iterator)for(const s of e.decode(t))yield JSON.parse(s);for(const t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(t,s){if(!t.body){if(s.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new C("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new C("Attempted to iterate over a response with no body")}return new e(me(t.body),s)}}return e})(),sr=class extends Gt{create(e,t){const{betas:s,user_profile_id:n,workspace_id:r,...i}=e;return this._client.post("/v1/messages/batches?beta=true",{body:i,...t,headers:ss([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...null!=n?{"anthropic-user-profile-id":n}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/messages/batches/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",Nt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}delete(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.delete(os`/v1/messages/batches/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}cancel(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/messages/batches/${e}/cancel?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}async results(e,t={},s){const n=await this.retrieve(e,t,s);if(!n.results_url)throw new C(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);const{betas:r,workspace_id:i}=t??{};return this._client.get(n.results_url,{...s,headers:ss([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>tr.fromResponse(t.response,t.controller))}},nr={"claude-opus-4@20250514":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function rr(e){return e?.output_format??e?.output_config?.format}function ir(e,t,s){const n=rr(t);return t&&"parse"in(n??{})?or(e,t,s):{...e,content:e.content.map(e=>{if("text"===e.type){const t=Object.defineProperty({...e},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(t,"parsed",{get:()=>(s.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null),enumerable:!1})}return e}),parsed_output:null}}function or(e,t,s){let n=null;const r=e.content.map(e=>{if("text"===e.type){const r=function(e,t){const s=rr(e);if("json_schema"!==s?.type)return null;try{return"parse"in s?s.parse(t):JSON.parse(t)}catch(n){throw new C(`Failed to parse structured output: ${n}`)}}(t,e.text);null===n&&(n=r);const i=Object.defineProperty({...e},"parsed_output",{value:r,enumerable:!1});return Object.defineProperty(i,"parsed",{get:()=>(s.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),r),enumerable:!1})}return e});return{...e,content:r,parsed_output:n}}var ar,cr,lr,hr,dr,ur,pr,fr,gr,mr,_r,wr,yr,br,vr,kr,Sr,xr,Rr,Ir,Ar,$r,Tr,Er,Mr,Or,Pr="__json_buf";function Cr(e,t){const s={};for(const i of Object.keys(e))"input"!==i&&(s[i]=e[i]);let n;Object.defineProperty(s,Pr,{value:t,enumerable:!1,writable:!0});let r=!1;return Object.defineProperty(s,"input",{enumerable:!0,configurable:!0,get:()=>(r||(n=t?(e=>JSON.parse((e=>{let t="";return e.map(e=>{"string"===e.type?t+='"'+e.value+'"':t+=e.value}),t})((e=>{let t=[];return e.map(e=>{"brace"===e.type&&("{"===e.value?t.push("}"):t.splice(t.lastIndexOf("}"),1)),"paren"===e.type&&("["===e.value?t.push("]"):t.splice(t.lastIndexOf("]"),1))}),t.length>0&&t.reverse().map(t=>{"}"===t?e.push({type:"brace",value:"}"}):"]"===t&&e.push({type:"paren",value:"]"})}),e})((e=>{let t=[];for(const i of e)"brace"!==i.type&&"paren"!==i.type||("{"===i.value||"["===i.value?t.push(i.value):t.pop());let s=t[t.length-1],n=e.length,r=/^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?$/;for(;n>0;){let t=e[n-1];switch(t.type){case"separator":n--;continue;case"number":if(t.unterminated||!r.test(t.value)){n--;continue}break;case"string":let i=e[n-2];if("{"===s&&("delimiter"===i?.type||"brace"===i?.type&&"{"===i.value)){n--;continue}break;case"delimiter":n--}break}return e.slice(0,n)})((e=>{let t=0,s=[];for(;t<e.length;){let n=e[t];if("\\"===n){t++;continue}if("{"===n){s.push({type:"brace",value:"{"}),t++;continue}if("}"===n){s.push({type:"brace",value:"}"}),t++;continue}if("["===n){s.push({type:"paren",value:"["}),t++;continue}if("]"===n){s.push({type:"paren",value:"]"}),t++;continue}if(":"===n){s.push({type:"separator",value:":"}),t++;continue}if(","===n){s.push({type:"delimiter",value:","}),t++;continue}if('"'===n){const n=t+1;let r=n,i=!1;for(;;){if(r=e.indexOf('"',r),-1===r){i=!0;break}let t=0,s=r-1;for(;s>=n&&"\\"===e[s];)t++,s--;if(t%2==0)break;r++}i?t=e.length:(s.push({type:"string",value:e.slice(n,r)}),t=r+1);continue}if(n&&/\s/.test(n)){t++;continue}let r=/[0-9]/;if(n&&r.test(n)||"-"===n||"."===n){let i="";for("-"===n&&(i+=n,n=e[++t]);n&&(r.test(n)||"."===n||"e"===n||"E"===n||("-"===n||"+"===n)&&("e"===i[i.length-1]||"E"===i[i.length-1]));)i+=n,n=e[++t];s.push({type:"number",value:i,unterminated:t===e.length});continue}let i=/[a-z]/i;if(n&&i.test(n)){let r="";for(;n&&i.test(n)&&t!==e.length;)r+=n,n=e[++t];if("true"!=r&&"false"!=r&&"null"!==r){t++;continue}s.push({type:"name",value:r});continue}t++}return s})(e))))))(t):{},r=!0),n)}),s}function Lr(e){return"tool_use"===e.type||"server_tool_use"===e.type||"mcp_tool_use"===e.type}var Nr,qr,Wr,jr,Ur,Dr,Hr,zr,Fr,Br,Kr,Jr,Vr,Xr,Gr,Yr,Qr,Zr,ei,ti,si,ni,ri,ii,oi,ai,ci,li,hi,di,ui,pi,fi,gi,mi,_i,wi,yi=/* @__PURE__ */(()=>{class e{constructor(e,t){ar.add(this),this.messages=[],this.receivedMessages=[],cr.set(this,void 0),lr.set(this,null),this.controller=new AbortController,hr.set(this,void 0),dr.set(this,()=>{}),ur.set(this,()=>{}),pr.set(this,void 0),fr.set(this,()=>{}),gr.set(this,()=>{}),mr.set(this,{}),_r.set(this,!1),wr.set(this,!1),yr.set(this,!1),br.set(this,!1),vr.set(this,void 0),kr.set(this,void 0),Sr.set(this,void 0),xr.set(this,void 0),Ar.set(this,e=>{if(X(this,wr,!0,"f"),O(e)&&(e=new N),e instanceof N)return X(this,yr,!0,"f"),this._emit("abort",e);if(e instanceof C)return this._emit("error",e);if(e instanceof Error){const t=new C(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new C(String(e)))}),X(this,hr,new Promise((e,t)=>{X(this,dr,e,"f"),X(this,ur,t,"f")}),"f"),X(this,pr,new Promise((e,t)=>{X(this,fr,e,"f"),X(this,gr,t,"f")}),"f"),G(this,hr,"f").catch(()=>{}),G(this,pr,"f").catch(()=>{}),X(this,lr,e,"f"),X(this,xr,t?.logger??console,"f")}get response(){return G(this,vr,"f")}get request_id(){return G(this,kr,"f")}get workspace_id(){return G(this,Sr,"f")}async withResponse(){X(this,br,!0,"f");const e=await G(this,hr,"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(t){const s=new e(null);return s._run(()=>s._fromReadableStream(t)),s}static createMessage(t,s,n,{logger:r}={}){const i=new e(s,{logger:r});for(const e of s.messages)i._addMessageParam(e);return X(i,lr,{...s,stream:!0},"f"),i._run(()=>i._createMessage(t,{...s,stream:!0},{...n,headers:{...n?.headers,[ds]:"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},G(this,Ar,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,s){const n=s?.signal;let r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener("abort",r));try{G(this,ar,"m",$r).call(this);const{response:n,data:r}=await e.create({...t,stream:!0},{...s,signal:this.controller.signal}).withResponse();this._connected(n);for await(const e of r)G(this,ar,"m",Tr).call(this,e);if(r.controller.signal?.aborted)throw new N;G(this,ar,"m",Er).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}_connected(e){this.ended||(X(this,vr,e,"f"),X(this,kr,e?.headers.get("request-id"),"f"),X(this,Sr,e?.headers.get("anthropic-workspace-id"),"f"),G(this,dr,"f").call(this,e),this._emit("connect"))}get ended(){return G(this,_r,"f")}get errored(){return G(this,wr,"f")}get aborted(){return G(this,yr,"f")}abort(){this.controller.abort()}on(e,t){return(G(this,mr,"f")[e]||(G(this,mr,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=G(this,mr,"f")[e];if(!s)return this;const n=s.findIndex(e=>e.listener===t);return n>=0&&s.splice(n,1),this}once(e,t){return(G(this,mr,"f")[e]||(G(this,mr,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{X(this,br,!0,"f"),"error"!==e&&this.once("error",s),this.once(e,t)})}async done(){X(this,br,!0,"f"),await G(this,pr,"f")}get currentMessage(){return G(this,cr,"f")}async finalMessage(){return await this.done(),G(this,ar,"m",Rr).call(this)}async finalText(){return await this.done(),G(this,ar,"m",Ir).call(this)}_emit(e,...t){if(G(this,_r,"f"))return;"end"===e&&(X(this,_r,!0,"f"),G(this,fr,"f").call(this));const s=G(this,mr,"f")[e];if(s&&(G(this,mr,"f")[e]=s.filter(e=>!e.once),s.forEach(({listener:e})=>e(...t))),"abort"===e){const e=t[0];return G(this,br,"f")||s?.length||Promise.reject(e),G(this,ur,"f").call(this,e),G(this,gr,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];G(this,br,"f")||s?.length||Promise.reject(e),G(this,ur,"f").call(this,e),G(this,gr,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",G(this,ar,"m",Rr).call(this))}async _fromReadableStream(e,t){const s=t?.signal;let n;s&&(s.aborted&&this.controller.abort(),n=this.controller.abort.bind(this.controller),s.addEventListener("abort",n));try{G(this,ar,"m",$r).call(this),this._connected(null);const t=kt.fromReadableStream(e,this.controller);for await(const e of t)G(this,ar,"m",Tr).call(this,e);if(t.controller.signal?.aborted)throw new N;G(this,ar,"m",Er).call(this)}finally{s&&n&&s.removeEventListener("abort",n)}}[(cr=/* @__PURE__ */new WeakMap,lr=/* @__PURE__ */new WeakMap,hr=/* @__PURE__ */new WeakMap,dr=/* @__PURE__ */new WeakMap,ur=/* @__PURE__ */new WeakMap,pr=/* @__PURE__ */new WeakMap,fr=/* @__PURE__ */new WeakMap,gr=/* @__PURE__ */new WeakMap,mr=/* @__PURE__ */new WeakMap,_r=/* @__PURE__ */new WeakMap,wr=/* @__PURE__ */new WeakMap,yr=/* @__PURE__ */new WeakMap,br=/* @__PURE__ */new WeakMap,vr=/* @__PURE__ */new WeakMap,kr=/* @__PURE__ */new WeakMap,Sr=/* @__PURE__ */new WeakMap,xr=/* @__PURE__ */new WeakMap,Ar=/* @__PURE__ */new WeakMap,ar=/* @__PURE__ */new WeakSet,Rr=function(){if(0===this.receivedMessages.length)throw new C("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Ir=function(){if(0===this.receivedMessages.length)throw new C("stream ended without producing a Message with role=assistant");const e=this.receivedMessages.at(-1).content.filter(e=>"text"===e.type).map(e=>e.text);if(0===e.length)throw new C("stream ended without producing a content block with type=text");return e.join(" ")},$r=function(){this.ended||X(this,cr,void 0,"f")},Tr=function(e){if(this.ended)return;const t=G(this,ar,"m",Mr).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{const n=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===n.type&&this._emit("text",e.delta.text,n.text||"");break;case"citations_delta":"text"===n.type&&this._emit("citation",e.delta.citation,n.citations??[]);break;case"input_json_delta":if(Lr(n)&&G(this,mr,"f").inputJson?.length){let t;try{t=n.input}catch(s){G(this,Ar,"f").call(this,G(this,ar,"m",Or).call(this,n,s));break}this._emit("inputJson",e.delta.partial_json,t)}break;case"thinking_delta":"thinking"===n.type&&this._emit("thinking",e.delta.thinking,n.thinking);break;case"signature_delta":"thinking"===n.type&&this._emit("signature",n.signature);break;case"compaction_delta":"compaction"===n.type&&n.content&&this._emit("compaction",n.content);break;default:/* @__PURE__ */e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(ir(t,G(this,lr,"f"),{logger:G(this,xr,"f")}),!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":X(this,cr,t,"f")}},Er=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");const e=G(this,cr,"f");if(!e)throw new C("request ended without sending any chunks");return X(this,cr,void 0,"f"),ir(e,G(this,lr,"f"),{logger:G(this,xr,"f")})},Mr=function(e){let t=G(this,cr,"f");if("message_start"===e.type){if(t)throw new C(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new C(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.stop_details=e.delta.stop_details,t.usage.output_tokens=e.usage.output_tokens,null!=e.delta.container&&(t.container=e.delta.container),null!=e.context_management&&(t.context_management=e.context_management),null!=e.input_transformations&&(t.input_transformations=e.input_transformations),null!=e.usage.input_tokens&&(t.usage.input_tokens=e.usage.input_tokens),null!=e.usage.cache_creation_input_tokens&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),null!=e.usage.cache_read_input_tokens&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),null!=e.usage.server_tool_use&&(t.usage.server_tool_use=e.usage.server_tool_use),null!=e.usage.iterations&&(t.usage.iterations=e.usage.iterations),null!=e.usage.fallback_credit&&(t.usage.fallback_credit=e.usage.fallback_credit),null!=e.usage.output_tokens_details&&(t.usage.output_tokens_details=e.usage.output_tokens_details),t;case"content_block_start":return t.content.push(e.content_block),"fallback"===e.content_block.type&&(t.model=e.content_block.to.model),t;case"content_block_delta":{const s=t.content.at(e.index);switch(e.delta.type){case"text_delta":"text"===s?.type&&(t.content[e.index]={...s,text:(s.text||"")+e.delta.text});break;case"citations_delta":"text"===s?.type&&(t.content[e.index]={...s,citations:[...s.citations??[],e.delta.citation]});break;case"input_json_delta":if(s&&Lr(s)){const n=(s.__json_buf||"")+e.delta.partial_json;t.content[e.index]=Cr(s,n)}break;case"thinking_delta":"thinking"===s?.type&&(t.content[e.index]={...s,thinking:s.thinking+e.delta.thinking});break;case"signature_delta":"thinking"===s?.type&&(t.content[e.index]={...s,signature:e.delta.signature});break;case"compaction_delta":if("compaction"===s?.type){const n={...s,content:e.delta.content};"encrypted_content"in e.delta&&(n.encrypted_content=e.delta.encrypted_content),t.content[e.index]=n}break;default:/* @__PURE__ */e.delta}return t}case"content_block_stop":{const n=t.content.at(e.index);if(n&&Lr(n)&&"__json_buf"in n){let e;try{e=n.input}catch(s){e={},G(this,Ar,"f").call(this,G(this,ar,"m",Or).call(this,n,s))}Object.defineProperty(n,"input",{value:e,enumerable:!0,configurable:!0,writable:!0})}return t}}},Or=function(e,t){const s=e[Pr];return new C(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${t}. JSON: ${s}`)},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("streamEvent",s=>{const n=t.shift();n?n.resolve(s):e.push(s)}),this.on("end",()=>{s=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{s=!0;for(const s of t)s.reject(e);t.length=0}),this.on("error",e=>{s=!0;for(const s of t)s.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((e,s)=>t.push({resolve:e,reject:s})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new kt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}return e})(),bi=/* @__PURE__ */(()=>{class e extends yi{constructor(e,t){super(e),Nr.add(this),qr.set(this,void 0),Wr.set(this,0),jr.set(this,[]),Ur.set(this,[]),Dr.set(this,void 0),Hr.set(this,[]),zr.set(this,!1),X(this,qr,t,"f")}get toolCalls(){return G(this,Ur,"f")}static start(t,s,n,r){const i=new e({...s,stream:!0},r);for(const e of s.messages)i._addMessageParam(e);return i._run(()=>i._createMessage(t,{...s,stream:!0},{...n,headers:{...n?.headers,[ds]:"stream"}})),i}_emit(e,...t){var s;if("streamEvent"!==e||this.ended)return void super._emit(e,...t);X(this,Wr,(s=G(this,Wr,"f"),++s),"f");const[n,r]=t,i="content_block_stop"===n.type?r.content[n.index]:void 0,o="tool_use"===i?.type?i:void 0;o&&G(this,Ur,"f").push(o),super._emit(e,...t),G(this,Nr,"m",Fr).call(this,n,o),G(this,Nr,"m",Br).call(this)}[(qr=/* @__PURE__ */new WeakMap,Wr=/* @__PURE__ */new WeakMap,jr=/* @__PURE__ */new WeakMap,Ur=/* @__PURE__ */new WeakMap,Dr=/* @__PURE__ */new WeakMap,Hr=/* @__PURE__ */new WeakMap,zr=/* @__PURE__ */new WeakMap,Nr=/* @__PURE__ */new WeakSet,Symbol.asyncIterator)](){const e=super[Symbol.asyncIterator](),t={handled:G(this,Wr,"f")};G(this,jr,"f").push(t);let s=!1;return{next:async()=>{s&&(s=!1,t.handled++,G(this,Nr,"m",Br).call(this));try{const n=await e.next();return s=!n.done,n.done&&G(this,Nr,"m",Kr).call(this,t),n}catch(n){throw G(this,Nr,"m",Kr).call(this,t),n}},return:async()=>{const s=e.return?.();return G(this,Nr,"m",Kr).call(this,t),await s??{value:void 0,done:!0}}}}}return Fr=function(e,t){if(G(this,zr,"f"))return;if("content_block_start"===e.type&&"fallback"===e.content_block.type)return X(this,zr,!0,"f"),void X(this,Dr,void 0,"f");const s="content_block_start"===e.type||"message_delta"===e.type&&"tool_use"===e.delta.stop_reason;G(this,Dr,"f")&&s&&(G(this,Hr,"f").push({toolUse:G(this,Dr,"f"),event:G(this,Wr,"f")}),X(this,Dr,void 0,"f")),t&&X(this,Dr,t,"f")},Br=function(){if(this.errored||this.controller.signal.aborted)return;const e=Math.min(G(this,Wr,"f"),...G(this,jr,"f").map(e=>e.handled));for(;G(this,Hr,"f")[0]&&G(this,Hr,"f")[0].event<=e;)G(this,qr,"f").call(this,G(this,Hr,"f").shift().toolUse)},Kr=function(e){const t=G(this,jr,"f").indexOf(e);t>=0&&(G(this,jr,"f").splice(t,1),G(this,Nr,"m",Br).call(this))},e})();function vi(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}var ki=/* @__PURE__ */(()=>{class e{constructor(e,t,s){Jr.add(this),this.client=e,Vr.set(this,!1),Xr.set(this,!1),Gr.set(this,void 0),Yr.set(this,void 0),Qr.set(this,void 0),Zr.set(this,void 0),ei.set(this,void 0),ti.set(this,void 0),si.set(this,0),ni.set(this,{status:"idle"}),ri.set(this,void 0),ii.set(this,null),oi.set(this,/* @__PURE__ */new Map),ai.set(this,[]),Si(t),function(e){if("compactionControl"in e&&null!=e.compactionControl)throw new C("`compactionControl` has been removed from the tool runner. Use server-side compaction instead: call `runner.compactBeforeNextTurn()` when the conversation should be compacted.")}(t),xi(t),X(this,Gr,{params:{...t,messages:JSON.parse(JSON.stringify(t.messages))}},"f");const n=gs(t.tools,t.messages);X(this,Yr,{...s,headers:ss([us("BetaToolRunner"),n.length?{[hs]:n.join(", ")}:void 0,s?.headers])},"f"),X(this,ti,vi(),"f")}async*[(Vr=/* @__PURE__ */new WeakMap,Xr=/* @__PURE__ */new WeakMap,Gr=/* @__PURE__ */new WeakMap,Yr=/* @__PURE__ */new WeakMap,Qr=/* @__PURE__ */new WeakMap,Zr=/* @__PURE__ */new WeakMap,ei=/* @__PURE__ */new WeakMap,ti=/* @__PURE__ */new WeakMap,si=/* @__PURE__ */new WeakMap,ni=/* @__PURE__ */new WeakMap,ri=/* @__PURE__ */new WeakMap,ii=/* @__PURE__ */new WeakMap,oi=/* @__PURE__ */new WeakMap,ai=/* @__PURE__ */new WeakMap,Jr=/* @__PURE__ */new WeakSet,Symbol.asyncIterator)](){var e;if(G(this,Vr,"f"))throw new C("Cannot iterate over a consumed stream");X(this,Vr,!0,"f"),X(this,Xr,!0,"f"),X(this,ei,void 0,"f");try{for(;;)try{if(G(this,Gr,"f").params.max_iterations&&G(this,si,"f")>=G(this,Gr,"f").params.max_iterations)break;if(G(this,Jr,"m",_i).call(this),"scheduled"===G(this,ni,"f").status&&"resume"!==Ti(G(this,ii,"f"))){yield*G(this,Jr,"m",di).call(this,G(this,ni,"f").config);continue}X(this,Xr,!1,"f"),X(this,ei,void 0,"f"),X(this,si,(e=G(this,si,"f"),++e),"f"),X(this,Qr,void 0,"f");const{max_iterations:t,runToolsEagerly:s,...n}=G(this,Gr,"f").params;if(yield*G(this,Jr,"m",ci).call(this,n),G(this,Xr,"f"))X(this,ii,null,"f");else{const e=await G(this,Qr,"f"),t=Ti(e.stop_reason);X(this,ii,e.stop_reason,"f"),G(this,Gr,"f").params.messages.push({role:e.role,content:Ai(e.content)});const{container:s}=G(this,Gr,"f").params;if(e.container&&(null==s?G(this,Gr,"f").params.container=e.container.id:"object"==typeof s&&null==s.id&&(G(this,Gr,"f").params.container={...s,id:e.container.id})),"stop"===t){yield*G(this,Jr,"m",gi).call(this);break}if("resume"===t)continue}const r=await G(this,Jr,"m",mi).call(this,G(this,Gr,"f").params.messages.at(-1));if(r)G(this,Gr,"f").params.messages.push(r);else if(!G(this,Xr,"f")){yield*G(this,Jr,"m",gi).call(this);break}}finally{G(this,Zr,"f")?.abort(),X(this,Zr,void 0,"f")}if(await G(this,Jr,"m",hi).call(this),!G(this,Qr,"f"))throw new C("ToolRunner concluded without a message from the server");G(this,ti,"f").resolve(await G(this,Qr,"f"))}catch(t){throw X(this,Vr,!1,"f"),G(this,ti,"f").promise.catch(()=>{}),G(this,ti,"f").reject(t),X(this,ti,vi(),"f"),t}}setMessagesParams(e){const t="function"==typeof e?e(G(this,Gr,"f").params):e;if(Si(t),xi(t),"idle"!==G(this,ni,"f").status&&Ri(t),"in_flight"===G(this,ni,"f").status&&t.messages!==G(this,Gr,"f").params.messages)throw new C("Message params can't be changed while the conversation is being compacted, because the compaction response is about to replace them. Change them after this iteration instead.");G(this,Gr,"f").params=t,X(this,Xr,!0,"f"),X(this,ei,void 0,"f")}setRequestOptions(e){X(this,Yr,"function"==typeof e?e(G(this,Yr,"f")):{...G(this,Yr,"f"),...e},"f")}async generateToolResponse(e=G(this,Yr,"f").signal){const t=await G(this,Qr,"f")??this.params.messages.at(-1);return t?G(this,Jr,"m",mi).call(this,t,e):null}deferToolCall(e){const t="string"==typeof e?e:e.id;G(this,ri,"f")&&!G(this,ri,"f").has(t)&&G(this,ri,"f").set(t,{status:"held"})}get deferredToolCalls(){const e=G(this,Zr,"f"),t=G(this,ri,"f");return e instanceof bi&&t?e.toolCalls.filter(e=>"held"===t.get(e.id)?.status):[]}done(){return G(this,ti,"f").promise}async runUntilDone(){if(!G(this,Vr,"f"))for await(const e of this);return this.done()}get params(){return G(this,Gr,"f").params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}compactBeforeNextTurn(e){"in_flight"!==G(this,ni,"f").status&&(Ri(G(this,Gr,"f").params),X(this,ni,{status:"scheduled",config:e??{type:"summarize"}},"f"))}addTools(...e){for(const t of e)"name"in t&&G(this,oi,"f").set(t.name,"run"in t?t:null),G(this,ai,"f").push({type:"addition",tool:t})}removeTools(...e){for(const t of e){const e="string"==typeof t?t:t.name;G(this,oi,"f").set(e,null),G(this,ai,"f").push({type:"removal",name:e})}}then(e,t){return this.runUntilDone().then(e,t)}}return ci=async function*(e){await G(this,Jr,"m",hi).call(this),X(this,ri,void 0,"f"),e.stream?(X(this,Zr,G(this,Gr,"f").params.runToolsEagerly?G(this,Jr,"m",li).call(this,e):this.client.beta.messages.stream({...e},G(this,Yr,"f")),"f"),X(this,Qr,G(this,Zr,"f").finalMessage(),"f"),G(this,Qr,"f").catch(()=>{}),yield G(this,Zr,"f")):(X(this,Qr,this.client.beta.messages.create({...e,stream:!1},G(this,Yr,"f")),"f"),yield G(this,Qr,"f"))},li=function(e){const t=/* @__PURE__ */new Map;return X(this,ri,t,"f"),bi.start(this.client.beta.messages,e,G(this,Yr,"f"),e=>{if(t.has(e.id))return;const s=Ii(G(this,Jr,"m",ui).call(this),G(this,Jr,"m",pi).call(this),e,G(this,Yr,"f"));s.catch(()=>{}),t.set(e.id,{status:"started",result:s})})},hi=async function(){const e=[...G(this,ri,"f")?.values()??[]].filter(e=>"started"===e.status);await Promise.allSettled(e.map(e=>e.result))},di=async function*(e){Ri(G(this,Gr,"f").params);const{max_iterations:t,runToolsEagerly:s,...n}=G(this,Gr,"f").params,r=function(e){const{context_management:t,stop_sequences:s,output_format:n,...r}=e,i=({format:e,...t})=>t;return"any"!==r.tool_choice?.type&&"tool"!==r.tool_choice?.type||delete r.tool_choice,r.output_config&&(r.output_config=i(r.output_config)),Array.isArray(r.fallbacks)&&(r.fallbacks=r.fallbacks.map(e=>e.output_config?{...e,output_config:i(e.output_config)}:e)),r}(n);X(this,ni,{status:"in_flight"},"f"),X(this,ei,void 0,"f");const i=G(this,Qr,"f");try{yield*G(this,Jr,"m",ci).call(this,{...r,compaction:e});const t=await G(this,Qr,"f");t.content.some(e=>"compaction"===e.type&&e.content)?(G(this,Jr,"m",fi).call(this),G(this,Gr,"f").params.messages=[{role:t.role,content:t.content}]):(rt(this.client).warn("Compaction produced no summary; keeping the conversation as it is."),X(this,Qr,i,"f"))}finally{X(this,ni,{status:"idle"},"f")}},ui=function(){const e=/* @__PURE__ */new Map;for(const t of G(this,Gr,"f").params.tools)"run"in t&&e.set(t.name,t);for(const[t,s]of G(this,oi,"f"))s?e.set(t,s):e.delete(t);return e},pi=function(){const e=new Set(G(this,Jr,"m",ui).call(this).keys());for(const t of[...G(this,Gr,"f").params.messages,G(this,Jr,"m",wi).call(this)])if("string"!=typeof t.content)for(const s of t.content)if("system"===t.role)$i(s,e);else if("assistant"===t.role&&"compaction"===s.type)for(const t of s.tool_changes??[])$i(t,e);return e},fi=function(){const e=G(this,Jr,"m",pi).call(this);for(const t of G(this,Jr,"m",ui).call(this).keys())e.has(t)||G(this,oi,"f").set(t,null)},gi=async function*(){if("scheduled"!==G(this,ni,"f").status)return;const e=G(this,Gr,"f").params.messages.at(-1)?.content;if(Array.isArray(e)&&e.some(e=>"tool_use"===e.type))return rt(this.client).warn("The pending compaction was skipped because the last turn ended with tool calls that were not run. Call `compactBeforeNextTurn()` again if you continue the conversation."),void X(this,ni,{status:"idle"},"f");yield*G(this,Jr,"m",di).call(this,G(this,ni,"f").config)},mi=async function(e,t=G(this,Yr,"f").signal){return void 0!==G(this,ei,"f")||X(this,ei,async function(e,t,s,n,r){if(!s||"assistant"!==s.role||!s.content||"string"==typeof s.content)return null;const i=s.content.filter(e=>"tool_use"===e.type);return 0===i.length?null:{role:"user",content:await Promise.all(i.map(s=>{const i=r?.get(s.id);if("started"===i?.status)return i.result;const o=Ii(e,t,s,n);return r?.set(s.id,{status:"started",result:o}),o}))}}(G(this,Jr,"m",ui).call(this),G(this,Jr,"m",pi).call(this),e,{...G(this,Yr,"f"),signal:t},G(this,ri,"f")),"f"),G(this,ei,"f")},_i=function(){"pause_turn"!==G(this,ii,"f")&&0!==G(this,ai,"f").length&&(G(this,Gr,"f").params.messages.push(G(this,Jr,"m",wi).call(this)),X(this,ai,[],"f"))},wi=function(){const e=[];for(const t of G(this,ai,"f")){if("removal"===t.type){e.push({type:"tool_removal",tool:{type:"tool_reference",name:t.name}});continue}let s=t.tool;if("run"in t.tool){const{run:e,parse:n,close:r,...i}=t.tool;s=i}e.push({type:"tool_addition",tool:{type:"tool_definition",definition:s}})}return{role:"system",content:e}},e})();function Si(e){if("compaction"in e&&null!=e.compaction)throw new C("`compaction` cannot be set on a tool runner: every request in the loop would compact again. Call `runner.compactBeforeNextTurn()` when the conversation should be compacted instead.")}function xi(e){if(e.runToolsEagerly&&!e.stream)throw new TypeError("`runToolsEagerly: true` needs `stream: true` in the tool runner's params, because a reply that isn't streamed arrives whole.")}function Ri(e){if(e.context_management?.edits?.some(e=>e.type.startsWith("compact_")))throw new C("`compactBeforeNextTurn()` can't be used while `context_management` has a compaction edit, because the API doesn't accept a compaction block together with one. Remove the edit first.")}async function Ii(e,t,s,n){const r=t.has(s.name)?e.get(s.name):void 0;if(!r)return function(e){return{type:"tool_result",tool_use_id:e.id,content:`Error: Tool '${e.name}' not found`,is_error:!0}}(s);try{let e=s.input;"parse"in r&&r.parse&&(e=r.parse(e));const t=await r.run(e,{toolUse:s,toolUseBlock:s,signal:n?.signal});return{type:"tool_result",tool_use_id:s.id,content:t}}catch(i){return{type:"tool_result",tool_use_id:s.id,content:i instanceof Nn?i.content:`Error: ${i instanceof Error?i.message:String(i)}`,is_error:!0}}}function Ai(e){return e}function $i(e,t){switch(e.type){case"tool_removal":case"tool_addition":!function(e,t){const s=function(e){switch(e.type){case"tool_reference":return e.name;case"tool_definition":return"name"in e.definition?e.definition.name:void 0;default:return}}(e.tool);void 0!==s&&("tool_removal"===e.type?t.delete(s):t.add(s))}(e,t)}}function Ti(e){if(null===e)return"stop";switch(e){case"tool_use":return"run_tools";case"pause_turn":case"compaction":return"resume";default:return"stop"}}var Ei=["claude-mythos-preview","claude-opus-4-6"],Mi=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.batches=new sr(this._client)}create(e,t){const s=Oi(e),{betas:n,user_profile_id:r,workspace_id:i,...o}=s;o.model,Ei.includes(o.model)&&o.thinking&&o.thinking.type;let a=t?.timeout??this._client._options.timeout;if(!o.stream&&null==a){const e=nr[o.model]??void 0;a=this._client.calculateNonstreamingTimeout(o.max_tokens,e)}const c=ms(o.tools,o.messages);return this._client.post("/v1/messages?beta=true",{body:o,timeout:a??6e5,...t,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-user-profile-id":r}:void 0,...null!=i?{"anthropic-workspace-id":i}:void 0},c,t?.headers]),stream:s.stream??!1})}parse(e,t){return t={...t,headers:ss([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},t?.headers])},this.create(e,t).then(t=>or(t,e,{logger:this._client.logger??console}))}stream(e,t){return yi.createMessage(this,e,t)}countTokens(e,t){const{betas:s,user_profile_id:n,workspace_id:r,...i}=Oi(e);return this._client.post("/v1/messages/count_tokens?beta=true",{body:i,...t,headers:ss([{"anthropic-beta":[...s??[],"token-counting-2024-11-01"].toString(),...null!=n?{"anthropic-user-profile-id":n}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},t?.headers])})}toolRunner(e,t){return new ki(this._client,e,t)}}return e.Batches=sr,e.BetaToolRunner=ki,e.ToolError=Nn,e})();function Oi(e){if(!e.output_format)return e;if(e.output_config?.format)throw new C("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");const{output_format:t,...s}=e;return{...s,output_config:{...e.output_config,format:t}}}var Pi,Ci,Li,Ni,qi,Wi,ji,Ui,Di,Hi,zi,Fi,Bi,Ki,Ji,Vi,Xi,Gi,Yi,Qi,Zi,eo,to,so,no,ro=class extends Gt{retrieve(e,t){return this._client.get(os`/v1/organizations/api_keys/${e}?beta=true`,t)}update(e,t,s){return this._client.post(os`/v1/organizations/api_keys/${e}?beta=true`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/api_keys?beta=true",Nt,{query:e,...t})}},io=class extends Gt{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})}},oo=class extends Gt{create(e,t){return this._client.post("/v1/organizations/external_keys?beta=true",{body:e,...t})}retrieve(e,t){return this._client.get(os`/v1/organizations/external_keys/${e}?beta=true`,t)}update(e,t,s){return this._client.post(os`/v1/organizations/external_keys/${e}?beta=true`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/external_keys?beta=true",qt,{query:e,...t})}delete(e,t){return this._client.delete(os`/v1/organizations/external_keys/${e}?beta=true`,t)}validate(e,t){return this._client.post(os`/v1/organizations/external_keys/${e}/validate?beta=true`,t)}},ao=class extends Gt{create(e,t){return this._client.post("/v1/organizations/invites?beta=true",{body:e,...t})}retrieve(e,t){return this._client.get(os`/v1/organizations/invites/${e}?beta=true`,t)}list(e={},t){return this._client.getAPIList("/v1/organizations/invites?beta=true",Nt,{query:e,...t})}delete(e,t){return this._client.delete(os`/v1/organizations/invites/${e}?beta=true`,t)}},co=class extends Gt{list(e={},t){return this._client.getAPIList("/v1/organizations/rate_limits?beta=true",qt,{query:e,...t})}},lo=class extends Gt{retrieve(e,t){return this._client.get(os`/v1/organizations/users/${e}?beta=true`,t)}update(e,t,s){return this._client.post(os`/v1/organizations/users/${e}?beta=true`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/users?beta=true",Nt,{query:e,...t})}remove(e,t){return this._client.delete(os`/v1/organizations/users/${e}?beta=true`,t)}},ho=class extends Gt{create(e,t){const{betas:s,...n}=e;return this._client.post("/v1/organizations/federation_issuers?beta=true",{body:n,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n}=t??{};return this._client.get(os`/v1/organizations/federation_issuers/${e}?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}update(e,t,s){const{betas:n,...r}=t;return this._client.post(os`/v1/organizations/federation_issuers/${e}?beta=true`,{body:r,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}list(e={},t){const{betas:s,...n}=e??{};return this._client.getAPIList("/v1/organizations/federation_issuers?beta=true",qt,{query:n,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}archive(e,t={},s){const{betas:n}=t??{};return this._client.post(os`/v1/organizations/federation_issuers/${e}/archive?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}},uo=class extends Gt{list(e,t={},s){const{betas:n,...r}=t??{};return this._client.getAPIList(os`/v1/organizations/federation_rules/${e}/workspaces?beta=true`,qt,{query:r,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}add(e,t,s){const{betas:n,...r}=t;return this._client.post(os`/v1/organizations/federation_rules/${e}/workspaces?beta=true`,{body:r,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}remove(e,t,s){const{federation_rule_id:n,betas:r}=t;return this._client.delete(os`/v1/organizations/federation_rules/${n}/workspaces/${e}?beta=true`,{...s,headers:ss([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}},po=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.workspaces=new uo(this._client)}create(e,t){const{betas:s,...n}=e;return this._client.post("/v1/organizations/federation_rules?beta=true",{body:n,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n}=t??{};return this._client.get(os`/v1/organizations/federation_rules/${e}?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}update(e,t,s){const{betas:n,...r}=t;return this._client.post(os`/v1/organizations/federation_rules/${e}?beta=true`,{body:r,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}list(e={},t){const{betas:s,...n}=e??{};return this._client.getAPIList("/v1/organizations/federation_rules?beta=true",qt,{query:n,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}archive(e,t={},s){const{betas:n}=t??{};return this._client.post(os`/v1/organizations/federation_rules/${e}/archive?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}}return e.Workspaces=uo,e})(),fo=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.issuers=new ho(this._client),this.rules=new po(this._client)}}return e.Issuers=ho,e.Rules=po,e})(),go=class extends Gt{list(e,t={},s){const{betas:n,...r}=t??{};return this._client.getAPIList(os`/v1/organizations/service_accounts/${e}/workspaces?beta=true`,qt,{query:r,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}add(e,t,s){const{betas:n,...r}=t;return this._client.post(os`/v1/organizations/service_accounts/${e}/workspaces?beta=true`,{body:r,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}remove(e,t,s){const{service_account_id:n,betas:r}=t;return this._client.delete(os`/v1/organizations/service_accounts/${n}/workspaces/${e}?beta=true`,{...s,headers:ss([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}},mo=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.workspaces=new go(this._client)}create(e,t){const{betas:s,...n}=e;return this._client.post("/v1/organizations/service_accounts?beta=true",{body:n,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n}=t??{};return this._client.get(os`/v1/organizations/service_accounts/${e}?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}update(e,t,s){const{betas:n,...r}=t;return this._client.post(os`/v1/organizations/service_accounts/${e}?beta=true`,{body:r,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}list(e={},t){const{betas:s,...n}=e??{};return this._client.getAPIList("/v1/organizations/service_accounts?beta=true",qt,{query:n,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}archive(e,t={},s){const{betas:n}=t??{};return this._client.post(os`/v1/organizations/service_accounts/${e}/archive?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}}return e.Workspaces=go,e})(),_o=class extends Gt{retrieve(e,t,s){const{workspace_id:n}=t;return this._client.get(os`/v1/organizations/workspaces/${n}/members/${e}?beta=true`,s)}update(e,t,s){const{workspace_id:n,...r}=t;return this._client.post(os`/v1/organizations/workspaces/${n}/members/${e}?beta=true`,{body:r,...s})}list(e,t={},s){return this._client.getAPIList(os`/v1/organizations/workspaces/${e}/members?beta=true`,Nt,{query:t,...s})}add(e,t,s){return this._client.post(os`/v1/organizations/workspaces/${e}/members?beta=true`,{body:t,...s})}remove(e,t,s){const{workspace_id:n}=t;return this._client.delete(os`/v1/organizations/workspaces/${n}/members/${e}?beta=true`,s)}},wo=class extends Gt{list(e,t={},s){return this._client.getAPIList(os`/v1/organizations/workspaces/${e}/rate_limits?beta=true`,qt,{query:t,...s})}},yo=class extends Gt{retrieve(e,t,s){const{workspace_id:n,betas:r}=t;return this._client.get(os`/v1/organizations/workspaces/${n}/service_accounts/${e}?beta=true`,{...s,headers:ss([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}update(e,t,s){const{workspace_id:n,betas:r,...i}=t;return this._client.post(os`/v1/organizations/workspaces/${n}/service_accounts/${e}?beta=true`,{body:i,...s,headers:ss([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}list(e,t={},s){const{betas:n,...r}=t??{};return this._client.getAPIList(os`/v1/organizations/workspaces/${e}/service_accounts?beta=true`,qt,{query:r,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}add(e,t,s){const{betas:n,...r}=t;return this._client.post(os`/v1/organizations/workspaces/${e}/service_accounts?beta=true`,{body:r,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}remove(e,t,s){const{workspace_id:n,betas:r}=t;return this._client.delete(os`/v1/organizations/workspaces/${n}/service_accounts/${e}?beta=true`,{...s,headers:ss([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}},bo=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.rateLimits=new wo(this._client),this.members=new _o(this._client),this.serviceAccounts=new yo(this._client)}create(e,t){const{betas:s,...n}=e;return this._client.post("/v1/organizations/workspaces?beta=true",{body:n,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}retrieve(e,t){return this._client.get(os`/v1/organizations/workspaces/${e}?beta=true`,t)}update(e,t,s){return this._client.post(os`/v1/organizations/workspaces/${e}?beta=true`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/workspaces?beta=true",Nt,{query:e,...t})}archive(e,t){return this._client.post(os`/v1/organizations/workspaces/${e}/archive?beta=true`,t)}}return e.RateLimits=wo,e.Members=_o,e.ServiceAccounts=yo,e})(),vo=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.apiKeys=new ro(this._client),this.externalKeys=new oo(this._client),this.federation=new fo(this._client),this.invites=new ao(this._client),this.serviceAccounts=new mo(this._client),this.users=new lo(this._client),this.workspaces=new bo(this._client),this.rateLimits=new co(this._client),this.complianceSettings=new io(this._client)}retrieve(e){return this._client.get("/v1/organizations/me?beta=true",e)}}return e.APIKeys=ro,e.ExternalKeys=oo,e.Federation=fo,e.Invites=ao,e.ServiceAccounts=mo,e.Users=lo,e.Workspaces=bo,e.RateLimits=co,e.ComplianceSettings=io,e})(),ko=/* @__PURE__ */(()=>{class e extends Gt{list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(os`/v1/sessions/${e}/events?beta=true`,qt,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}send(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/sessions/${e}/events?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}stream(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.get(os`/v1/sessions/${e}/events/stream?beta=true`,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers]),stream:!0})}toolRunner(e,t){return new Kn(e,{...t,client:this._client})}}return e.SessionToolRunner=Kn,e})(),So=class extends Gt{retrieve(e,t,s){const{session_id:n,betas:r,workspace_id:i}=t;return this._client.get(os`/v1/sessions/${n}/resources/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}update(e,t,s){const{session_id:n,betas:r,workspace_id:i,...o}=t;return this._client.post(os`/v1/sessions/${n}/resources/${e}?beta=true`,{body:o,...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(os`/v1/sessions/${e}/resources?beta=true`,qt,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}delete(e,t,s){const{session_id:n,betas:r,workspace_id:i}=t;return this._client.delete(os`/v1/sessions/${n}/resources/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}add(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/sessions/${e}/resources?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},xo=class extends Gt{list(e,t,s){const{session_id:n,betas:r,workspace_id:i,...o}=t;return this._client.getAPIList(os`/v1/sessions/${n}/threads/${e}/events?beta=true`,qt,{query:o,...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}stream(e,t,s){const{session_id:n,betas:r,workspace_id:i,...o}=t;return this._client.get(os`/v1/sessions/${n}/threads/${e}/stream?beta=true`,{query:o,...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers]),stream:!0})}},Ro=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.events=new xo(this._client)}retrieve(e,t,s){const{session_id:n,betas:r,workspace_id:i}=t;return this._client.get(os`/v1/sessions/${n}/threads/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(os`/v1/sessions/${e}/threads?beta=true`,qt,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}archive(e,t,s){const{session_id:n,betas:r,workspace_id:i}=t;return this._client.post(os`/v1/sessions/${n}/threads/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}}return e.Events=xo,e})(),Io=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.events=new ko(this._client),this.resources=new So(this._client),this.threads=new Ro(this._client)}create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/sessions?beta=true",{body:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/sessions/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}update(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/sessions/${e}?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/sessions?beta=true",Wt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}delete(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.delete(os`/v1/sessions/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}archive(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/sessions/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Events=ko,e.Resources=So,e.Threads=Ro,e})(),Ao=class extends Gt{create(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/skills/${e}/versions?beta=true`,zt({body:i,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])},this._client,!1))}retrieve(e,t,s){const{skill_id:n,betas:r,workspace_id:i}=t;return this._client.get(os`/v1/skills/${n}/versions/${e}?beta=true`,{...s,headers:ss([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0,...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(os`/v1/skills/${e}/versions?beta=true`,qt,{query:i,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}delete(e,t,s){const{skill_id:n,betas:r,workspace_id:i}=t;return this._client.delete(os`/v1/skills/${n}/versions/${e}?beta=true`,{...s,headers:ss([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0,...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}download(e,t,s){const{skill_id:n,betas:r,workspace_id:i}=t;return this._client.get(os`/v1/skills/${n}/versions/${e}/content?beta=true`,{...s,headers:ss([{Accept:"application/binary",...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0,...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers]),__binaryResponse:!0})}},$o=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.versions=new Ao(this._client)}create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/skills?beta=true",zt({body:r,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])},this._client,!1))}retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/skills/${e}?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/skills?beta=true",qt,{query:r,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}delete(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.delete(os`/v1/skills/${e}?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Versions=Ao,e})(),To=class extends Gt{create(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/tunnels/${e}/certificates?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"mcp-tunnels-2026-06-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}retrieve(e,t,s){const{tunnel_id:n,betas:r,workspace_id:i}=t;return this._client.get(os`/v1/tunnels/${n}/certificates/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"mcp-tunnels-2026-06-22"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(os`/v1/tunnels/${e}/certificates?beta=true`,qt,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"mcp-tunnels-2026-06-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}archive(e,t,s){const{tunnel_id:n,betas:r,workspace_id:i}=t;return this._client.post(os`/v1/tunnels/${n}/certificates/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"mcp-tunnels-2026-06-22"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}},Eo=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.certificates=new To(this._client)}create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/tunnels?beta=true",{body:r,...t,headers:ss([{"anthropic-beta":[...s??[],"mcp-tunnels-2026-06-22"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/tunnels/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"mcp-tunnels-2026-06-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/tunnels?beta=true",qt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"mcp-tunnels-2026-06-22"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}archive(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/tunnels/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"mcp-tunnels-2026-06-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}revealToken(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/tunnels/${e}/reveal_token?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"mcp-tunnels-2026-06-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}rotateToken(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/tunnels/${e}/rotate_token?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"mcp-tunnels-2026-06-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Certificates=To,e})(),Mo=class extends Gt{create(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/vaults/${e}/credentials?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}retrieve(e,t,s){const{vault_id:n,betas:r,workspace_id:i}=t;return this._client.get(os`/v1/vaults/${n}/credentials/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}update(e,t,s){const{vault_id:n,betas:r,workspace_id:i,...o}=t;return this._client.post(os`/v1/vaults/${n}/credentials/${e}?beta=true`,{body:o,...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(os`/v1/vaults/${e}/credentials?beta=true`,qt,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}delete(e,t,s){const{vault_id:n,betas:r,workspace_id:i}=t;return this._client.delete(os`/v1/vaults/${n}/credentials/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}archive(e,t,s){const{vault_id:n,betas:r,workspace_id:i}=t;return this._client.post(os`/v1/vaults/${n}/credentials/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}mcpOAuthValidate(e,t,s){const{vault_id:n,betas:r,workspace_id:i}=t;return this._client.post(os`/v1/vaults/${n}/credentials/${e}/mcp_oauth_validate?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}},Oo=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.credentials=new Mo(this._client)}create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/vaults?beta=true",{body:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/vaults/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}update(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/vaults/${e}?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/vaults?beta=true",qt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}delete(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.delete(os`/v1/vaults/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}archive(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/vaults/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Credentials=Mo,e})(),Po=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.models=new Os(this._client),this.messages=new Mi(this._client),this.agents=new Ds(this._client),this.environments=new Yn(this._client),this.sessions=new Io(this._client),this.deployments=new cs(this._client),this.deploymentRuns=new as(this._client),this.vaults=new Oo(this._client),this.memoryStores=new er(this._client),this.files=new Ms(this._client),this.skills=new $o(this._client),this.webhooks=new js(this._client),this.userProfiles=new Ps(this._client),this.dreams=new ls(this._client),this.tunnels=new Eo(this._client),this.organization=new vo(this._client)}}return e.Models=Os,e.Messages=Mi,e.Agents=Ds,e.Environments=Yn,e.Sessions=Io,e.Deployments=cs,e.DeploymentRuns=as,e.Vaults=Oo,e.MemoryStores=er,e.Files=Ms,e.Skills=$o,e.Webhooks=js,e.UserProfiles=Ps,e.Dreams=ls,e.Tunnels=Eo,e.Organization=vo,e})(),Co=class extends Gt{create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/complete",{body:r,timeout:this._client._options.timeout??6e5,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers]),stream:e.stream??!1})}},Lo=class extends Gt{list(e={},t){const{workspace_id:s,...n}=e??{};return this._client.getAPIList("/v1/files",qt,{query:n,...t,headers:ss([{...null!=s?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(e,t={},s){const{workspace_id:n}=t??{};return this._client.delete(os`/v1/files/${e}`,{...s,headers:ss([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}download(e,t={},s){const{workspace_id:n}=t??{};return this._client.get(os`/v1/files/${e}/content`,{...s,headers:ss([{Accept:"application/binary",...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},s){const{workspace_id:n}=t??{};return this._client.get(os`/v1/files/${e}`,{...s,headers:ss([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}upload(e,t){const{workspace_id:s,...n}=e;return this._client.post("/v1/files",zt({body:n,...t,headers:ss([{...null!=s?{"anthropic-workspace-id":s}:void 0},_s(n.file),t?.headers])},this._client))}};function No(e){return e?.output_config?.format}function qo(e,t,s){const n=No(t);return t&&"parse"in(n??{})?Wo(e,t):{...e,content:e.content.map(e=>"text"===e.type?Object.defineProperty({...e},"parsed_output",{value:null,enumerable:!1}):e),parsed_output:null}}function Wo(e,t,s){let n=null;const r=e.content.map(e=>{if("text"===e.type){const s=function(e,t){const s=No(e);if("json_schema"!==s?.type)return null;try{return"parse"in s?s.parse(t):JSON.parse(t)}catch(n){throw new C(`Failed to parse structured output: ${n}`)}}(t,e.text);return null===n&&(n=s),Object.defineProperty({...e},"parsed_output",{value:s,enumerable:!1})}return e});return{...e,content:r,parsed_output:n}}function jo(e){return"tool_use"===e.type||"server_tool_use"===e.type}var Uo,Do,Ho,zo,Fo=/* @__PURE__ */(()=>{class e{constructor(e,t){Pi.add(this),this.messages=[],this.receivedMessages=[],Ci.set(this,void 0),Li.set(this,null),this.controller=new AbortController,Ni.set(this,void 0),qi.set(this,()=>{}),Wi.set(this,()=>{}),ji.set(this,void 0),Ui.set(this,()=>{}),Di.set(this,()=>{}),Hi.set(this,{}),zi.set(this,!1),Fi.set(this,!1),Bi.set(this,!1),Ki.set(this,!1),Ji.set(this,void 0),Vi.set(this,void 0),Xi.set(this,void 0),Gi.set(this,void 0),Zi.set(this,e=>{if(X(this,Fi,!0,"f"),O(e)&&(e=new N),e instanceof N)return X(this,Bi,!0,"f"),this._emit("abort",e);if(e instanceof C)return this._emit("error",e);if(e instanceof Error){const t=new C(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new C(String(e)))}),X(this,Ni,new Promise((e,t)=>{X(this,qi,e,"f"),X(this,Wi,t,"f")}),"f"),X(this,ji,new Promise((e,t)=>{X(this,Ui,e,"f"),X(this,Di,t,"f")}),"f"),G(this,Ni,"f").catch(()=>{}),G(this,ji,"f").catch(()=>{}),X(this,Li,e,"f"),X(this,Gi,t?.logger??console,"f")}get response(){return G(this,Ji,"f")}get request_id(){return G(this,Vi,"f")}get workspace_id(){return G(this,Xi,"f")}async withResponse(){X(this,Ki,!0,"f");const e=await G(this,Ni,"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(t){const s=new e(null);return s._run(()=>s._fromReadableStream(t)),s}static createMessage(t,s,n,{logger:r}={}){const i=new e(s,{logger:r});for(const e of s.messages)i._addMessageParam(e);return X(i,Li,{...s,stream:!0},"f"),i._run(()=>i._createMessage(t,{...s,stream:!0},{...n,headers:{...n?.headers,[ds]:"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},G(this,Zi,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,s){const n=s?.signal;let r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener("abort",r));try{G(this,Pi,"m",eo).call(this);const{response:n,data:r}=await e.create({...t,stream:!0},{...s,signal:this.controller.signal}).withResponse();this._connected(n);for await(const e of r)G(this,Pi,"m",to).call(this,e);if(r.controller.signal?.aborted)throw new N;G(this,Pi,"m",so).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}_connected(e){this.ended||(X(this,Ji,e,"f"),X(this,Vi,e?.headers.get("request-id"),"f"),X(this,Xi,e?.headers.get("anthropic-workspace-id"),"f"),G(this,qi,"f").call(this,e),this._emit("connect"))}get ended(){return G(this,zi,"f")}get errored(){return G(this,Fi,"f")}get aborted(){return G(this,Bi,"f")}abort(){this.controller.abort()}on(e,t){return(G(this,Hi,"f")[e]||(G(this,Hi,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=G(this,Hi,"f")[e];if(!s)return this;const n=s.findIndex(e=>e.listener===t);return n>=0&&s.splice(n,1),this}once(e,t){return(G(this,Hi,"f")[e]||(G(this,Hi,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{X(this,Ki,!0,"f"),"error"!==e&&this.once("error",s),this.once(e,t)})}async done(){X(this,Ki,!0,"f"),await G(this,ji,"f")}get currentMessage(){return G(this,Ci,"f")}async finalMessage(){return await this.done(),G(this,Pi,"m",Yi).call(this)}async finalText(){return await this.done(),G(this,Pi,"m",Qi).call(this)}_emit(e,...t){if(G(this,zi,"f"))return;"end"===e&&(X(this,zi,!0,"f"),G(this,Ui,"f").call(this));const s=G(this,Hi,"f")[e];if(s&&(G(this,Hi,"f")[e]=s.filter(e=>!e.once),s.forEach(({listener:e})=>e(...t))),"abort"===e){const e=t[0];return G(this,Ki,"f")||s?.length||Promise.reject(e),G(this,Wi,"f").call(this,e),G(this,Di,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];G(this,Ki,"f")||s?.length||Promise.reject(e),G(this,Wi,"f").call(this,e),G(this,Di,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",G(this,Pi,"m",Yi).call(this))}async _fromReadableStream(e,t){const s=t?.signal;let n;s&&(s.aborted&&this.controller.abort(),n=this.controller.abort.bind(this.controller),s.addEventListener("abort",n));try{G(this,Pi,"m",eo).call(this),this._connected(null);const t=kt.fromReadableStream(e,this.controller);for await(const e of t)G(this,Pi,"m",to).call(this,e);if(t.controller.signal?.aborted)throw new N;G(this,Pi,"m",so).call(this)}finally{s&&n&&s.removeEventListener("abort",n)}}[(Ci=/* @__PURE__ */new WeakMap,Li=/* @__PURE__ */new WeakMap,Ni=/* @__PURE__ */new WeakMap,qi=/* @__PURE__ */new WeakMap,Wi=/* @__PURE__ */new WeakMap,ji=/* @__PURE__ */new WeakMap,Ui=/* @__PURE__ */new WeakMap,Di=/* @__PURE__ */new WeakMap,Hi=/* @__PURE__ */new WeakMap,zi=/* @__PURE__ */new WeakMap,Fi=/* @__PURE__ */new WeakMap,Bi=/* @__PURE__ */new WeakMap,Ki=/* @__PURE__ */new WeakMap,Ji=/* @__PURE__ */new WeakMap,Vi=/* @__PURE__ */new WeakMap,Xi=/* @__PURE__ */new WeakMap,Gi=/* @__PURE__ */new WeakMap,Zi=/* @__PURE__ */new WeakMap,Pi=/* @__PURE__ */new WeakSet,Yi=function(){if(0===this.receivedMessages.length)throw new C("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Qi=function(){if(0===this.receivedMessages.length)throw new C("stream ended without producing a Message with role=assistant");const e=this.receivedMessages.at(-1).content.filter(e=>"text"===e.type).map(e=>e.text);if(0===e.length)throw new C("stream ended without producing a content block with type=text");return e.join(" ")},eo=function(){this.ended||X(this,Ci,void 0,"f")},to=function(e){if(this.ended)return;const t=G(this,Pi,"m",no).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{const s=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===s.type&&this._emit("text",e.delta.text,s.text||"");break;case"citations_delta":"text"===s.type&&this._emit("citation",e.delta.citation,s.citations??[]);break;case"input_json_delta":jo(s)&&G(this,Hi,"f").inputJson?.length&&this._emit("inputJson",e.delta.partial_json,s.input);break;case"thinking_delta":"thinking"===s.type&&this._emit("thinking",e.delta.thinking,s.thinking);break;case"signature_delta":"thinking"===s.type&&this._emit("signature",s.signature);break;default:/* @__PURE__ */e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(qo(t,G(this,Li,"f"),G(this,Gi,"f")),!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":X(this,Ci,t,"f")}},so=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");const e=G(this,Ci,"f");if(!e)throw new C("request ended without sending any chunks");return X(this,Ci,void 0,"f"),qo(e,G(this,Li,"f"),G(this,Gi,"f"))},no=function(e){let t=G(this,Ci,"f");if("message_start"===e.type){if(t)throw new C(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new C(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.stop_details=e.delta.stop_details,t.usage.output_tokens=e.usage.output_tokens,null!=e.delta.container&&(t.container=e.delta.container),null!=e.usage.input_tokens&&(t.usage.input_tokens=e.usage.input_tokens),null!=e.usage.cache_creation_input_tokens&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),null!=e.usage.cache_read_input_tokens&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),null!=e.usage.server_tool_use&&(t.usage.server_tool_use=e.usage.server_tool_use),null!=e.usage.output_tokens_details&&(t.usage.output_tokens_details=e.usage.output_tokens_details),t;case"content_block_start":return t.content.push({...e.content_block}),t;case"content_block_delta":{const s=t.content.at(e.index);switch(e.delta.type){case"text_delta":"text"===s?.type&&(t.content[e.index]={...s,text:(s.text||"")+e.delta.text});break;case"citations_delta":"text"===s?.type&&(t.content[e.index]={...s,citations:[...s.citations??[],e.delta.citation]});break;case"input_json_delta":if(s&&jo(s)){const n=(s.__json_buf||"")+e.delta.partial_json;t.content[e.index]=Cr(s,n)}break;case"thinking_delta":"thinking"===s?.type&&(t.content[e.index]={...s,thinking:s.thinking+e.delta.thinking});break;case"signature_delta":"thinking"===s?.type&&(t.content[e.index]={...s,signature:e.delta.signature});break;default:/* @__PURE__ */e.delta}return t}case"content_block_stop":{const s=t.content.at(e.index);return s&&jo(s)&&"__json_buf"in s&&Object.defineProperty(s,"input",{value:s.input,enumerable:!0,configurable:!0,writable:!0}),t}}},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("streamEvent",s=>{const n=t.shift();n?n.resolve(s):e.push(s)}),this.on("end",()=>{s=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{s=!0;for(const s of t)s.reject(e);t.length=0}),this.on("error",e=>{s=!0;for(const s of t)s.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((e,s)=>t.push({resolve:e,reject:s})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new kt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}return e})(),Bo=class extends Gt{create(e,t){const{user_profile_id:s,workspace_id:n,...r}=e;return this._client.post("/v1/messages/batches",{body:r,...t,headers:ss([{...null!=s?{"anthropic-user-profile-id":s}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}retrieve(e,t={},s){const{workspace_id:n}=t??{};return this._client.get(os`/v1/messages/batches/${e}`,{...s,headers:ss([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}list(e={},t){const{workspace_id:s,...n}=e??{};return this._client.getAPIList("/v1/messages/batches",Nt,{query:n,...t,headers:ss([{...null!=s?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(e,t={},s){const{workspace_id:n}=t??{};return this._client.delete(os`/v1/messages/batches/${e}`,{...s,headers:ss([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}cancel(e,t={},s){const{workspace_id:n}=t??{};return this._client.post(os`/v1/messages/batches/${e}/cancel`,{...s,headers:ss([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}async results(e,t={},s){const n=await this.retrieve(e,t,s);if(!n.results_url)throw new C(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);const{workspace_id:r}=t??{};return this._client.get(n.results_url,{...s,headers:ss([{Accept:"application/binary",...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>tr.fromResponse(t.response,t.controller))}},Ko=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.batches=new Bo(this._client)}create(e,t){const{user_profile_id:s,workspace_id:n,...r}=e;r.model,Jo.includes(r.model)&&r.thinking&&r.thinking.type;let i=t?.timeout??this._client._options.timeout;if(!r.stream&&null==i){const e=nr[r.model]??void 0;i=this._client.calculateNonstreamingTimeout(r.max_tokens,e)}const o=ms(r.tools,r.messages);return this._client.post("/v1/messages",{body:r,timeout:i??6e5,...t,headers:ss([{...null!=s?{"anthropic-user-profile-id":s}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},o,t?.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then(t=>Wo(t,e,this._client.logger??console))}stream(e,t){return Fo.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){const{user_profile_id:s,workspace_id:n,...r}=e;return this._client.post("/v1/messages/count_tokens",{body:r,...t,headers:ss([{...null!=s?{"anthropic-user-profile-id":s}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}}return e.Batches=Bo,e})(),Jo=["claude-mythos-preview","claude-opus-4-6"],Vo=class extends Gt{retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/models/${e}`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/models",Nt,{query:r,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}},Xo=class extends Gt{create(e,t,s){const{workspace_id:n,...r}=t;return this._client.post(os`/v1/skills/${e}/versions`,zt({body:r,...s,headers:ss([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])},this._client,!1))}retrieve(e,t,s){const{skill_id:n,workspace_id:r}=t;return this._client.get(os`/v1/skills/${n}/versions/${e}`,{...s,headers:ss([{...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e,t={},s){const{workspace_id:n,...r}=t??{};return this._client.getAPIList(os`/v1/skills/${e}/versions`,qt,{query:r,...s,headers:ss([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}delete(e,t,s){const{skill_id:n,workspace_id:r}=t;return this._client.delete(os`/v1/skills/${n}/versions/${e}`,{...s,headers:ss([{...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},Go=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.versions=new Xo(this._client)}create(e,t){const{workspace_id:s,...n}=e;return this._client.post("/v1/skills",zt({body:n,...t,headers:ss([{...null!=s?{"anthropic-workspace-id":s}:void 0},t?.headers])},this._client,!1))}retrieve(e,t={},s){const{workspace_id:n}=t??{};return this._client.get(os`/v1/skills/${e}`,{...s,headers:ss([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}list(e={},t){const{workspace_id:s,...n}=e??{};return this._client.getAPIList("/v1/skills",qt,{query:n,...t,headers:ss([{...null!=s?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(e,t={},s){const{workspace_id:n}=t??{};return this._client.delete(os`/v1/skills/${e}`,{...s,headers:ss([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}}return e.Versions=Xo,e})(),Yo=/* @__PURE__ */(()=>{class e{get credentials(){return this._authState.provider}constructor({baseURL:e=Ke("ANTHROPIC_BASE_URL"),apiKey:t,authToken:s,webhookKey:n=Ke("ANTHROPIC_WEBHOOK_SIGNING_KEY")??null,...r}={}){if(Uo.add(this),this._requestAuthFlags=/* @__PURE__ */new WeakMap,Ho.set(this,void 0),void 0===t&&(t=null!=r.profile?null:Ke("ANTHROPIC_API_KEY")??null),void 0===s&&(s=null!=r.profile?null:Ke("ANTHROPIC_AUTH_TOKEN")??null),null!=r.profile&&(null!=r.credentials||null!=r.config))throw new TypeError("Pass at most one of `profile`, `credentials`, or `config`.");const i={apiKey:t,authToken:s,webhookKey:n,...r,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new C("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");this.baseURL=i.baseURL,this._baseURLIsExplicit=r.__baseURLIsExplicit??!!e,this.timeout=i.timeout??Do.DEFAULT_TIMEOUT,this.logger=i.logger??console,this.logLevel="warn",this.logLevel=Ge(i.logLevel,"ClientOptions.logLevel",rt(this))??Ge(Ke("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",rt(this))??"warn",this.fetchOptions=i.fetchOptions,this.maxRetries=re("maxRetries",i.maxRetries??2),this.fetch=i.fetch??function(){if("undefined"!=typeof fetch)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`")}(),X(this,Ho,_e,"f"),this.middleware=[...i.middleware??[]];const o=Ke("ANTHROPIC_CUSTOM_HEADERS");if(o){const e={};for(const t of o.split("\n")){const s=t.indexOf(":");s>=0&&(e[t.substring(0,s).trim()]=t.substring(s+1).trim())}i.defaultHeaders={...e,...i.defaultHeaders}}const a=r.__auth;if(delete i.__auth,delete i.__baseURLIsExplicit,this._options=i,this.apiKey="string"==typeof t?t:null,this.authToken=s,this.webhookKey=n,a)this._authState=a,!this._baseURLIsExplicit&&a.baseURL&&(this.baseURL=a.baseURL);else if(this._authState={provider:null,tokenCache:null,resolution:null,error:null,extraHeaders:{}},null==this.apiKey&&null==this.authToken){const e=i.credentials??null;if(e)this._authState.provider=e,this._authState.tokenCache=this._makeTokenCache(e);else if(null!=i.config){const e=wt(i.config,this._credentialResolverOptions());this._authState.provider=e.provider,this._authState.tokenCache=this._makeTokenCache(e.provider),this._authState.extraHeaders=e.extraHeaders,this._applyCredentialBaseURL(e.baseURL)}else null!=i.profile?this._authState.resolution=this._resolveDefaultCredentials(i.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=>{rt(this).debug("credential cache write failed (best-effort)",e)},onSafetyWarning:e=>{rt(this).warn(e)}}}_credentialsFetch(){return Et(this.fetch,this.middleware,void 0,this)}_makeTokenCache(e){return new Be(e,e=>{rt(this).debug("advisory token refresh failed; serving cached token",e)})}withOptions(e){const t="credentials"in e||"config"in e||"profile"in e,s="apiKey"in e||"authToken"in e||t,n={...this._options,...this._baseURLIsExplicit?{baseURL:this.baseURL}:{},maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,middleware:this.middleware,apiKey:this.apiKey,authToken:this.authToken,webhookKey:this.webhookKey,credentials:this.credentials,...t?{credentials:void 0,config:void 0,profile:void 0}:{},...e,__auth:s?void 0:this._authState,__baseURLIsExplicit:"baseURL"in e||this._baseURLIsExplicit};return new this.constructor(n)}async _resolveDefaultCredentials(e){try{const t=await async function(e,t){const s=await(async e=>{var t,s;const n=await ft();if(null===n)return null;const r=e??await mt();if(null===r)return null;ht(r);const{fs:i,path:o}=await(import("./node.browser-B4wGYm0x.js")),a=o.join(n,"configs",`${r}.json`);let c,l;try{c=await i.promises.readFile(a,"utf-8")}catch(d){if("ENOENT"!==d?.code)throw new Error(`failed to read config file ${a}: ${d}`);c=null}if(null===c){const e=Ke("ANTHROPIC_ORGANIZATION_ID"),t=Ke("ANTHROPIC_IDENTITY_TOKEN_FILE"),s=Ke("ANTHROPIC_FEDERATION_RULE_ID");return s&&e?{fromFile:!1,config:{organization_id:e,workspace_id:Ke("ANTHROPIC_WORKSPACE_ID"),base_url:Ke("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:s,service_account_id:Ke("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:t?{source:"file",path:t}:void 0,scope:Ke("ANTHROPIC_SCOPE")}}}:null}try{l=JSON.parse(c)}catch(d){throw new Error(`failed to parse config file ${a}: ${d}`)}if(!l.authentication)throw new Error(`config file ${a} is missing "authentication"`);const h=l.authentication.type;if("oidc_federation"!==h&&"user_oauth"!==h)throw new Error(`authentication.type "${h}" is not a known authentication type`);if(l.organization_id??(l.organization_id=Ke("ANTHROPIC_ORGANIZATION_ID")),l.workspace_id??(l.workspace_id=Ke("ANTHROPIC_WORKSPACE_ID")),l.base_url??(l.base_url=Ke("ANTHROPIC_BASE_URL")),(t=l.authentication).scope??(t.scope=Ke("ANTHROPIC_SCOPE")),"oidc_federation"===l.authentication.type){if(!l.authentication.identity_token){const e=Ke("ANTHROPIC_IDENTITY_TOKEN_FILE");e&&(l.authentication.identity_token={source:"file",path:e})}l.authentication.federation_rule_id||(l.authentication.federation_rule_id=Ke("ANTHROPIC_FEDERATION_RULE_ID")??""),(s=l.authentication).service_account_id??(s.service_account_id=Ke("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:l,fromFile:!0}})(t);if(!s)return null;const{config:n,fromFile:r}=s;return wt(n.authentication.credentials_path||!r?n:{...n,authentication:{...n.authentication,credentials_path:await pt(n,t)??void 0}},e)}(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(null!=e)throw new C(`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&&null==this.apiKey){const t=await this._authState.tokenCache.getToken();return this._authFlags(e).usedTokenCache=!0,ss([{Authorization:`Bearer ${t}`}])}return ss([await this.apiKeyAuth(e),await this.bearerAuth(e)])}}async apiKeyAuth(e){if(null!=this.apiKey)return ss([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(null!=this.authToken)return ss([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return function(e){return function(e,t={}){let s=e;const n=function(e=$e){if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.encodeDotInKeys&&"boolean"!=typeof e.encodeDotInKeys)throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");const t=e.charset||$e.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let s=we;if(void 0!==e.format){if(!ve(be,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const n=be[s];let r,i=$e.filter;if(("function"==typeof e.filter||Q(e.filter))&&(i=e.filter),r=e.arrayFormat&&e.arrayFormat in Ie?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":$e.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const o=void 0===e.allowDots?1==!!e.encodeDotInKeys||$e.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:$e.addQueryPrefix,allowDots:o,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:$e.allowEmptyArrays,arrayFormat:r,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:$e.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?$e.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:$e.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:$e.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:$e.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:$e.encodeValuesOnly,filter:i,format:s,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:$e.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:$e.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:$e.strictNullHandling}}(t);let r,i;"function"==typeof n.filter?(i=n.filter,s=i("",s)):Q(n.filter)&&(i=n.filter,r=i);const o=[];if("object"!=typeof s||null===s)return"";const a=Ie[n.arrayFormat],c="comma"===a&&n.commaRoundTrip;r||(r=Object.keys(s)),n.sort&&r.sort(n.sort);const l=/* @__PURE__ */new WeakMap;for(let u=0;u<r.length;++u){const e=r[u];n.skipNulls&&null===s[e]||Ae(o,Ee(s[e],e,a,c,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,l))}const h=o.join(n.delimiter);let d=!0===n.addQueryPrefix?"?":"";return n.charsetSentinel&&("iso-8859-1"===n.charset?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),h.length>0?d+h:""}(e,{arrayFormat:"brackets"})}(e)}getUserAgent(){return`Anthropic/JS ${ae}`}makeStatusError(e,t,s,n){return L.generate(e,t,s,n)}buildURL(e,t,s){const n=!G(this,Uo,"m",zo).call(this)&&s||this.baseURL,r=(e=>Y.test(e))(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),o=Object.fromEntries(r.searchParams);return te(i)&&te(o)||(t={...o,...i,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new C("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 6e5}async prepareOptions(e){}async prepareRequest(e,{url:t,options:s}){if(this._authState.tokenCache&&null==this.apiKey){const t=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(const[e,n]of Object.entries(this._authState.extraHeaders))t.has(e)||t.set(e,n);const s=t.get("anthropic-beta")?.split(",").map(e=>e.trim());s?.includes("oauth-2025-04-20")||t.set("anthropic-beta",[...s??[],Oe].join(",")),e.headers=t}}backendMiddleware(){return[]}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,s){return this.request(Promise.resolve(s).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new Pt(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){const n=await e;let r=re("maxRetries",n.maxRetries??this.maxRetries);this.isStreamBody(n.body)&&(r=0),null==t&&(t=r,this._requestAuthFlags.delete(n)),await this.prepareOptions(n);const{req:i,url:o,timeout:a}=await this.buildRequest(n,{retryCount:r-t}),c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=void 0===s?"":`, retryOf: ${s}`,h=Date.now();if(n.signal?.aborted)throw new N;const d=new AbortController,u=await this.fetchWithTimeout(o,i,a,d,n,{requestLogID:c,retryOfRequestLogID:s}).catch(P),p=Date.now();if(u instanceof globalThis.Error){pe(d);const e=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new N;const r=O(u)||/timed? ?out/i.test(String(u)+("cause"in u?String(u.cause):"")),i=this.middleware.length>0||!!n.middleware?.length||this.backendMiddleware().length>0;if(i&&!r&&!function(e){const t=/* @__PURE__ */new Set;for(;"object"==typeof e&&null!==e&&!t.has(e);){if(t.add(e),Tt(e)||O(e)||e instanceof q||e instanceof j)return!0;e=e.cause}return!1}(u))throw rt(this).info(`[${c}] middleware error (not retryable)`),ot(rt(this),`[${c}] middleware error (not retryable)`,{retryOfRequestLogID:s,url:o,durationMs:p-h,message:u.message}),u;if(t)return rt(this).info(`[${c}] connection ${r?"timed out":"failed"} - ${e}`),ot(rt(this),`[${c}] connection ${r?"timed out":"failed"} (${e})`,{retryOfRequestLogID:s,url:o,durationMs:p-h,message:u.message}),this.retryRequest(n,t,s??c);if(rt(this).info(`[${c}] connection ${r?"timed out":"failed"} - error; no more retries left`),ot(rt(this),`[${c}] connection ${r?"timed out":"failed"} (error; no more retries left)`,{retryOfRequestLogID:s,url:o,durationMs:p-h,message:u.message}),r)throw new W;if(i&&!Tt(u))throw u;throw new q({cause:u})}const f=`[${c}${l}${[...u.headers.entries()].filter(([e])=>"request-id"===e||"anthropic-workspace-id"===e).map(([e,t])=>", "+e+": "+JSON.stringify(t)).join("")}] ${i.method} ${o} ${u.ok?"succeeded":"failed"} with status ${u.status} in ${p-h}ms`;if(!u.ok){const e=await this.shouldRetry(u,n);if(t&&e){const e=`retrying, ${t} attempts remaining`;return await async function(e){if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void(await(e[Symbol.asyncIterator]().return?.()));const t=e.getReader(),s=t.cancel();t.releaseLock(),await s}(u.body),pe(d),rt(this).info(`${f} - ${e}`),ot(rt(this),`[${c}] response error (${e})`,{retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,durationMs:p-h}),this.retryRequest(n,t,s??c,u.headers)}const r=e?"error; no more retries left":"error; not retryable";rt(this).info(`${f} - ${r}`);const i=await u.text().catch(e=>P(e).message),o=ie(i),a=o?void 0:i;throw ot(rt(this),`[${c}] response error (${r})`,{retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,message:a,durationMs:Date.now()-h}),pe(d),this.makeStatusError(u.status,o,a,u.headers)}return rt(this).info(f),ot(rt(this),`[${c}] response start`,{retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,durationMs:p-h}),function(e,t){de.has(t)&&ue?.register(e,t,t)}(u.body??u,d),{response:u,options:n,controller:d,requestLogID:c,retryOfRequestLogID:s,startTime:h}}getAPIList(e,t,s){return this.requestAPIList(t,s&&"then"in s?s.then(t=>({method:"get",path:e,...t})):{method:"get",path:e,...s})}requestAPIList(e,t){const s=this.makeRequest(t,null,void 0);return new Lt(this,s,e)}async fetchWithTimeout(e,t,s,n,r,i){const{signal:o,method:a,...c}=t||{},l=this._makeAbort(n);o&&(o.addEventListener("abort",l,{once:!0}),function(e,t,s){de.set(e,function(e,t){return()=>e.removeEventListener("abort",t)}(t,s))}(n,o,l));const h=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||"object"==typeof c.body&&null!==c.body&&Symbol.asyncIterator in c.body,d={signal:n.signal,...h?{duplex:"half"}:{},method:"GET",...c};a&&(d.method=a.toUpperCase());const u=this.fetch,p=async(e,t)=>{const n=setTimeout(l,s);try{return await u.call(void 0,e,t)}finally{clearTimeout(n)}},f=void 0===r?p:async(e,t={})=>{const s="string"==typeof e?e:e instanceof URL?e.href:e.url;return t.headers=t.headers instanceof Headers?t.headers:new Headers(t.headers),await this.prepareRequest(t,{url:s,options:r}),i&&ot(rt(this),`[${i.requestLogID}] sending request`,{retryOfRequestLogID:i.retryOfRequestLogID,method:t.method,url:s,options:r,headers:t.headers}),p(e,t)},g=r?.middleware,m=this.backendMiddleware(),_=g?.length||m.length?[...this.middleware,...g??[],...m]:this.middleware;return await Et(f,_,r,this)(e,d)}async shouldRetry(e,t){const s=this._authFlags(t);if(401===e.status&&this._authState.tokenCache&&s.usedTokenCache&&!s.didRefreshFor401)return s.didRefreshFor401=!0,this._authState.tokenCache.invalidate(),!0;const n=e.headers.get("x-should-retry");return"true"===n||"false"!==n&&(408===e.status||409===e.status||429===e.status||e.status>=500)}async retryRequest(e,t,s,n){let r;const i=n?.get("retry-after-ms");if(i){const e=parseFloat(i);Number.isNaN(e)||(r=e)}const o=n?.get("retry-after");if(o&&!r){const e=parseFloat(o);r=Number.isNaN(e)?Date.parse(o)-Date.now():1e3*e}if(void 0===r||!(r>0&&r<=2**31-1)){const s=e.maxRetries??this.maxRetries;r=this.calculateDefaultRetryTimeoutMillis(t,s)}return await oe(r,e.signal??void 0),this.makeRequest(e,t-1,s)}calculateDefaultRetryTimeoutMillis(e,t){const s=t-e;return Math.min(.5*Math.pow(2,s),8)*(1-.25*Math.random())*1e3}calculateNonstreamingTimeout(e,t){const s=6e5;if(36e5*e/128e3>s||null!=t&&e>t)throw new C("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 s}async buildRequest(e,{retryCount:t=0}={}){const s={...e},{method:n,path:r,query:i,defaultBaseURL:o}=s;this._authState.resolution&&await this._authState.resolution,!this._baseURLIsExplicit&&this._authState.baseURL&&this.baseURL!==this._authState.baseURL&&(this.baseURL=this._authState.baseURL);const a=this.buildURL(r,i,o);"timeout"in s&&re("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:c,body:l}=this.buildBody({options:s});return{req:{method:n,headers:await this.buildHeaders({options:e,method:n,bodyHeaders:c,retryCount:t,timeout:s.timeout}),...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...s.fetchOptions??{}},url:a,timeout:s.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:s,retryCount:n,timeout:r}){const i=ss([{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),"X-Stainless-Timeout":String(Math.trunc(r/1e3)),...he(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(i),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=ss([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:this.isStreamBody(e)?{bodyHeaders:void 0,body:ge(e)}:"object"==typeof e&&"application/x-www-form-urlencoded"===s.values.get("content-type")?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:G(this,Ho,"f").call(this,{body:e,headers:s})}isStreamBody(e){return!!(globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)||"object"==typeof e&&null!==e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)}}return Do=e,Ho=/* @__PURE__ */new WeakMap,Uo=/* @__PURE__ */new WeakSet,zo=function(){return"https://api.anthropic.com"!==this.baseURL},e.Anthropic=Do,e.DEFAULT_TIMEOUT=6e5,e.AnthropicError=C,e.APIError=L,e.APIConnectionError=q,e.APIConnectionTimeoutError=W,e.APIUserAbortError=N,e.NotFoundError=z,e.ConflictError=F,e.RateLimitError=K,e.BadRequestError=U,e.AuthenticationError=D,e.InternalServerError=J,e.PermissionDeniedError=H,e.UnprocessableEntityError=B,e.toFile=Vt,e.HUMAN_PROMPT="\\n\\nHuman:",e.AI_PROMPT="\\n\\nAssistant:",e})(),Qo=/* @__PURE__ */(()=>{class e extends Yo{constructor(){super(...arguments),this.completions=new Co(this),this.messages=new Ko(this),this.models=new Vo(this),this.files=new Lo(this),this.skills=new Go(this),this.beta=new Po(this)}}return e.Completions=Co,e.Messages=Ko,e.Models=Vo,e.Files=Lo,e.Skills=Go,e.Beta=Po,e})(),Zo=/* @__PURE__ */e({stream:()=>ya,streamSimple:()=>ba});function ea(e,t){return e||("long"===b("PI_CACHE_RETENTION",t)?"long":"short")}var ta=new Map(["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"].map(e=>[e.toLowerCase(),e])),sa=e=>ta.get(e.toLowerCase())??e,na=(e,t)=>{if(t&&t.length>0){const s=e.toLowerCase(),n=t.find(e=>e.name.toLowerCase()===s);if(n)return n.name}return e};function ra(e){return{type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}}}function ia(e){if(!e.some(e=>"image"===e.type))return I(e.map(e=>e.text).join("\n"));const t=e.map(e=>"text"===e.type?{type:"text",text:I(e.text)}:ra(e));return t.some(e=>"text"===e.type)||t.unshift({type:"text",text:"(see attached image)"}),t}var oa={name:"__pi_deferred_placeholder__",description:"Reserved placeholder. Never available. Never call this.",input_schema:{type:"object",properties:{},required:[]},defer_loading:!0};function aa(e){const t="openrouter"===e.provider||e.baseUrl.includes("openrouter.ai");return{supportsEagerToolInputStreaming:e.compat?.supportsEagerToolInputStreaming??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0,sendSessionAffinityHeaders:e.compat?.sendSessionAffinityHeaders??t,sessionAffinityFormat:e.compat?.sessionAffinityFormat??(t?"openrouter":void 0),supportsCacheControlOnTools:e.compat?.supportsCacheControlOnTools??!0,supportsTemperature:e.compat?.supportsTemperature??!0,allowEmptySignature:e.compat?.allowEmptySignature??!1,supportsStrictTools:e.compat?.supportsStrictTools??!1,supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,supportsMidConvoToolChanges:e.compat?.supportsMidConvoToolChanges??!1}}function ca(...e){const t={};for(const s of e)s&&Object.assign(t,s);return t}function la(e,t){if(!e)return!1;const s=t.toLowerCase();for(const[n,r]of Object.entries(e))if(n.toLowerCase()===s&&null!==r&&r.trim().length>0)return!0;return!1}function ha(e,t){return!!e||la(t,"authorization")||la(t,"x-api-key")||la(t,"cf-aig-authorization")}function da(e,t,s){if(!ha(t,s))throw new Error(`No API key for provider: ${e}`)}var ua,pa=class extends Qo{_shouldResolveDefaultCredentials(){return!1}};function fa(e,t,s,n){if("anthropic"!==e.provider||ha(t,s))return;const r=b(d,n),i=b(h,n),c=b(o,n);return r&&i&&c?{organization_id:i,workspace_id:b(a,n),authentication:{type:"oidc_federation",federation_rule_id:r,service_account_id:b(u,n),identity_token:{source:"file",path:c}}}:void 0}var ga=/* @__PURE__ */new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);function ma(e){if(!e.event&&0===e.data.length)return null;const t={event:e.event,data:e.data.join("\n"),raw:[...e.raw]};return e.event=null,e.data=[],e.raw=[],t}function _a(e,t){if(""===e)return ma(t);if(t.raw.push(e),e.startsWith(":"))return null;const s=e.indexOf(":"),n=-1===s?e:e.slice(0,s);let r=-1===s?"":e.slice(s+1);return r.startsWith(" ")&&(r=r.slice(1)),"event"===n?t.event=r:"data"===n&&t.data.push(r),null}function wa(e){const t=function(e){const t=e.indexOf("\r"),s=e.indexOf("\n");return-1===t?s:-1===s?t:Math.min(t,s)}(e);if(-1===t)return null;let s=t+1;return"\r"===e[t]&&"\n"===e[s]&&(s+=1),{line:e.slice(0,t),rest:e.slice(s)}}var ya=(e,t,n)=>{const r=new c,i=f(t,aa(e).supportsMidConvoSystemMessages),o=g(i.messages);return(async()=>{const t={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let c,h,d,u=e;if(n?.client)c=n.client,h=!1;else{const t=n?.apiKey,s=fa(e,t,n?.headers,n?.env);let r;if(s||da(e.provider,t,n?.headers),"github-copilot"===e.provider){const e=w(i.messages);r=v({messages:i.messages,hasImages:e})}const o="none"===ea(n?.cacheRetention,n?.env)?void 0:n?.sessionId,a=function(e,t,s,n,r,i,o,a){if("github-copilot"===e.provider)return{client:new pa({apiKey:null,authToken:t??null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:n,defaultHeaders:ca(l(e,a),{accept:"application/json","anthropic-dangerous-direct-browser-access":"true"},e.headers,r,s)}),isOAuthToken:!1};if(t&&function(e){return e.includes("sk-ant-oat")}(t))return{client:new pa({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:n,defaultHeaders:ca({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","user-agent":"claude-cli/2.1.280","x-app":"cli"},e.headers,s)}),isOAuthToken:!0};const c=aa(e),h={};i&&c.sendSessionAffinityHeaders&&(h["openrouter"===c.sessionAffinityFormat?"x-session-id":"x-session-affinity"]=i);const d=ca(l(e,a),{accept:"application/json","anthropic-dangerous-direct-browser-access":"true"},h,e.headers,s);if(o){const t=JSON.stringify([e.baseUrl,o]);return ua?.key===t&&ua.fetch===n||(ua={key:t,fetch:n,client:new pa({apiKey:null,authToken:null,config:o,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:n})}),{client:ua.client.withOptions({defaultHeaders:d}),isOAuthToken:!1}}return{client:new pa({apiKey:t??null,authToken:null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:n,defaultHeaders:d}),isOAuthToken:!1}}(e,t,n?.headers,n?.fetch,r,o,s,n?.identity);c=a.client,h=a.isOAuthToken}const f={...n?.signal?{signal:n.signal}:{},...void 0!==n?.timeoutMs?{timeout:n.timeoutMs}:{},maxRetries:0};let g,b=!1;for(;;){n?.signal?.throwIfAborted();const r=va(e,i,h,n,b);r.providerThinkingLevel&&(t.providerThinkingLevel=r.providerThinkingLevel);let o=r.params;const l=await(n?.onPayload?.(o,e));void 0!==l&&(o={...l,stream:!0});try{g=await S(()=>c.beta.messages.create(o,f).asResponse(),{maxRetries:n?.maxRetries,maxRetryDelayMs:n?.maxRetryDelayMs,signal:n?.signal});break}catch(a){if(n?.signal?.aborted||b||!r.hasPreferredStrictTools||!(a instanceof Qo.APIError)||400!==a.status||"invalid_request_error"!==a.type||!["The compiled grammar is too large","Too many strict tools (","Schemas contains too many parameters with union types ("].some(e=>a.message.includes(e)))throw a;b=!0,s(t,{type:"anthropic_strict_tools_fallback",timestamp:Date.now(),error:{message:a.message},details:{reason:"strict_tool_limits_exceeded"}})}}await(n?.onResponse?.({status:g.status,headers:k(g.headers)},e)),r.push({type:"start",partial:t});const x=t.content;for await(const s of async function*(e,t){if(!e.body)throw new Error("Attempted to iterate over an Anthropic response with no body");let s=!1,n=!1;for await(const r of async function*(e,t){const s=e.getReader(),n=new TextDecoder,r={event:null,data:[],raw:[]};let i="";try{for(;;){if(t?.aborted)throw new Error("Request was aborted");const{value:e,done:o}=await s.read();if(o)break;i+=n.decode(e,{stream:!0});let a=wa(i);for(;a;){i=a.rest;const e=_a(a.line,r);e&&(yield e),a=wa(i)}}i+=n.decode();let e=wa(i);for(;e;){i=e.rest;const t=_a(e.line,r);t&&(yield t),e=wa(i)}if(i.length>0){const e=_a(i,r);e&&(yield e)}const o=ma(r);o&&(yield o)}finally{s.releaseLock()}}(e.body,t)){if("error"===r.event)throw new Error(r.data);if(ga.has(r.event??""))try{const e=_(r.data);"message_start"===e.type?s=!0:"message_stop"===e.type&&(n=!0),yield e}catch(a){const t=a instanceof Error?a.message:String(a);throw new Error(`Could not parse Anthropic SSE event ${r.event}: ${t}; data=${r.data}; raw=${r.raw.join("\\n")}`)}}if(s&&!n)throw new Error("Anthropic stream ended before message_stop")}(g,n?.signal))if(await(n?.onProviderStreamEvent?.(s,e)),"message_start"===s.type){t.responseId=s.message.id;const n=s.message.input_transformations;Array.isArray(n)&&(d=n);const r=s.message.model;r!==e.id&&(t.responseModel=r);const i=r===e.id?void 0:e.compat?.allowedFallbackModels?.find(t=>t.provider===e.provider&&t.model===r)?.cost;u=i?{...e,id:r,cost:i}:e,t.usage.input=s.message.usage.input_tokens||0,t.usage.output=s.message.usage.output_tokens||0,t.usage.cacheRead=s.message.usage.cache_read_input_tokens||0,t.usage.cacheWrite=s.message.usage.cache_creation_input_tokens||0,t.usage.cacheWrite1h=s.message.usage.cache_creation?.ephemeral_1h_input_tokens||0,t.usage.totalTokens=t.usage.input+t.usage.output+t.usage.cacheRead+t.usage.cacheWrite,p(u,t.usage)}else if("content_block_start"===s.type){if("fallback"===s.content_block.type){if(t.content.length>0)throw new Error("Anthropic performed an unsupported mid-output model fallback");continue}if("text"===s.content_block.type){const e={type:"text",text:s.content_block.text??"",index:s.index};t.content.push(e),r.push({type:"text_start",contentIndex:t.content.length-1,partial:t})}else if("thinking"===s.content_block.type){const e={type:"thinking",thinking:s.content_block.thinking??"",thinkingSignature:s.content_block.signature??"",index:s.index};t.content.push(e),r.push({type:"thinking_start",contentIndex:t.content.length-1,partial:t})}else if("redacted_thinking"===s.content_block.type){const e={type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:s.content_block.data,redacted:!0,index:s.index};t.content.push(e),r.push({type:"thinking_start",contentIndex:t.content.length-1,partial:t})}else if("tool_use"===s.content_block.type){const e={type:"toolCall",id:s.content_block.id,name:h?na(s.content_block.name,o):s.content_block.name,arguments:s.content_block.input??{},partialJson:"",index:s.index};t.content.push(e),r.push({type:"toolcall_start",contentIndex:t.content.length-1,partial:t})}}else if("content_block_delta"===s.type){if("text_delta"===s.delta.type){const e=x.findIndex(e=>e.index===s.index),n=x[e];n&&"text"===n.type&&(n.text+=s.delta.text,r.push({type:"text_delta",contentIndex:e,delta:s.delta.text,partial:t}))}else if("thinking_delta"===s.delta.type){const e=x.findIndex(e=>e.index===s.index),n=x[e];n&&"thinking"===n.type&&(n.thinking+=s.delta.thinking,r.push({type:"thinking_delta",contentIndex:e,delta:s.delta.thinking,partial:t}))}else if("input_json_delta"===s.delta.type){const e=x.findIndex(e=>e.index===s.index),n=x[e];n&&"toolCall"===n.type&&(n.partialJson+=s.delta.partial_json,n.arguments=m(n.partialJson),r.push({type:"toolcall_delta",contentIndex:e,delta:s.delta.partial_json,partial:t}))}else if("signature_delta"===s.delta.type){const e=x[x.findIndex(e=>e.index===s.index)];e&&"thinking"===e.type&&(e.thinkingSignature=e.thinkingSignature||"",e.thinkingSignature+=s.delta.signature)}}else if("content_block_stop"===s.type){const e=x.findIndex(e=>e.index===s.index),n=x[e];n&&(delete n.index,"text"===n.type?r.push({type:"text_end",contentIndex:e,content:n.text,partial:t}):"thinking"===n.type?r.push({type:"thinking_end",contentIndex:e,content:n.thinking,partial:t}):"toolCall"===n.type&&(Object.assign(n,y(n.partialJson)),delete n.partialJson,r.push({type:"toolcall_end",contentIndex:e,toolCall:n,partial:t})))}else if("message_delta"===s.type){const e=s.input_transformations;if(Array.isArray(e)&&(d=e),s.delta.stop_reason){t.rawStopReason=s.delta.stop_reason;const e=Ta(s.delta.stop_reason,s.delta.stop_details);t.stopReason=e.stopReason,e.errorMessage&&(t.errorMessage=e.errorMessage)}if(s.usage){null!=s.usage.input_tokens&&(t.usage.input=s.usage.input_tokens),null!=s.usage.output_tokens&&(t.usage.output=s.usage.output_tokens),null!=s.usage.cache_read_input_tokens&&(t.usage.cacheRead=s.usage.cache_read_input_tokens),null!=s.usage.cache_creation_input_tokens&&(t.usage.cacheWrite=s.usage.cache_creation_input_tokens);const e=s.usage.cache_creation;null!=e?.ephemeral_1h_input_tokens&&(t.usage.cacheWrite1h=e.ephemeral_1h_input_tokens);const n=s.usage.output_tokens_details?.thinking_tokens;null!=n&&(t.usage.reasoning=n)}t.usage.totalTokens=t.usage.input+t.usage.output+t.usage.cacheRead+t.usage.cacheWrite,p(u,t.usage)}if(n?.signal?.aborted)throw new Error("Request was aborted");if("pending"===t.stopReason)throw new Error("Anthropic stream ended without a stop reason");if("aborted"===t.stopReason||"error"===t.stopReason)throw new Error(t.errorMessage||"An unknown error occurred");d&&d.length>0&&s(t,{type:"anthropic_input_transformations",timestamp:Date.now(),details:{transformations:d.map(e=>({type:e.type??void 0,path:e.path??void 0,reason:e.reason??void 0}))}}),r.push({type:"done",reason:t.stopReason,message:t}),r.end()}catch(a){for(const e of t.content)delete e.index,delete e.partialJson;t.stopReason=n?.signal?.aborted?"aborted":"error",t.errorMessage=a instanceof Error?a.message:JSON.stringify(a),r.push({type:"error",reason:t.stopReason,error:t}),r.end()}})(),r},ba=(e,t,s)=>{fa(e,s?.apiKey,s?.headers,s?.env)||da(e.provider,s?.apiKey,s?.headers);const n={...A(e,t,s,s?.apiKey),toolChoice:s?.toolChoice};if(!s?.reasoning)return ya(e,t,{...n,thinkingEnabled:!1});if(!0===e.compat?.forceAdaptiveThinking){const r=function(e,t){const s=t?e.thinkingLevelMap?.[t]:void 0;if("string"==typeof s)return s;switch(t){case"minimal":case"low":return"low";case"medium":return"medium";default:return"high"}}(e,s.reasoning);return ya(e,t,{...n,thinkingEnabled:!0,effort:r})}const r=E(n.maxTokens,e.maxTokens,s.reasoning,s.thinkingBudgets),i=x(e,t,r.maxTokens);return ya(e,t,{...n,maxTokens:i,thinkingEnabled:!0,thinkingBudgetTokens:Math.min(r.thinkingBudget,Math.max(0,i-1024))})};function va(e,t,s,o,a=!1){const{cacheControl:c}=function(e,t,s){const n=ea(t,s);if("none"===n)return{retention:n};const r="long"===n&&aa(e).supportsLongCacheRetention?"1h":void 0;return{retention:n,cacheControl:{type:"ephemeral",...r&&{ttl:r}}}}(e,o?.cacheRetention,o?.env),l=aa(e),h=n(t.messages),d=h?r(h):"",u=T(t.messages,e,ka),p=h?u.slice(1):u;let f=!1;const m=(e,t)=>{const n=function(e,t,s,n,r,i=!1){return e?e.map((o,a)=>{const c=o.constrainedSampling,l=i&&c&&"json_schema"===c.type&&"prefer"===c.strict?void 0:$(o,n,$a),h=R(o,l),d=h,u={type:"object",properties:d.properties??{},required:d.required??[]},p=!0===l?{...h,...u}:u;return{name:t?sa(o.name):o.name,description:o.description,...s?{eager_input_streaming:!0}:{},...!0===l?{strict:!0}:{},input_schema:p,...r&&a===e.length-1?{cache_control:r}:{}}}):[]}(e,s,l.supportsEagerToolInputStreaming,l.supportsStrictTools,t,a);return n.some((t,s)=>{const n=e[s].constrainedSampling;return!0===t.strict&&n&&"json_schema"===n.type&&"prefer"===n.strict})&&(f=!0),n},_=h?.toolsAdded??[],w=l.supportsMidConvoSystemMessages&&l.supportsMidConvoToolChanges&&_.length>0,y=e.reasoning&&!1===o?.thinkingEnabled&&null!==e.thinkingLevelMap?.off,b=!0===e.compat?.supportsMidConvoEffort&&!y,v=function(e,t,s,n=!1,r,o){const a=[],c=/* @__PURE__ */new Map,l=[],h=()=>{a.push(...l),l.length=0};for(let d=0;d<e.length;d++){const s=e[d];if("system"===s.role){const e=i(s),n=[];if(e.length>0&&n.push({type:"text",text:I(e)}),o){const e=s.toolsAdded??[],r=new Set(e.map(e=>e.name));for(const i of s.toolsRemoved??[])r.has(i.name)||n.push({type:"tool_removal",tool:{type:"tool_reference",name:t?sa(i.name):i.name}});for(const t of o(e))n.push({type:"tool_addition",tool:{type:"tool_definition",definition:t}})}n.length>0&&l.push({role:"system",content:n})}else if("user"===s.role)if("string"==typeof s.content)s.content.trim().length>0&&a.push({role:"user",content:I(s.content)});else{const e=s.content.map(e=>"text"===e.type?{type:"text",text:I(e.text)}:ra(e)).filter(e=>"text"!==e.type||e.text.trim().length>0);if(0===e.length)continue;a.push({role:"user",content:e})}else if("assistant"===s.role){h();const e=[];for(const r of s.content)if("text"===r.type){if(0===r.text.trim().length)continue;e.push({type:"text",text:I(r.text)})}else if("thinking"===r.type){if(r.redacted){e.push({type:"redacted_thinking",data:r.thinkingSignature});continue}const t=r.thinkingSignature,s=!!t&&t.trim().length>0;if(0===r.thinking.trim().length&&!s)continue;s?e.push({type:"thinking",thinking:I(r.thinking),signature:t}):e.push(n?{type:"thinking",thinking:I(r.thinking),signature:""}:{type:"text",text:I(r.thinking)})}else"toolCall"===r.type&&e.push({type:"tool_use",id:r.id,name:t?sa(r.name):r.name,input:r.arguments??{}});if(0===e.length)continue;const i=a.length;a.push({role:"assistant",content:e}),void 0!==r&&"anthropic-messages"===s.api&&s.provider===r&&xa(s.providerThinkingLevel)&&c.set(i,s.providerThinkingLevel)}else if("toolResult"===s.role){const t=[],s=[];let n=d;for(;n<e.length&&"toolResult"===e[n].role;){const r=e[n],i=M(r);t.push(Sa(r,i?.content)),i&&s.push({type:"text",text:i.caption},...i.images.map(ra)),n++}d=n-1,a.push({role:"user",content:[...t,...s]})}}if(h(),s&&a.length>0){const e=a[a.length-1];if("user"===e.role||"system"===e.role)if(Array.isArray(e.content)){const t=e.content[e.content.length-1];!t||"text"!==t.type&&"image"!==t.type&&"tool_result"!==t.type&&"tool_addition"!==t.type&&"tool_removal"!==t.type||(t.cache_control=s)}else"string"==typeof e.content&&(e.content=[{type:"text",text:e.content,cache_control:s}])}return{messages:a,assistantLevels:c}}(p,s,c,l.allowEmptySignature,b?e.provider:void 0,w?m:void 0),k=o?.effort??"high",S=function(e,t,s,n,r){let i;for(const a of[e.headers,r?.headers])for(const[e,t]of Object.entries(a??{}))"anthropic-beta"===e.toLowerCase()&&(i=t);if(null===i)return[];if(void 0!==i)return[...new Set(i.split(",").map(e=>e.trim()).filter(e=>e.length>0))];const o=[];return s&&o.push("claude-code-20250219","oauth-2025-04-20"),function(e,t){return g(t.messages).length>0&&!aa(e).supportsEagerToolInputStreaming}(e,t)&&o.push("fine-grained-tool-streaming-2025-05-14"),e.reasoning&&!0===r?.thinkingEnabled&&(r.interleavedThinking??!0)&&!0!==e.compat?.forceAdaptiveThinking&&o.push("interleaved-thinking-2025-05-14"),function(e){return(e.compat?.allowedFallbackModels?.length??0)>0}(e)&&o.push("server-side-fallback-2026-07-01"),!0===e.compat?.supportsMidConvoEffort&&o.push("mid-conversation-output-config-2026-07-01","thinking-binding-controls-2026-08-01"),n&&o.push("inline-tools-2026-09-15"),[...new Set(o)]}(e,t,s,w,o),x={model:e.id,messages:b?Ra(v,k):v.messages,max_tokens:o?.maxTokens??e.maxTokens,stream:!0,...S.length>0?{betas:S}:{}};s?(x.system=[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude.",...c?{cache_control:c}:{}}],d&&x.system.push({type:"text",text:I(d),...c?{cache_control:c}:{}})):d&&(x.system=[{type:"text",text:I(d),...c?{cache_control:c}:{}}]),void 0!==o?.temperature&&!o?.thinkingEnabled&&!0!==e.compat?.supportsMidConvoEffort&&l.supportsTemperature&&(x.temperature=o.temperature);const A=l.supportsCacheControlOnTools?c:void 0;if(w)x.tools=[...m(_,A),oa];else{const e=g(t.messages);e.length>0&&(x.tools=m(e,A))}if(y)x.thinking={type:"disabled"};else if(b)x.thinking={type:"adaptive",display:o?.thinkingDisplay??"summarized",block_binding:{prefix_mismatch_behavior:"drop_block"}},x.output_config={effort:"high"};else if(e.reasoning&&o?.thinkingEnabled){const t=o.thinkingDisplay??"summarized";!0===e.compat?.forceAdaptiveThinking?(x.thinking={type:"adaptive",display:t},o.effort&&(x.output_config={effort:o.effort})):x.thinking={type:"enabled",budget_tokens:o.thinkingBudgetTokens||1024,display:t}}if(o?.metadata){const e=o.metadata.user_id;"string"==typeof e&&(x.metadata={user_id:e})}o?.toolChoice&&("string"==typeof o.toolChoice?x.tool_choice={type:o.toolChoice}:x.tool_choice=o.toolChoice);const E=e.compat?.allowedFallbackModels;return E&&E.length>0&&(x.fallbacks=E.map(e=>({model:e.model}))),{params:x,hasPreferredStrictTools:f,providerThinkingLevel:b?k:void 0}}function ka(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function Sa(e,t=e.content){return{type:"tool_result",tool_use_id:e.toolCallId,content:ia(t),is_error:e.isError}}function xa(e){return"low"===e||"medium"===e||"high"===e||"xhigh"===e||"max"===e}function Ra(e,t){const s=[];for(let n=0;n<e.messages.length;n++){const t=e.assistantLevels.get(n);void 0!==t&&s.push({role:"system",content:[],output_config:{effort:t}}),s.push(e.messages[n])}return s.push({role:"system",content:[],output_config:{effort:t}}),s}var Ia=/* @__PURE__ */new Set(["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","maxItems","uniqueItems","minContains","maxContains","minProperties","maxProperties"]),Aa=/* @__PURE__ */new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),$a=(e,t)=>!(!Ia.has(e)&&("minItems"===e?0===t||1===t:"format"!==e||"string"==typeof t&&Aa.has(t)));function Ta(e,t){switch(e){case"end_turn":case"pause_turn":case"stop_sequence":return{stopReason:"stop"};case"max_tokens":return{stopReason:"length"};case"tool_use":return{stopReason:"toolUse"};case"refusal":return{stopReason:"error",errorMessage:t?.explanation||"The model refused to complete the request"};case"sensitive":return{stopReason:"error",errorMessage:"Provider stopped with: sensitive"};default:throw new Error(`Unhandled stop reason: ${e}`)}}export{V as n,C as r,ya as stream,ba as streamSimple,Zo as t};
1
+ void 0===globalThis.process&&(globalThis.process={env:{},platform:"browser",version:"",versions:{},browser:!0,nextTick:function(e){return Promise.resolve().then(e)}});import{r as e,t}from"./rolldown-runtime-9urLBz53.js";import{C as s,S as n,T as r,_ as i,a as o,f as a,h as c,i as l,n as h,o as d,r as u,v as p,w as f,x as g}from"./AssistantPane-CRFX-ZVk.js";import{a as m,i as _,n as w,o as y,r as b,t as v}from"./github-copilot-headers-EfqOaQ0F.js";import{n as k,t as S}from"./provider-retry-DNH2SSUZ.js";import{a as x,f as R,h as I,i as A,m as $,n as T,r as E,t as M}from"./transform-messages-Zq_vaj0G.js";function O(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var P=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{const t=Object.prototype.toString.call(e);if("[object Error]"===t||"[object DOMException]"===t){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)},C=/* @__PURE__ */(()=>{class e extends Error{}return e})(),L=class e extends C{constructor(t,s,n,r,i){super(`${e.makeMessage(t,s,n)}`),this.status=t,this.headers=r,this.requestID=r?.get("request-id"),this.workspaceID=r?.get("anthropic-workspace-id"),this.error=s,this.type=i??null}static makeMessage(e,t,s){const n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(t,s,n,r){if(!t||!r)return new q({message:n,cause:P(s)});const i=s,o=i?.error?.type;return 400===t?new U(t,i,n,r,o):401===t?new D(t,i,n,r,o):403===t?new H(t,i,n,r,o):404===t?new z(t,i,n,r,o):409===t?new F(t,i,n,r,o):422===t?new B(t,i,n,r,o):429===t?new K(t,i,n,r,o):t>=500?new J(t,i,n,r,o):new e(t,i,n,r,o)}},N=class extends L{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},q=class extends L{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},W=class extends q{constructor({message:e}={}){super({message:e??"Request timed out."})}},j=class extends C{constructor(e,{cause:t}={}){super(e??"Retryable error."),void 0!==t&&(this.cause=t)}},U=class extends L{},D=class extends L{},H=class extends L{},z=class extends L{},F=class extends L{},B=class extends L{},K=class extends L{},J=class extends L{},V=5e3;function X(e,t,s,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,s):r?r.value=s:t.set(e,s),s}function G(e,t,s,n){if("a"===s&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?n:"a"===s?n.call(e):n?n.value:t.get(e)}var Y=/^[a-z][a-z0-9+.-]*:/i,Q=e=>(Q=Array.isArray)(e),Z=Q;function ee(e){return"object"!=typeof e?{}:e??{}}function te(e){if(!e)return!0;for(const t in e)return!1;return!0}function se(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}var ne,re=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new C(`${e} must be an integer`);if(t<0)throw new C(`${e} must be a positive integer`);return t},ie=e=>{try{return JSON.parse(e)}catch(t){return}},oe=(e,t)=>new Promise(s=>{if(t?.aborted)return s();const n=()=>{clearTimeout(r),s()},r=setTimeout(()=>{t?.removeEventListener("abort",n),s()},e);t?.addEventListener("abort",n,{once:!0})}),ae="0.129.0",ce=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",le=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown",he=()=>ne??(ne=(()=>{const e="undefined"!=typeof Deno&&null!=Deno.build?"deno":"undefined"!=typeof EdgeRuntime?"edge":"[object process]"===Object.prototype.toString.call(void 0!==globalThis.process?globalThis.process:0)?"node":"unknown";if("deno"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ae,"X-Stainless-OS":le(Deno.build.os),"X-Stainless-Arch":ce(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ae,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process?.version??"unknown"};if("node"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ae,"X-Stainless-OS":le(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ce(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=function(){if("undefined"==typeof navigator||!navigator)return null;for(const{key:e,pattern:t}of[{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/}]){const s=t.exec(navigator.userAgent);if(s)return{browser:e,version:`${s[1]||0}.${s[2]||0}.${s[3]||0}`}}return null}();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ae,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ae,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}})()),de=/* @__PURE__ */new WeakMap,ue="function"==typeof globalThis.FinalizationRegistry?new globalThis.FinalizationRegistry(e=>pe(e)):null;function pe(e){const t=de.get(e);t&&(de.delete(e),ue?.unregister(e),t())}function fe(...e){const t=globalThis.ReadableStream;if(void 0===t)throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function ge(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return fe({start(){},async pull(e){const{done:s,value:n}=await t.next();s?e.close():e.enqueue(n)},async cancel(){await(t.return?.())}})}function me(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var _e=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),we="RFC3986",ye=e=>String(e),be={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:ye},ve=(e,t)=>(ve=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty))(e,t),ke=/* @__PURE__ */(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),Se=1024;function xe(e,t){if(Q(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}var Re,Ie={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},Ae=function(e,t){Array.prototype.push.apply(e,Q(t)?t:[t])},$e={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,s,n,r)=>{if(0===e.length)return e;let i=e;if("symbol"==typeof e?i=Symbol.prototype.toString.call(e):"string"!=typeof e&&(i=String(e)),"iso-8859-1"===s)return escape(i).replace(/%u[0-9a-f]{4}/gi,function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"});let o="";for(let a=0;a<i.length;a+=Se){const e=i.length>=Se?i.slice(a,a+Se):i,t=[];for(let s=0;s<e.length;++s){let n=e.charCodeAt(s);45===n||46===n||95===n||126===n||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||"RFC1738"===r&&(40===n||41===n)?t[t.length]=e.charAt(s):n<128?t[t.length]=ke[n]:n<2048?t[t.length]=ke[192|n>>6]+ke[128|63&n]:n<55296||n>=57344?t[t.length]=ke[224|n>>12]+ke[128|n>>6&63]+ke[128|63&n]:(s+=1,n=65536+((1023&n)<<10|1023&e.charCodeAt(s)),t[t.length]=ke[240|n>>18]+ke[128|n>>12&63]+ke[128|n>>6&63]+ke[128|63&n])}o+=t.join("")}return o},encodeValuesOnly:!1,format:we,formatter:ye,indices:!1,serializeDate:e=>(Re??(Re=Function.prototype.call.bind(Date.prototype.toISOString)))(e),skipNulls:!1,strictNullHandling:!1},Te={};function Ee(e,t,s,n,r,i,o,a,c,l,h,d,u,p,f,g,m,_){let w=e,y=_,b=0,v=!1;for(;void 0!==(y=y.get(Te))&&!v;){const t=y.get(e);if(b+=1,void 0!==t){if(t===b)throw new RangeError("Cyclic object value");v=!0}void 0===y.get(Te)&&(b=0)}if("function"==typeof l?w=l(t,w):w instanceof Date?w=u?.(w):"comma"===s&&Q(w)&&(w=xe(w,function(e){return e instanceof Date?u?.(e):e})),null===w){if(i)return c&&!g?c(t,$e.encoder,m,"key",p):t;w=""}if("string"==typeof(k=w)||"number"==typeof k||"boolean"==typeof k||"symbol"==typeof k||"bigint"==typeof k||function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))}(w)){if(c){const e=g?t:c(t,$e.encoder,m,"key",p);return[f?.(e)+"="+f?.(c(w,$e.encoder,m,"value",p))]}return[f?.(t)+"="+f?.(String(w))]}var k;const S=[];if(void 0===w)return S;let x;if("comma"===s&&Q(w))g&&c&&(w=xe(w,c)),x=[{value:w.length>0?w.join(",")||null:void 0}];else if(Q(l))x=l;else{const e=Object.keys(w);x=h?e.sort(h):e}const R=a?String(t).replace(/\./g,"%2E"):String(t),I=n&&Q(w)&&1===w.length?R+"[]":R;if(r&&Q(w)&&0===w.length)return I+"[]";for(let A=0;A<x.length;++A){const t=x[A],y="object"==typeof t&&void 0!==t.value?t.value:w[t];if(o&&null===y)continue;const v=d&&a?t.replace(/\./g,"%2E"):t,k=Q(w)?"function"==typeof s?s(I,v):I:I+(d?"."+v:"["+v+"]");_.set(e,b);const R=/* @__PURE__ */new WeakMap;R.set(Te,_),Ae(S,Ee(y,k,s,n,r,i,o,a,"comma"===s&&g&&Q(w)?null:c,l,h,d,u,p,f,g,m,R))}return S}var Me="/v1/oauth/token",Oe="oauth-2025-04-20",Pe=1<<20;function Ce(e){if(!e)return;let t;try{t=new URL(e)}catch(n){throw new De(`Invalid token endpoint base URL "${e}": ${n}`)}if("https:"===t.protocol)return;const s=t.hostname.toLowerCase().replace(/^\[|\]$/g,"");if("http:"!==t.protocol||"localhost"!==s&&"127.0.0.1"!==s&&"::1"!==s)throw new De(`Refusing to send credential over non-https token endpoint "${e}"`)}async function Le(e,t){const s=await async function(e){if(!e.body)return"";const t=e.body.getReader(),s=[];let n,r=0;for(;;){const{done:e,value:n}=await t.read();if(e)break;if(r+n.length>Pe){const e=Pe-r;e>0&&s.push(n.subarray(0,e)),await t.cancel();break}s.push(n),r+=n.length}if(1===s.length)n=s[0];else{n=new Uint8Array(s.reduce((e,t)=>e+t.length,0));let e=0;for(const t of s)n.set(t,e),e+=t.length}return new TextDecoder("utf-8").decode(n)}(e);let n;try{n=JSON.parse(s)}catch{throw new De(`Token endpoint returned non-JSON response (status ${e.status})`,e.status,We(s),t)}if(!n.access_token)throw new De(`Token endpoint response missing access_token: ${JSON.stringify(We(n))}`,e.status,We(n),t);if(n.token_type&&"bearer"!==n.token_type.toLowerCase())throw new De(`Token endpoint response: unsupported token_type "${n.token_type}" (want Bearer)`,e.status,We(n),t);return n}var Ne=2e3,qe=/* @__PURE__ */new Set(["error","error_description","error_uri"]);function We(e){if(null==e)return e;if("string"==typeof e){let t;try{t=JSON.parse(e)}catch{return e.length<=Ne?e:e.slice(0,Ne)+`... <${e.length-Ne} more chars>`}return JSON.stringify(We(t))}if("object"==typeof e&&!Array.isArray(e)){const t={};for(const[s,n]of Object.entries(e))qe.has(s)&&(t[s]=n);return t}return null}async function je(e,t=e=>{}){if("undefined"==typeof process)return;const{fs:s}=await(import("./node.browser-CE0N-lmH.js"));let n,r=e;try{r=await s.promises.realpath(e),n=await s.promises.stat(r)}catch{return}const i=511&n.mode;if(18&i)throw new De(`Credentials file at ${r} is group/world-writable (mode 0o${i.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${r}\`.`);if(36&i)throw new De(`Credentials file at ${r} is group/world-readable (mode 0o${i.toString(8)}); run \`chmod 600 ${r}\` before retrying.`);"function"==typeof process.getuid&&n.uid!==process.getuid()&&t(`credentials file at ${r} is owned by uid ${n.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function Ue(e,t){const{fs:s,path:n}=await(import("./node.browser-CE0N-lmH.js")),r=n.dirname(e);await s.promises.mkdir(r,{recursive:!0,mode:448});const i=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{const n=await s.promises.open(i,"w",384);try{await n.writeFile(JSON.stringify(t,null,2)),await n.sync()}finally{await n.close()}await s.promises.rename(i,e)}catch(o){throw await s.promises.unlink(i).catch(()=>{}),o}try{const e=await s.promises.open(r,"r");try{await e.sync()}finally{await e.close()}}catch{}}var De=class extends C{constructor(e,t=null,s=null,n=null){super(e),this.statusCode=t,this.body=s,this.requestId=n}};function He(){return Math.floor(Date.now()/1e3)}var ze,Fe,Be=class{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||null==t)return(await this.refresh(e)).token;if(null==t.expiresAt)return t.token;const s=t.expiresAt-He();return s>120?t.token:s>30?(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||He()-this.lastAdvisoryError<5||this.doRefresh().catch(e=>{this.lastAdvisoryError=He(),this.onAdvisoryRefreshError?.(e)})}doRefresh(e=!1){return this.pendingRefresh=this.provider(e?{forceRefresh:!0}:void 0).then(e=>(this.cached=e,this.pendingRefresh=null,e),e=>{throw this.pendingRefresh=null,e}),this.pendingRefresh}},Ke=e=>void 0!==globalThis.process?globalThis.process.env?.[e]?.trim()||void 0:void 0!==globalThis.Deno&&globalThis.Deno.env?.get?.(e)?.trim()||void 0;function Je(e){let t;return(ze??(t=new globalThis.TextEncoder,ze=t.encode.bind(t)))(e)}function Ve(e){let t;return(Fe??(t=new globalThis.TextDecoder,Fe=t.decode.bind(t)))(e)}var Xe={off:0,error:200,warn:300,info:400,debug:500},Ge=(e,t,s)=>{var n,r;if(e)return n=Xe,r=e,Object.prototype.hasOwnProperty.call(n,r)?e:void s.warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Xe))}`)};function Ye(){}function Qe(e,t,s){return!t||Xe[e]>Xe[s]?Ye:t[e].bind(t)}var Ze,et,tt={error:Ye,warn:Ye,info:Ye,debug:Ye},st=/* @__PURE__ */new WeakMap;function nt(e,t){const s=st.get(e);if(s&&s[0]===t)return s[1];const n={error:Qe("error",e,t),warn:Qe("warn",e,t),info:Qe("info",e,t),debug:Qe("debug",e,t)};return st.set(e,[t,n]),n}function rt(e){const t=e.logger,s=e.logLevel??"off";return t?nt(t,s):tt}function it(){const e=Ke("ANTHROPIC_LOG");return et&&e===Ze||(Ze=e,et=nt(console,Ge(e,"process.env['ANTHROPIC_LOG']",nt(console,"warn"))??"warn")),et}function ot(e,t,s){e.debug!==Ye&&e.debug(t,at(s))}var at=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,"authorization"===e.toLowerCase()||"api-key"===e.toLowerCase()||"x-api-key"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),ct=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return ct=e.randomUUID.bind(e),e.randomUUID();const t=/* @__PURE__ */new Uint8Array(1),s=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^s()&15>>+e/4).toString(16))},lt=/^[A-Za-z0-9_.-]+$/;function ht(e){if(!e)throw new Error("profile name is empty");if("."===e||".."===e)throw new Error(`profile name "${e}" is not allowed`);if(e.includes("/")||e.includes("\\"))throw new Error(`profile name "${e}" must not contain path separators`);if(!lt.test(e))throw new Error(`profile name "${e}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var dt,ut,pt=async(e,t)=>{if(e?.authentication.credentials_path)return e.authentication.credentials_path;const s=await ft();if(!s)return null;const n=t??await mt();if(!n)return null;ht(n);const{path:r}=await(import("./node.browser-CE0N-lmH.js"));return r.join(s,"credentials",`${n}.json`)},ft=async()=>{if(!gt())return null;const{path:e}=await(import("./node.browser-CE0N-lmH.js")),t=Ke("ANTHROPIC_CONFIG_DIR");if(t)return t;if("Windows"===he()["X-Stainless-OS"]){const t=Ke("APPDATA");if(t)return e.join(t,"Anthropic");const s=Ke("USERPROFILE");return s?e.join(s,"AppData","Roaming","Anthropic"):null}const s=Ke("XDG_CONFIG_HOME");if(s)return e.join(s,"anthropic");const n=Ke("HOME");return n?e.join(n,".config","anthropic"):null},gt=()=>{const e=he()["X-Stainless-Runtime"];return"node"===e||"deno"===e},mt=async()=>{const e=await ft();if(!e)return null;const t=Ke("ANTHROPIC_PROFILE");if(t)return t;const{fs:s,path:n}=await(import("./node.browser-CE0N-lmH.js")),r=n.join(e,"active_config");try{return(await s.promises.readFile(r,"utf-8")).trim()||"default"}catch(i){if("ENOENT"!==i?.code)throw new Error(`failed to read ${r}: ${i}`);return"default"}};function _t(e){if(!e)throw new C("Identity token file path is empty");return async()=>{const{fs:t}=await(import("./node.browser-CE0N-lmH.js"));let s;try{s=await t.promises.readFile(e,"utf-8")}catch(r){throw new C(`Failed to read identity token file at ${e}: ${r}`)}const n=s.trim();if(!n)throw new C(`Identity token file at ${e} is empty`);return n}}function wt(e,t){const s=function(e,t,s,n){switch(e.authentication.type){case"oidc_federation":{const r=e.authentication,i=function(e){if(e.identity_token){const t=e.identity_token.source;if("file"!==t)throw new De(`identity_token.source "${t}" is not supported by this SDK version (only "file")`);if(!e.identity_token.path)throw new De('identity_token.source "file" requires a non-empty path');return _t(e.identity_token.path)}const t=Ke("ANTHROPIC_IDENTITY_TOKEN_FILE");if(t)return _t(t);const s=Ke("ANTHROPIC_IDENTITY_TOKEN");return s?function(e){if(!e)throw new C("Identity token value is empty");return()=>e}(s):null}(r);if(!i)throw new De("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)");if(!r.federation_rule_id)throw new De("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(!e.organization_id)throw new De("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");const o=function(e){return async()=>{Ce(e.baseURL);const t=await e.identityTokenProvider();if(t.length>16384)throw new De(`Identity token is ${Math.ceil(t.length/1024)} KiB, exceeds the 16 KiB assertion limit`);const s={grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:t,federation_rule_id:e.federationRuleId,organization_id:e.organizationId};e.serviceAccountId&&(s.service_account_id=e.serviceAccountId),e.workspaceId&&(s.workspace_id=e.workspaceId);const n=`${e.baseURL}${Me}`;let r;try{r=await e.fetch(n,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${Oe},oidc-federation-2026-04-01`,"User-Agent":e.userAgent||"anthropic-sdk-typescript/0.129.0 oidcFederationProvider"},body:JSON.stringify(s)})}catch(c){throw new De(`Failed to reach token endpoint ${n}: ${c}`)}const i=r.headers.get("Request-Id");if(!r.ok){const t=We(await r.text().catch(()=>""));let s="";throw 401===r.status&&(s=` Ensure your federation rule matches your identity token. ${e.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 De(`Token exchange failed with status ${r.status}${i?` (request-id ${i})`:""}: ${t}${s}`,r.status,t,i)}const o=await Le(r,i),a=Number(o.expires_in);if(!Number.isFinite(a))throw new De(`Token endpoint response missing required fields: ${JSON.stringify(We(o))}`,r.status,We(o),i);return{token:o.access_token,expiresAt:He()+a}}}({identityTokenProvider:i,federationRuleId:r.federation_rule_id,organizationId:e.organization_id,serviceAccountId:r.service_account_id,workspaceId:e.workspace_id,baseURL:s,fetch:n.fetch,userAgent:n.userAgent});return t?function(e,t,s,n){return async r=>{const{fs:i}=await(import("./node.browser-CE0N-lmH.js"));let o;await je(t,n);try{const e=await i.promises.readFile(t,"utf-8");o=JSON.parse(e);const s=o?.access_token;if(s&&!r?.forceRefresh){const e=o?.expires_at;if(null==e||He()<e-30)return{token:s,expiresAt:e??null}}}catch(c){"ENOENT"===c?.code||c instanceof SyntaxError||s?.(c)}const a=await e(r);try{await Ue(t,{...o??{},version:"1.0",type:"oauth_token",access_token:a.token,expires_at:a.expiresAt})}catch(c){s?.(c)}return a}}(o,t,n.onCacheWriteError,n.onSafetyWarning):o}case"user_oauth":if(!t)throw new De("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return function(e){return async t=>{const{fs:s}=await(import("./node.browser-CE0N-lmH.js"));let n,r;await je(e.credentialsPath,e.onSafetyWarning);try{n=await s.promises.readFile(e.credentialsPath,"utf-8")}catch(m){throw new De(`Credentials file not found at ${e.credentialsPath}: ${m}`)}try{r=JSON.parse(n)}catch(m){throw new De(`Credentials file at ${e.credentialsPath} is not valid JSON: ${m}`)}const i=r.access_token;if(!i)throw new De(`Credentials file at ${e.credentialsPath} must include 'access_token'`);const o=r.expires_at;if(!t?.forceRefresh&&(null==o||He()<o-30))return{token:i,expiresAt:o??null};const a=r.refresh_token;if(!e.clientId||!a)throw new De(`Access token at ${e.credentialsPath} has expired and no refresh is available (client_id ${e.clientId?"set":"empty"}, refresh_token ${a?"set":"empty"})`);Ce(e.baseURL);const c={grant_type:"refresh_token",refresh_token:a,client_id:e.clientId},l=`${e.baseURL}${Me}`;let h;try{h=await e.fetch(l,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":Oe,"User-Agent":e.userAgent||"anthropic-sdk-typescript/0.129.0 userOAuthProvider"},body:JSON.stringify(c)})}catch(m){throw new De(`User OAuth refresh failed to reach token endpoint: ${m}`)}const d=h.headers.get("Request-Id");if(!h.ok){const e=await h.text().catch(()=>"");throw new De(`User OAuth refresh failed (HTTP ${h.status}): ${We(e)}`,h.status,We(e),d)}const u=await Le(h,d),p=Number(u.expires_in);if(!Number.isFinite(p))throw new De(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(We(u))}`,h.status,We(u),d);const f=He()+p,g=u.refresh_token||a;return await Ue(e.credentialsPath,{...r,version:"1.0",type:"oauth_token",access_token:u.access_token,expires_at:f,refresh_token:g}),{token:u.access_token,expiresAt:f}}}({credentialsPath:t,clientId:e.authentication.client_id,baseURL:s,fetch:n.fetch,userAgent:n.userAgent,onSafetyWarning:n.onSafetyWarning});default:{const t=e.authentication.type;throw new De(`authentication.type "${t}" is not a known authentication type`)}}}(e,e.authentication.credentials_path??null,(e.base_url||t.baseURL).replace(/\/+$/,""),t),n={};return e.workspace_id&&"user_oauth"===e.authentication.type&&(n["anthropic-workspace-id"]=e.workspace_id),{provider:s,extraHeaders:n,baseURL:e.base_url||void 0}}var yt,bt=/* @__PURE__ */(()=>{class e{constructor(){dt.set(this,void 0),ut.set(this,void 0),X(this,dt,/* @__PURE__ */new Uint8Array,"f"),X(this,ut,null,"f")}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?Je(e):e;X(this,dt,function(e){let t=0;for(const r of e)t+=r.length;const s=new Uint8Array(t);let n=0;for(const r of e)s.set(r,n),n+=r.length;return s}([G(this,dt,"f"),t]),"f");const s=[];let n;for(;null!=(n=vt(G(this,dt,"f"),G(this,ut,"f")));){if(n.carriage&&null==G(this,ut,"f")){X(this,ut,n.index,"f");continue}if(null!=G(this,ut,"f")&&(n.index!==G(this,ut,"f")+1||n.carriage)){s.push(Ve(G(this,dt,"f").subarray(0,G(this,ut,"f")-1))),X(this,dt,G(this,dt,"f").subarray(G(this,ut,"f")),"f"),X(this,ut,null,"f");continue}const e=null!==G(this,ut,"f")?n.preceding-1:n.preceding,t=Ve(G(this,dt,"f").subarray(0,e));s.push(t),X(this,dt,G(this,dt,"f").subarray(n.index),"f"),X(this,ut,null,"f")}return s}flush(){return G(this,dt,"f").length?this.decode("\n"):[]}}return dt=/* @__PURE__ */new WeakMap,ut=/* @__PURE__ */new WeakMap,e.NEWLINE_CHARS=/* @__PURE__ */new Set(["\n","\r"]),e.NEWLINE_REGEXP=/\r\n|[\n\r]/g,e})();function vt(e,t){for(let s=t??0;s<e.length;s++){if(10===e[s])return{preceding:s,index:s+1,carriage:!1};if(13===e[s])return{preceding:s,index:s+1,carriage:!0}}return null}var kt=/* @__PURE__ */(()=>{class e{constructor(e,t,s){this.iterator=e,yt.set(this,void 0),this.controller=t,X(this,yt,s,"f")}static rawEvents(e,t=new AbortController){return St(e,t)}static fromSSEResponse(t,s,n){let r=!1;const i=n?rt(n):console;return new e(async function*(){if(r)throw new C("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let e=!1;try{for await(const e of St(t,s)){if("completion"===e.event)try{yield JSON.parse(e.data)}catch(n){throw i.error("Could not parse message into JSON:",e.data),i.error("From chunk:",e.raw),n}if("message_start"===e.event||"message_delta"===e.event||"message_stop"===e.event||"content_block_start"===e.event||"content_block_delta"===e.event||"content_block_stop"===e.event||"message"===e.event||"user.message"===e.event||"user.interrupt"===e.event||"user.tool_confirmation"===e.event||"user.custom_tool_result"===e.event||"user.tool_result"===e.event||"agent.message"===e.event||"agent.thinking"===e.event||"agent.tool_use"===e.event||"agent.tool_result"===e.event||"agent.mcp_tool_use"===e.event||"agent.mcp_tool_result"===e.event||"agent.custom_tool_use"===e.event||"agent.thread_context_compacted"===e.event||"session.status_running"===e.event||"session.status_idle"===e.event||"session.status_rescheduled"===e.event||"session.status_terminated"===e.event||"session.error"===e.event||"session.deleted"===e.event||"session.updated"===e.event||"span.model_request_start"===e.event||"span.model_request_end"===e.event||"span.outcome_evaluation_start"===e.event||"span.outcome_evaluation_ongoing"===e.event||"span.outcome_evaluation_end"===e.event||"user.define_outcome"===e.event||"agent.thread_message_received"===e.event||"agent.thread_message_sent"===e.event||"agent.session_thread_message_received"===e.event||"agent.session_thread_message_sent"===e.event||"session.thread_created"===e.event||"session.thread_status_created"===e.event||"session.thread_status_running"===e.event||"session.thread_status_idle"===e.event||"session.thread_status_rescheduled"===e.event||"session.thread_status_terminated"===e.event||"event_start"===e.event||"event_delta"===e.event||"system.message"===e.event)try{yield JSON.parse(e.data)}catch(n){throw i.error("Could not parse message into JSON:",e.data),i.error("From chunk:",e.raw),n}if("ping"!==e.event&&"error"===e.event){const s=ie(e.data)??e.data,n=s?.error?.type;throw new L(void 0,s,void 0,t.headers,n)}}e=!0}catch(n){if(O(n))return;throw n}finally{e||s.abort(),pe(s)}},s,n)}static fromReadableStream(t,s,n){let r=!1;return new e(async function*(){if(r)throw new C("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let e=!1;try{for await(const s of async function*(){const e=new bt,s=me(t);for await(const t of s)for(const s of e.decode(t))yield s;for(const t of e.flush())yield t}())e||s&&(yield JSON.parse(s));e=!0}catch(n){if(O(n))return;throw n}finally{e||s.abort(),pe(s)}},s,n)}[(yt=/* @__PURE__ */new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const t=[],s=[],n=this.iterator(),r=e=>({next:()=>{if(0===e.length){const e=n.next();t.push(e),s.push(e)}return e.shift()}});return[new e(()=>r(t),this.controller,G(this,yt,"f")),new e(()=>r(s),this.controller,G(this,yt,"f"))]}toReadableStream(){const e=this;let t;return fe({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:s,done:n}=await t.next();if(n)return e.close();const r=Je(JSON.stringify(s)+"\n");e.enqueue(r)}catch(s){e.error(s)}},async cancel(){await(t.return?.())}})}}return e})();async function*St(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new C("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new C("Attempted to iterate over a response with no body")}const s=new xt,n=new bt,r=me(e.body);for await(const i of r)for(const e of n.decode(i)){const t=s.decode(e);t&&(yield t)}for(const i of n.flush()){const e=s.decode(i);e&&(yield e)}}var xt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,n]=function(e){const t=e.indexOf(":");return-1!==t?[e.substring(0,t),":",e.substring(t+1)]:[e,"",""]}(e);return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}};async function Rt(e,t){const{response:s,requestLogID:n,retryOfRequestLogID:r,startTime:i}=t,o=await(async()=>{if(t.options.stream)return rt(e).debug("response",s.status,s.url,s.headers,s.body),kt.fromSSEResponse(s,t.controller,e);if(204===s.status)return null;if(t.options.__binaryResponse)return s;const n=s.headers.get("content-type")?.split(";")[0]?.trim();if(n?.includes("application/json")||n?.endsWith("+json")){if("0"===s.headers.get("content-length"))return;return It(await s.json(),s)}return await s.text()})().finally(()=>{t.options.stream||t.options.__binaryResponse||pe(t.controller)});return ot(rt(e),`[${n}] response parsed`,{retryOfRequestLogID:r,url:s.url,status:s.status,body:o,durationMs:Date.now()-i}),o}function It(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperties(e,{_request_id:{value:t.headers.get("request-id"),enumerable:!1},_workspace_id:{value:t.headers.get("anthropic-workspace-id"),enumerable:!1}})}var At,$t=/* @__PURE__ */new WeakSet;function Tt(e){return"object"==typeof e&&null!==e&&$t.has(e)}function Et(e,t,s,n){return async(r,i={})=>{if(0===t.length)return e.call(void 0,r,i);const o=i.headers instanceof Headers?i.headers:new Headers(i.headers),a=await function(e,t,s,n){let r=async({url:t,...s})=>{try{return await e.call(void 0,t,s)}catch(n){const e=P(n);throw $t.add(e),e}};const i=function(e,t){const s=/* @__PURE__ */new WeakMap;return{options:e,logger:t?rt(t):it(),parse(n){if(e?.stream&&n.ok)return Mt(n,e,t);let r=s.get(n);return r||(r=Mt(n,e,t),s.set(n,r)),r}}}(s,n);for(let o=t.length-1;o>=0;o--){const e=t[o],s=r;r=async t=>e(t,s,i)}return r}(e,t,s,n)({...i,headers:o,url:"string"==typeof r?r:r instanceof URL?r.href:r.url});if(a.bodyUsed||a.body?.locked)throw new C("middleware consumed the response body; use response.clone() to inspect it, or return new Response(body, response) to consume and replace it");return a}}async function Mt(e,t,s){if(e.bodyUsed||e.body?.locked)throw new C("cannot ctx.parse() a response whose body was already consumed; call ctx.parse() instead of reading the body, or read via response.clone()");if(t?.stream&&e.ok)return kt.fromSSEResponse(e.clone(),new AbortController,s);if(204===e.status)return null;if(t?.__binaryResponse)return e;const n=e.headers.get("content-type")?.split(";")[0]?.trim();if(n?.includes("application/json")||n?.endsWith("+json")){if("0"===e.headers.get("content-length"))return;return It(await e.clone().json(),e)}return await e.clone().text()}var Ot,Pt=/* @__PURE__ */(()=>{class e extends Promise{constructor(e,t,s=Rt){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=s,At.set(this,void 0),X(this,At,e,"f")}_thenUnwrap(t){return new e(G(this,At,"f"),this.responsePromise,async(e,s)=>It(t(await this.parseResponse(e,s),s),s.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id"),workspace_id:t.headers.get("anthropic-workspace-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(G(this,At,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}return At=/* @__PURE__ */new WeakMap,e})(),Ct=/* @__PURE__ */(()=>{class e{constructor(e,t,s,n){Ot.set(this,void 0),X(this,Ot,e,"f"),this.options=n,this.response=t,this.body=s}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageRequestOptions()}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new C("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await G(this,Ot,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ot=/* @__PURE__ */new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}return e})(),Lt=/* @__PURE__ */(()=>{class e extends Pt{constructor(e,t,s){super(e,t,async(e,t)=>new s(e,t.response,await Rt(e,t),t.options))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}return e})(),Nt=class extends Ct{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1,this.first_id=s.first_id||null,this.last_id=s.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){const e=this.first_id;return e?{...this.options,query:{...ee(this.options.query),before_id:e}}:null}const e=this.last_id;return e?{...this.options,query:{...ee(this.options.query),after_id:e}}:null}},qt=class extends Ct{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.next_page=s.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){const e=this.next_page;return e?{...this.options,query:{...ee(this.options.query),page:e}}:null}},Wt=class extends Ct{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.next_page=s.next_page||null,this.prev_page=s.prev_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){const e=this.next_page;return e?{...this.options,query:{...ee(this.options.query),page:e}}:null}},jt=()=>{if("undefined"==typeof File){const{process:e}=globalThis,t="string"==typeof e?.versions?.node&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Ut(e,t,s){return jt(),new File(e,t??"",s)}function Dt(e,t){const s="object"==typeof e&&null!==e&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"";return t?s.split(/[\\/]/).pop()||void 0:s}var Ht=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],zt=async(e,t,s=!0)=>({...e,body:await Bt(e.body,t,s)}),Ft=/* @__PURE__ */new WeakMap,Bt=async(e,t,s=!0)=>{if(!(await function(e){const t="function"==typeof e?e:e.fetch,s=Ft.get(t);if(s)return s;const n=(async()=>{try{const e="Response"in t?t.Response:(await t("data:,")).constructor,s=new FormData;return s.toString()!==await new e(s).text()}catch{return!0}})();return Ft.set(t,n),n}(t)))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(e||{}).map(([e,t])=>Kt(n,e,t,s))),n},Kt=async(e,t,s,n)=>{if(void 0!==s){if(null==s)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof s||"number"==typeof s||"boolean"==typeof s)e.append(t,String(s));else if(s instanceof Response){let r={};const i=s.headers.get("Content-Type");i&&(r={type:i}),e.append(t,Ut([await s.blob()],Dt(s,n),r))}else if(Ht(s))e.append(t,Ut([await new Response(ge(s)).blob()],Dt(s,n)));else if(s instanceof Blob){const r="undefined"!=typeof File&&s instanceof File?s.name:Dt(s,n);e.append(t,Ut([s],r,{type:s.type}))}else if(Array.isArray(s))await Promise.all(s.map(s=>Kt(e,t+"[]",s,n)));else{if("function"==typeof s.then)throw new TypeError(`Received a Promise for "${t}"; await it first, e.g. \`await toFile(...)\``);if(s instanceof ArrayBuffer||ArrayBuffer.isView(s))throw new TypeError(`Received ${s.constructor.name} for "${t}"; to upload raw bytes, wrap them with \`await toFile(bytes, 'filename')\``);if("object"!=typeof s)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${s} instead`);await Promise.all(Object.entries(s).map(([s,r])=>Kt(e,`${t}[${s}]`,r,n)))}}},Jt=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function Vt(e,t,s){if(jt(),e=await e,t||(t=e instanceof File?e.name:Dt(e,!0)),(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&Jt(e))(e))return e instanceof File&&null==t&&null==s?e:Ut([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...s});if((e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob)(e)){const n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Ut(await Xt(n),t,s)}const n=await Xt(e);if(!s?.type){const e=n.find(e=>"object"==typeof e&&"type"in e&&e.type);"string"==typeof e&&(s={...s,type:e})}return Ut(n,t,s)}async function Xt(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Jt(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else{if(!Ht(e)){const t=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){return"object"!=typeof e||null===e?"":`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(", ")}]`}(e)}`)}for await(const s of e)t.push(...await Xt(s))}return t}var Gt=class{constructor(e){this._client=e}},Yt=Symbol.for("brand.privateNullableHeaders");function*Qt(e){if(!e)return;if(Yt in e){const{values:t,nulls:s}=e;yield*t.entries();for(const e of s)yield[e,null];return}let t,s=!1;e instanceof Headers?t=e.entries():Z(e)?t=e:(s=!0,t=Object.entries(e??{}));for(let n of t){const e=n[0];if("string"!=typeof e)throw new TypeError("expected header name to be a string");const t=Z(n[1])?n[1]:[n[1]];let r=!1;for(const n of t)void 0!==n&&(s&&!r&&(r=!0,yield[e,Zt]),yield[e,n])}}var Zt=Symbol("clear"),es=/* @__PURE__ */new Set(["x-stainless-helper"]),ts=(e,t)=>{const s=e?e.split(",").map(e=>e.trim()).filter(Boolean):[];for(const n of t.split(",").map(e=>e.trim()))n&&!s.includes(n)&&s.push(n);return s.join(", ")},ss=e=>{const t=new Headers,s=/* @__PURE__ */new Set;for(const n of e){const e=/* @__PURE__ */new Set;for(const[r,i]of Qt(n)){const n=r.toLowerCase();if(es.has(n)){if(i===Zt)continue;null===i?(t.delete(r),s.add(n)):(t.set(r,ts(t.get(r),i)),s.delete(n))}else(i!==Zt&&e.has(n)||(t.delete(r),e.add(n),i!==Zt))&&(null===i?(t.delete(r),s.add(n)):(t.append(r,i),s.delete(n)))}}return{[Yt]:!0,values:t,nulls:s}};function ns(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var rs=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.create(null)),is=(e=ns)=>function(t,...s){if(1===t.length)return t[0];let n=!1;const r=[],i=t.reduce((t,i,o)=>{/[?#]/.test(i)&&(n=!0);const a=s[o];let c=(n?encodeURIComponent:e)(""+a);return o!==s.length&&(null==a||"object"==typeof a&&a.toString===Object.getPrototypeOf(Object.getPrototypeOf(a.hasOwnProperty??rs)??rs)?.toString)&&(c=a+"",r.push({start:t.length+i.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(a).slice(8,-1)} is not a valid path parameter`})),t+i+(o===s.length?"":c)},""),o=i.split(/[?#]/,1)[0],a=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let c;for(;null!==(c=a.exec(o));)r.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(r.sort((e,t)=>e.start-t.start),r.length>0){let e=0;const t=r.reduce((t,s)=>{const n=" ".repeat(s.start-e),r="^".repeat(s.length);return e=s.start+s.length,t+n+r},"");throw new C(`Path parameters result in path with invalid segments:\n${r.map(e=>e.error).join("\n")}\n${i}\n${t}`)}return i},os=/* @__PURE__ */is(ns),as=class extends Gt{retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/deployment_runs/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/deployment_runs?beta=true",qt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}},cs=class extends Gt{create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/deployments?beta=true",{body:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/deployments/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}update(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/deployments/${e}?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/deployments?beta=true",qt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}archive(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/deployments/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}pause(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/deployments/${e}/pause?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}run(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/deployments/${e}/run?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}unpause(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/deployments/${e}/unpause?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},ls=class extends Gt{create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/dreams?beta=true",{body:r,...t,headers:ss([{"anthropic-beta":[...s??[],"dreaming-2026-04-21"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/dreams/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"dreaming-2026-04-21"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/dreams?beta=true",qt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"dreaming-2026-04-21"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}archive(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/dreams/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"dreaming-2026-04-21"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}cancel(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/dreams/${e}/cancel?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"dreaming-2026-04-21"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},hs="x-stainless-helper",ds="x-stainless-helper-method";function us(e){return{[hs]:e}}var ps=Symbol("anthropic.sdk.stainlessHelper");function fs(e){return"object"==typeof e&&null!==e&&ps in e}function gs(e,t){const s=/* @__PURE__ */new Set;if(e)for(const n of e)fs(n)&&s.add(n[ps]);if(t)for(const n of t){fs(n)&&s.add(n[ps]);const e=n.content;if(Array.isArray(e))for(const t of e){fs(t)&&s.add(t[ps]);const e=t?.tool?.definition;fs(e)&&s.add(e[ps])}}return Array.from(s)}function ms(e,t){const s=gs(e,t);return 0===s.length?{}:{[hs]:s.join(", ")}}function _s(e){return fs(e)?{[hs]:e[ps]}:{}}var ws,ys,bs,vs,ks,Ss,xs,Rs,Is,As,$s,Ts,Es,Ms=class extends Gt{list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/files?beta=true",qt,{query:r,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}delete(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.delete(os`/v1/files/${e}?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}download(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/files/${e}/content?beta=true`,{...s,headers:ss([{Accept:"application/binary",...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/files/${e}?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}upload(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/files?beta=true",zt({body:r,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},_s(r.file),t?.headers])},this._client))}},Os=class extends Gt{retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/models/${e}?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/models?beta=true",Nt,{query:r,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}},Ps=class extends Gt{create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/user_profiles?beta=true",{body:r,...t,headers:ss([{"anthropic-beta":[...s??[],"user-profiles-2026-08-18"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/user_profiles/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"user-profiles-2026-08-18"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}update(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/user_profiles/${e}?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"user-profiles-2026-08-18"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/user_profiles?beta=true",qt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"user-profiles-2026-08-18"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}createEnrollmentURL(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"user-profiles-2026-08-18"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},Cs=/* @__PURE__ */t(e=>{var t,s=e&&e.__extends||(t=function(e,s){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var s in t)t.hasOwnProperty(s)&&(e[s]=t[s])},t(e,s)},function(e,s){function n(){this.constructor=e}t(e,s),e.prototype=null===s?Object.create(s):(n.prototype=s.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var n=256,r=function(){function e(e){void 0===e&&(e="="),this._paddingCharacter=e}return e.prototype.encodedLength=function(e){return this._paddingCharacter?(e+2)/3*4|0:(8*e+5)/6|0},e.prototype.encode=function(e){for(var t="",s=0;s<e.length-2;s+=3){var n=e[s]<<16|e[s+1]<<8|e[s+2];t+=this._encodeByte(n>>>18&63),t+=this._encodeByte(n>>>12&63),t+=this._encodeByte(n>>>6&63),t+=this._encodeByte(n>>>0&63)}var r=e.length-s;return r>0&&(n=e[s]<<16|(2===r?e[s+1]<<8:0),t+=this._encodeByte(n>>>18&63),t+=this._encodeByte(n>>>12&63),t+=2===r?this._encodeByte(n>>>6&63):this._paddingCharacter||"",t+=this._paddingCharacter||""),t},e.prototype.maxDecodedLength=function(e){return this._paddingCharacter?e/4*3|0:(6*e+7)/8|0},e.prototype.decodedLength=function(e){return this.maxDecodedLength(e.length-this._getPaddingLength(e))},e.prototype.decode=function(e){if(0===e.length)/* @__PURE__ */return new Uint8Array(0);for(var t=this._getPaddingLength(e),s=e.length-t,r=new Uint8Array(this.maxDecodedLength(s)),i=0,o=0,a=0,c=0,l=0,h=0,d=0;o<s-4;o+=4)c=this._decodeChar(e.charCodeAt(o+0)),l=this._decodeChar(e.charCodeAt(o+1)),h=this._decodeChar(e.charCodeAt(o+2)),d=this._decodeChar(e.charCodeAt(o+3)),r[i++]=c<<2|l>>>4,r[i++]=l<<4|h>>>2,r[i++]=h<<6|d,a|=c&n,a|=l&n,a|=h&n,a|=d&n;if(o<s-1&&(c=this._decodeChar(e.charCodeAt(o)),l=this._decodeChar(e.charCodeAt(o+1)),r[i++]=c<<2|l>>>4,a|=c&n,a|=l&n),o<s-2&&(h=this._decodeChar(e.charCodeAt(o+2)),r[i++]=l<<4|h>>>2,a|=h&n),o<s-3&&(d=this._decodeChar(e.charCodeAt(o+3)),r[i++]=h<<6|d,a|=d&n),0!==a)throw new Error("Base64Coder: incorrect characters for decoding");return r},e.prototype._encodeByte=function(e){var t=e;return t+=65,t+=25-e>>>8&6,t+=51-e>>>8&-75,t+=61-e>>>8&-15,t+=62-e>>>8&3,String.fromCharCode(t)},e.prototype._decodeChar=function(e){var t=n;return t+=(42-e&e-44)>>>8&-256+e-43+62,t+=(46-e&e-48)>>>8&-256+e-47+63,t+=(47-e&e-58)>>>8&-256+e-48+52,(t+=(64-e&e-91)>>>8&-256+e-65+0)+((96-e&e-123)>>>8&-256+e-97+26)},e.prototype._getPaddingLength=function(e){var t=0;if(this._paddingCharacter){for(var s=e.length-1;s>=0&&e[s]===this._paddingCharacter;s--)t++;if(e.length<4||t>2)throw new Error("Base64Coder: incorrect padding")}return t},e}();e.Coder=r;var i=new r;e.encode=function(e){return i.encode(e)},e.decode=function(e){return i.decode(e)};var o=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return s(t,e),t.prototype._encodeByte=function(e){var t=e;return t+=65,t+=25-e>>>8&6,t+=51-e>>>8&-75,t+=61-e>>>8&-13,t+=62-e>>>8&49,String.fromCharCode(t)},t.prototype._decodeChar=function(e){var t=n;return t+=(44-e&e-46)>>>8&-256+e-45+62,t+=(94-e&e-96)>>>8&-256+e-95+63,t+=(47-e&e-58)>>>8&-256+e-48+52,(t+=(64-e&e-91)>>>8&-256+e-65+0)+((96-e&e-123)>>>8&-256+e-97+26)},t}(r);e.URLSafeCoder=o;var a=new o;e.encodeURLSafe=function(e){return a.encode(e)},e.decodeURLSafe=function(e){return a.decode(e)},e.encodedLength=function(e){return i.encodedLength(e)},e.maxDecodedLength=function(e){return i.maxDecodedLength(e)},e.decodedLength=function(e){return i.decodedLength(e)}}),Ls=/* @__PURE__ */t((e,t)=>{!function(e){var s={};!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 s(e,s,n,r,i){for(var o,a,c,l,h,d,u,p,f,g,m,_,w;i>=64;){for(o=s[0],a=s[1],c=s[2],l=s[3],h=s[4],d=s[5],u=s[6],p=s[7],g=0;g<16;g++)m=r+4*g,e[g]=(255&n[m])<<24|(255&n[m+1])<<16|(255&n[m+2])<<8|255&n[m+3];for(g=16;g<64;g++)_=((f=e[g-2])>>>17|f<<15)^(f>>>19|f<<13)^f>>>10,w=((f=e[g-15])>>>7|f<<25)^(f>>>18|f<<14)^f>>>3,e[g]=(_+e[g-7]|0)+(w+e[g-16]|0);for(g=0;g<64;g++)_=(((h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7))+(h&d^~h&u)|0)+(p+(t[g]+e[g]|0)|0)|0,w=((o>>>2|o<<30)^(o>>>13|o<<19)^(o>>>22|o<<10))+(o&a^o&c^a&c)|0,p=u,u=d,d=h,h=l+_|0,l=c,c=a,a=o,o=_+w|0;s[0]+=o,s[1]+=a,s[2]+=c,s[3]+=l,s[4]+=h,s[5]+=d,s[6]+=u,s[7]+=p,r+=64,i-=64}return r}var n=function(){function t(){this.digestLength=e.digestLength,this.blockSize=e.blockSize,this.state=/* @__PURE__ */new Int32Array(8),this.temp=/* @__PURE__ */new Int32Array(64),this.buffer=/* @__PURE__ */new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return t.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},t.prototype.clean=function(){for(var e=0;e<this.buffer.length;e++)this.buffer[e]=0;for(e=0;e<this.temp.length;e++)this.temp[e]=0;this.reset()},t.prototype.update=function(e,t){if(void 0===t&&(t=e.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");var n=0;if(this.bytesHashed+=t,this.bufferLength>0){for(;this.bufferLength<64&&t>0;)this.buffer[this.bufferLength++]=e[n++],t--;64===this.bufferLength&&(s(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(t>=64&&(n=s(this.temp,this.state,e,n,t),t%=64);t>0;)this.buffer[this.bufferLength++]=e[n++],t--;return this},t.prototype.finish=function(e){if(!this.finished){var t=this.bytesHashed,n=this.bufferLength,r=t/536870912|0,i=t<<3,o=t%64<56?64:128;this.buffer[n]=128;for(var a=n+1;a<o-8;a++)this.buffer[a]=0;this.buffer[o-8]=r>>>24&255,this.buffer[o-7]=r>>>16&255,this.buffer[o-6]=r>>>8&255,this.buffer[o-5]=r>>>0&255,this.buffer[o-4]=i>>>24&255,this.buffer[o-3]=i>>>16&255,this.buffer[o-2]=i>>>8&255,this.buffer[o-1]=i>>>0&255,s(this.temp,this.state,this.buffer,0,o),this.finished=!0}for(a=0;a<8;a++)e[4*a+0]=this.state[a]>>>24&255,e[4*a+1]=this.state[a]>>>16&255,e[4*a+2]=this.state[a]>>>8&255,e[4*a+3]=this.state[a]>>>0&255;return this},t.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},t.prototype._saveState=function(e){for(var t=0;t<this.state.length;t++)e[t]=this.state[t]},t.prototype._restoreState=function(e,t){for(var s=0;s<this.state.length;s++)this.state[s]=e[s];this.bytesHashed=t,this.finished=!1,this.bufferLength=0},t}();e.Hash=n;var r=function(){function e(e){this.inner=new n,this.outer=new n,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var t=new Uint8Array(this.blockSize);if(e.length>this.blockSize)(new n).update(e).finish(t).clean();else for(var s=0;s<e.length;s++)t[s]=e[s];for(s=0;s<t.length;s++)t[s]^=54;for(this.inner.update(t),s=0;s<t.length;s++)t[s]^=106;for(this.outer.update(t),this.istate=/* @__PURE__ */new Uint32Array(8),this.ostate=/* @__PURE__ */new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate),s=0;s<t.length;s++)t[s]=0}return e.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},e.prototype.clean=function(){for(var e=0;e<this.istate.length;e++)this.ostate[e]=this.istate[e]=0;this.inner.clean(),this.outer.clean()},e.prototype.update=function(e){return this.inner.update(e),this},e.prototype.finish=function(e){return this.outer.finished?this.outer.finish(e):(this.inner.finish(e),this.outer.update(e,this.digestLength).finish(e)),this},e.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},e}();function i(e){var t=(new n).update(e),s=t.digest();return t.clean(),s}function o(e,t){var s=new r(e).update(t),n=s.digest();return s.clean(),n}function a(e,t,s,n){var r=n[0];if(0===r)throw new Error("hkdf: cannot expand more");t.reset(),r>1&&t.update(e),s&&t.update(s),t.update(n),t.finish(e),n[0]++}e.HMAC=r,e.hash=i,e.default=i,e.hmac=o;var c=new Uint8Array(e.digestLength);e.hkdf=function(e,t,s,n){void 0===t&&(t=c),void 0===n&&(n=32);for(var i=new Uint8Array([1]),l=new r(o(t,e)),h=new Uint8Array(l.digestLength),d=h.length,u=new Uint8Array(n),p=0;p<n;p++)d===h.length&&(a(h,l,s,i),d=0),u[p]=h[d++];return l.clean(),h.fill(0),i.fill(0),u},e.pbkdf2=function(e,t,s,n){for(var i=new r(e),o=i.digestLength,a=/* @__PURE__ */new Uint8Array(4),c=new Uint8Array(o),l=new Uint8Array(o),h=new Uint8Array(n),d=0;d*o<n;d++){var u=d+1;a[0]=u>>>24&255,a[1]=u>>>16&255,a[2]=u>>>8&255,a[3]=u>>>0&255,i.reset(),i.update(t),i.update(a),i.finish(l);for(var p=0;p<o;p++)c[p]=l[p];for(p=2;p<=s;p++){i.reset(),i.update(l).finish(l);for(var f=0;f<o;f++)c[f]^=l[f]}for(p=0;p<o&&d*o+p<n;p++)h[d*o+p]=c[p]}for(d=0;d<o;d++)c[d]=l[d]=0;for(d=0;d<4;d++)a[d]=0;return i.clean(),h}}(s);var n=s.default;for(var r in s)n[r]=s[r];"object"==typeof t&&"object"==typeof t.exports?t.exports=n:"function"==typeof define&&define.amd?define(function(){return n}):e.sha256=n}(e)}),Ns=/* @__PURE__ */t(e=>{function t(e,t=""){if(!e)throw new Error(t)}Object.defineProperty(e,"__esModule",{value:!0}),e.timingSafeEqual=function(e,s){if(e.byteLength!==s.byteLength)return!1;e instanceof DataView||(e=new DataView(ArrayBuffer.isView(e)?e.buffer:e)),s instanceof DataView||(s=new DataView(ArrayBuffer.isView(s)?s.buffer:s)),t(e instanceof DataView),t(s instanceof DataView);const n=e.byteLength;let r=0,i=-1;for(;++i<n;)r|=e.getUint8(i)^s.getUint8(i);return 0===r}}),qs=/* @__PURE__ */t(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Webhook=e.WebhookVerificationError=void 0;var t=Cs(),s=Ls(),n=Ns(),r=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype),this.name="ExtendableError",this.stack=new Error(t).stack}},i=class e extends r{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype),this.name="WebhookVerificationError"}};e.WebhookVerificationError=i;var o=class e{constructor(s,n){if("raw"===(null==n?void 0:n.format))s instanceof Uint8Array?this.key=s:this.key=Uint8Array.from(s,e=>e.charCodeAt(0));else{if("string"!=typeof s)throw new Error("Expected secret to be of type string");s.startsWith(e.prefix)&&(s=s.substring(e.prefix.length)),this.key=t.decode(s)}if(0===this.key.length)throw new Error("Secret can't be empty.")}verify(e,t,s){var r;const o=null===(r=null==s?void 0:s.jsonParse)||void 0===r||r,a={};for(const n of Object.keys(t))a[n.toLowerCase()]=t[n];const c=a["webhook-id"],l=a["webhook-signature"],h=a["webhook-timestamp"];if(!l||!c||!h)throw new i("Missing required headers");const d=this.verifyTimestamp(h),u=this.sign(c,d,e).split(",")[1],p=l.split(" "),f=new globalThis.TextEncoder;for(const i of p){const[t,s]=i.split(",");if("v1"===t&&(0,n.timingSafeEqual)(f.encode(s),f.encode(u))){const t=e.toString();if(""===t)return;return o?JSON.parse(t):void 0}}throw new i("No matching signature found")}sign(e,n,r){if("string"==typeof r);else{if("Buffer"!==r.constructor.name)throw new Error("Expected payload to be of type string or Buffer.");r=r.toString()}const i=new TextEncoder,o=Math.floor(n.getTime()/1e3),a=i.encode(`${e}.${o}.${r}`);return`v1,${t.encode(s.hmac(this.key,a))}`}verifyTimestamp(e){const t=Math.floor(Date.now()/1e3),s=parseInt(e,10);if(Number.isNaN(s))throw new i("Invalid Signature Headers");if(t-s>300)throw new i("Message timestamp too old");if(s>t+300)throw new i("Message timestamp too new");/* @__PURE__ */
2
+ return new Date(1e3*s)}};e.Webhook=o,o.prefix="whsec_"}),Ws=qs(),js=class extends Gt{parseUnverified(e){return JSON.parse(e)}unwrap(e,t){const s=t?.headers;if(null==s)throw new Error("Webhook headers are required in order to verify the signature");const n=void 0===t.key?this._client.webhookKey:t.key;if(!n)throw new Error("Webhook key must not be null or empty in order to unwrap");return new Ws.Webhook(n).verify(e,s),JSON.parse(e)}},Us=class extends Gt{list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(os`/v1/agents/${e}/versions?beta=true`,qt,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},Ds=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.versions=new Us(this._client)}create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/agents?beta=true",{body:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.get(os`/v1/agents/${e}?beta=true`,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}update(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/agents/${e}?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/agents?beta=true",qt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}archive(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/agents/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Versions=Us,e})();function Hs(e,t){if(!e)return()=>{};if(e.aborted)return t.abort(),()=>{};const s=()=>t.abort();return e.addEventListener("abort",s),()=>e.removeEventListener("abort",s)}function zs(e,t){return e instanceof L&&e.status===t}function Fs(e){return function(e){return e instanceof L&&"number"==typeof e.status&&e.status>=400&&e.status<500}(e)&&!zs(e,408)&&!zs(e,409)&&!zs(e,429)}function Bs(e,t,s){return Math.min(t*2**e,s)}function Ks(e,t){return e+Math.random()*(t-e)}function Js(e){return e*(1-.25*Math.random())}function Vs(e,{authToken:t,helper:s}){if(!t)throw new C(`copyClientForHelper: expected a non-empty authToken but received ${JSON.stringify(t)}`);const n=e,r=n._options.defaultHeaders,i=n._authState?.extraHeaders,o=i?Object.fromEntries(Object.entries(i).filter(([e])=>{const t=e.toLowerCase();return"authorization"!==t&&"x-api-key"!==t})):void 0,a=ss([o,r,{[hs]:s}]);return e.withOptions({apiKey:null,authToken:t,baseURL:e.baseURL,credentials:void 0,defaultHeaders:a})}var Xs=/* @__PURE__ */(()=>{class e{constructor(e){ws.set(this,void 0),ys.set(this,!1),bs.set(this,void 0),vs.set(this,void 0),ks.set(this,void 0),Ss.set(this,void 0),xs.set(this,void 0),Rs.set(this,void 0),Is.set(this,void 0),this.client=e.client,this.environmentId=e.environmentId,this.environmentKey=e.environmentKey,this.workerId=e.workerId??function(){const e=(globalThis.process?.env)?.HOSTNAME;return e?`${e}-${ct()}`:ct()}(),X(this,ws,Vs(e.client,{authToken:e.environmentKey,helper:"environments-work-poller"}),"f"),X(this,ks,e.autoStop??!0,"f"),X(this,Ss,e.drain??!1,"f"),X(this,xs,void 0===e.blockMs?999:e.blockMs,"f"),X(this,Rs,e.reclaimOlderThanMs??null,"f"),X(this,Is,e.requestOptions,"f"),X(this,bs,new AbortController,"f"),X(this,vs,Hs(e.signal,G(this,bs,"f")),"f")}get signal(){return G(this,bs,"f").signal}abort(){G(this,bs,"f").abort()}async*[(ws=/* @__PURE__ */new WeakMap,ys=/* @__PURE__ */new WeakMap,bs=/* @__PURE__ */new WeakMap,vs=/* @__PURE__ */new WeakMap,ks=/* @__PURE__ */new WeakMap,Ss=/* @__PURE__ */new WeakMap,xs=/* @__PURE__ */new WeakMap,Rs=/* @__PURE__ */new WeakMap,Is=/* @__PURE__ */new WeakMap,Symbol.asyncIterator)](){if(G(this,ys,"f"))throw new C("Cannot iterate over a consumed WorkPoller");X(this,ys,!0,"f");const e=rt(this.client);e.info("poller starting",{component:"work-poller",environment_id:this.environmentId});const t=new Cn(e,this.environmentId);try{let n=0;for(;!G(this,bs,"f").signal.aborted;){let r;try{r=await G(this,ws,"f").beta.environments.work.poll(this.environmentId,{"Anthropic-Worker-ID":this.workerId,...null!==G(this,xs,"f")?{block_ms:G(this,xs,"f")}:{},...null!==G(this,Rs,"f")?{reclaim_older_than_ms:G(this,Rs,"f")}:{}},{headers:ss([G(this,Is,"f")?.headers]),signal:G(this,bs,"f").signal})}catch(s){if(G(this,bs,"f").signal.aborted)return;if(Fs(s))throw e.error("poll failed permanently, stopping poller",{error:String(s)}),s;const t=Js(Gs(n));e.warn("poll failed, backing off",{error:String(s),backoff_ms:t}),n++,await oe(t,G(this,bs,"f").signal);continue}if(n=0,null!=r){t.onClaim(),e.info("claimed work",{component:"work-poller",environment_id:this.environmentId,work_id:r.id,work_type:r.data.type});try{await G(this,ws,"f").beta.environments.work.ack(r.id,{environment_id:r.environment_id},{headers:ss([G(this,Is,"f")?.headers]),signal:G(this,bs,"f").signal})}catch(s){e.error("ack failed",{work_id:r.id,error:String(s)});continue}try{yield r}finally{if(G(this,ks,"f"))try{await G(this,ws,"f").beta.environments.work.stop(r.id,{environment_id:r.environment_id},{headers:ss([G(this,Is,"f")?.headers])})}catch(s){zs(s,409)||e.warn("stop failed",{work_id:r.id,error:String(s)})}}}else{if(G(this,Ss,"f"))return;t.onEmptyPoll(),await oe(Ks(1e3,3e3),G(this,bs,"f").signal)}}}finally{G(this,vs,"f").call(this)}}}return e})();function Gs(e){return Bs(e,1e3,6e4)}var Ys,Qs,Zs,en,tn,sn,nn,rn,on,an,cn,ln,hn,dn,un,pn,fn,gn,mn,_n,wn,yn,bn,vn,kn,Sn,xn,Rn,In,An,$n,Tn,En,Mn,On,Pn,Cn=/* @__PURE__ */(()=>(As=/* @__PURE__ */new WeakMap,$s=/* @__PURE__ */new WeakMap,Ts=/* @__PURE__ */new WeakMap,Es=/* @__PURE__ */new WeakMap,class{constructor(e,t){As.set(this,void 0),$s.set(this,void 0),Ts.set(this,void 0),Es.set(this,0),X(this,As,e,"f"),X(this,$s,t,"f")}onEmptyPoll(){const e=Date.now(),t={component:"work-poller",environment_id:G(this,$s,"f")};void 0===G(this,Ts,"f")?(X(this,Ts,X(this,Es,e,"f"),"f"),G(this,As,"f").info("idle; polling for work",t)):e-G(this,Es,"f")>=3e5?(X(this,Es,e,"f"),G(this,As,"f").info(`still polling; idle for ${Math.round((e-G(this,Ts,"f"))/1e3)}s`,t)):G(this,As,"f").debug("poll returned no work",t)}onClaim(){X(this,Ts,void 0,"f")}}))(),Ln=/* @__PURE__ */(()=>(Ys=/* @__PURE__ */new WeakMap,Qs=/* @__PURE__ */new WeakMap,Zs=/* @__PURE__ */new WeakMap,class{constructor(){Ys.set(this,[]),Qs.set(this,[]),Zs.set(this,!1)}push(e){if(G(this,Zs,"f"))return!1;const t=G(this,Qs,"f").shift();return t?t({done:!1,value:e}):G(this,Ys,"f").push(e),!0}close(){if(!G(this,Zs,"f"))for(X(this,Zs,!0,"f");G(this,Qs,"f").length>0;)G(this,Qs,"f").shift()({done:!0,value:void 0})}next(e){return G(this,Ys,"f").length>0?Promise.resolve({done:!1,value:G(this,Ys,"f").shift()}):G(this,Zs,"f")||e?.aborted?Promise.resolve({done:!0,value:void 0}):new Promise(t=>{const s=s=>{e?.removeEventListener("abort",n),t(s)},n=()=>{const e=G(this,Qs,"f").indexOf(s);e>=0&&G(this,Qs,"f").splice(e,1),t({done:!0,value:void 0})};G(this,Qs,"f").push(s),e?.addEventListener("abort",n,{once:!0})})}tryShift(){return G(this,Ys,"f").shift()}}))(),Nn=/* @__PURE__ */(()=>{class e extends Error{constructor(e){super("string"==typeof e?e:e.map(e=>"text"===e.type?e.text:`[${e.type}]`).join(" ")),this.name="ToolError",this.content=e}}return e})();function qn(e){return"name"in e?e.name:"mcp_server_name"in e?e.mcp_server_name:e.type}function Wn(e){return e instanceof Nn?e.content:`Error: ${e instanceof Error?e.message:String(e)}`}function jn(e){return"session.status_idle"===e.type&&"end_turn"===e.stop_reason?.type}var Un,Dn,Hn,zn,Fn,Bn=/* @__PURE__ */(()=>(en=/* @__PURE__ */new WeakMap,tn=/* @__PURE__ */new WeakMap,sn=/* @__PURE__ */new WeakMap,nn=/* @__PURE__ */new WeakMap,rn=/* @__PURE__ */new WeakMap,class{constructor(e,t){en.set(this,void 0),tn.set(this,void 0),sn.set(this,/* @__PURE__ */new Set),nn.set(this,!1),rn.set(this,void 0),X(this,en,e,"f"),X(this,tn,t,"f")}noteEvent(e){"user.tool_confirmation"!==e.type&&(jn(e)?this.arm():this.disarm())}block(e){G(this,sn,"f").add(e),void 0!==G(this,rn,"f")&&(X(this,nn,!0,"f"),clearTimeout(G(this,rn,"f")),X(this,rn,void 0,"f"))}unblock(e){G(this,sn,"f").delete(e),0===G(this,sn,"f").size&&G(this,nn,"f")&&this.arm()}arm(){G(this,en,"f")<=0||(G(this,sn,"f").size>0?X(this,nn,!0,"f"):(X(this,nn,!1,"f"),void 0!==G(this,rn,"f")&&clearTimeout(G(this,rn,"f")),X(this,rn,setTimeout(G(this,tn,"f"),G(this,en,"f")),"f")))}disarm(){X(this,nn,!1,"f"),void 0!==G(this,rn,"f")&&(clearTimeout(G(this,rn,"f")),X(this,rn,void 0,"f"))}}))(),Kn=/* @__PURE__ */(()=>{class e{constructor(e,t){on.add(this),an.set(this,!1),cn.set(this,void 0),ln.set(this,void 0),hn.set(this,void 0),dn.set(this,void 0),un.set(this,void 0),pn.set(this,/* @__PURE__ */new Set),fn.set(this,/* @__PURE__ */new Set),gn.set(this,/* @__PURE__ */new Map),mn.set(this,/* @__PURE__ */new Map),_n.set(this,new Ln),wn.set(this,0),yn.set(this,3e5),bn.set(this,null),vn.set(this,void 0),this.client=t.client,this.sessionId=e,this.tools=t.tools,this.maxIdleMs=t.maxIdleMs??6e4,X(this,un,rt(t.client),"f"),X(this,dn,new Map(t.tools.map(e=>[qn(e),e])),"f"),X(this,cn,new AbortController,"f"),X(this,ln,Hs(t.signal,G(this,cn,"f")),"f"),X(this,hn,t.requestOptions,"f"),X(this,vn,new Bn(this.maxIdleMs,()=>{G(this,un,"f").info("session idle after end_turn; stopping",{component:"session-tool-runner",session_id:this.sessionId,max_idle_ms:this.maxIdleMs}),G(this,cn,"f").abort()}),"f")}get signal(){return G(this,cn,"f").signal}abort(){G(this,cn,"f").abort()}_setSendRetryWindow(e){X(this,yn,e,"f")}async*[(an=/* @__PURE__ */new WeakMap,cn=/* @__PURE__ */new WeakMap,ln=/* @__PURE__ */new WeakMap,hn=/* @__PURE__ */new WeakMap,dn=/* @__PURE__ */new WeakMap,un=/* @__PURE__ */new WeakMap,pn=/* @__PURE__ */new WeakMap,fn=/* @__PURE__ */new WeakMap,gn=/* @__PURE__ */new WeakMap,mn=/* @__PURE__ */new WeakMap,_n=/* @__PURE__ */new WeakMap,wn=/* @__PURE__ */new WeakMap,yn=/* @__PURE__ */new WeakMap,bn=/* @__PURE__ */new WeakMap,vn=/* @__PURE__ */new WeakMap,on=/* @__PURE__ */new WeakSet,Symbol.asyncIterator)](){if(G(this,an,"f"))throw new C("Cannot iterate over a consumed SessionToolRunner");X(this,an,!0,"f"),G(this,un,"f").info("session tool runner starting",{component:"session-tool-runner",session_id:this.sessionId});const e=G(this,on,"m",Sn).call(this).catch(e=>{G(this,cn,"f").signal.aborted||G(this,un,"f").error("stream loop failed",{error:String(e)}),G(this,cn,"f").abort()});try{for(;;){const e=await G(this,_n,"f").next(G(this,cn,"f").signal);if(e.done)break;yield e.value}let t;for(await e;void 0!==(t=G(this,_n,"f").tryShift());)yield t}finally{G(this,cn,"f").abort(),G(this,vn,"f").disarm(),await e;try{await G(this,on,"m",Pn).call(this)}catch(t){G(this,un,"f").warn("drain failed",{error:String(t)})}G(this,_n,"f").close();for(const e of this.tools)try{await(e.close?.())}catch(t){G(this,un,"f").warn("tool.close failed",{tool:qn(e),error:String(t)})}G(this,ln,"f").call(this)}}}return kn=function(){return{...G(this,hn,"f"),headers:ss([us("session-tool-runner"),G(this,hn,"f")?.headers]),signal:G(this,cn,"f").signal}},Sn=async function(){const e=G(this,cn,"f");let t=500;for(;!e.signal.aborted;){try{const e=await this.client.beta.sessions.events.stream(this.sessionId,{},G(this,on,"m",kn).call(this));await G(this,on,"m",xn).call(this);for await(const s of e)if(t=500,await G(this,on,"m",In).call(this,s))return}catch(s){if(e.signal.throwIfAborted(),Fs(s))throw G(this,un,"f").error("permanent stream failure, shutting down",{error:String(s)}),e.abort(),s;G(this,un,"f").warn("stream disconnected, reconnecting",{error:String(s),backoff_ms:t})}e.signal.throwIfAborted(),await oe(t,e.signal),t=Math.min(2*t,1e4)}},xn=async function(){const e=G(this,cn,"f"),t=[];let s=!1;try{for await(const e of this.client.beta.sessions.events.list(this.sessionId,{limit:1e3},G(this,on,"m",kn).call(this)))G(this,on,"m",Rn).call(this,e,t),s=jn(e)}catch(i){e.signal.throwIfAborted(),G(this,un,"f").warn("reconcile list failed",{error:String(i)});for(const e of t)G(this,pn,"f").delete(e.id);return}const n=t.filter(e=>!G(this,fn,"f").has(e.id));G(this,vn,"f").disarm();for(const o of n)await G(this,on,"m",An).call(this,o);for(const o of[...G(this,mn,"f").values()]){const e=G(this,gn,"f").get(o.id);void 0!==e&&await G(this,on,"m",Tn).call(this,o,e)}const r=n.filter(e=>!G(this,fn,"f").has(e.id)&&!G(this,mn,"f").has(e.id));s&&0===r.length?G(this,vn,"f").arm():G(this,vn,"f").disarm()},Rn=function(e,t){"agent.tool_use"===e.type||"agent.custom_tool_use"===e.type?(G(this,pn,"f").add(e.id),G(this,fn,"f").has(e.id)||t.push(e)):"user.tool_result"===e.type?G(this,fn,"f").add(e.tool_use_id):"user.custom_tool_result"===e.type?G(this,fn,"f").add(e.custom_tool_use_id):"user.tool_confirmation"===e.type&&(G(this,fn,"f").has(e.tool_use_id)||G(this,gn,"f").set(e.tool_use_id,e.result))},In=async function(e){switch(G(this,vn,"f").noteEvent(e),e.type){case"agent.tool_use":case"agent.custom_tool_use":return G(this,pn,"f").has(e.id)||(G(this,pn,"f").add(e.id),await G(this,on,"m",An).call(this,e)),!1;case"user.tool_confirmation":return await G(this,on,"m",$n).call(this,e),!1;case"user.tool_result":return G(this,fn,"f").add(e.tool_use_id),!1;case"user.custom_tool_result":return G(this,fn,"f").add(e.custom_tool_use_id),!1;case"session.status_terminated":case"session.deleted":return G(this,un,"f").info("session terminated",{component:"session-tool-runner",session_id:this.sessionId}),G(this,cn,"f").abort(),!0;default:return!1}},An=async function(e){const t=e.evaluated_permission,s="deny"===t?"deny":G(this,gn,"f").get(e.id);void 0!==s?await G(this,on,"m",Tn).call(this,e,s):void 0===t||"allow"===t?await G(this,on,"m",Mn).call(this,e,void 0):G(this,mn,"f").has(e.id)||(G(this,un,"f").info("tool call awaiting confirmation; holding",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),G(this,mn,"f").set(e.id,e),G(this,vn,"f").block(e.id))},$n=async function(e){G(this,gn,"f").set(e.tool_use_id,e.result);const t=G(this,mn,"f").get(e.tool_use_id);void 0!==t&&await G(this,on,"m",Tn).call(this,t,e.result)},Tn=async function(e,t){const s=G(this,mn,"f").delete(e.id);if("allow"!==t)s&&G(this,vn,"f").unblock(e.id),G(this,fn,"f").add(e.id),G(this,un,"f").info("tool call denied; not executing",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),G(this,on,"m",En).call(this,{event:e,toolUseId:e.id,name:e.name,isError:!1,posted:!1,confirmation:"deny"});else{G(this,un,"f").info("tool call confirmed",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),s||G(this,vn,"f").block(e.id);try{await G(this,on,"m",Mn).call(this,e,"allow")}finally{G(this,vn,"f").unblock(e.id)}}},En=function(e){G(this,_n,"f").push(e)},Mn=async function(e,t){var s,n;if(!G(this,fn,"f").has(e.id)){G(this,un,"f").info("executing tool",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),X(this,wn,(s=G(this,wn,"f"),++s),"f");try{const s=G(this,dn,"f").get(e.name);if(!s)return G(this,un,"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}),void G(this,on,"m",En).call(this,{event:e,toolUseId:e.id,name:e.name,isError:!1,posted:!1,confirmation:t});let n,r;const i=new AbortController,o=Hs(G(this,cn,"f").signal,i),a=setTimeout(()=>i.abort(),12e4);try{const t=await async function(e,t,s){try{const n=e.parse?e.parse(t):t;return{content:await e.run(n,s),isError:!1}}catch(n){return{content:Wn(n),isError:!0}}}(s,e.input,{toolUse:e,toolUseBlock:e,signal:i.signal});n=t.content,r=t.isError}finally{clearTimeout(a),o()}const c=function(e,t,s){return"agent.custom_tool_use"===e.type?{type:"user.custom_tool_result",custom_tool_use_id:e.id,is_error:t,content:s}:{type:"user.tool_result",tool_use_id:e.id,is_error:t,content:s}}(e,r,function(e){if("string"==typeof e)return[{type:"text",text:e||"(no output)"}];const t=e.map(e=>"text"===e.type?{type:"text",text:e.text||"(no output)"}:"image"===e.type||"document"===e.type?e:"search_result"===e.type?{type:"search_result",source:e.source,title:e.title,content:e.content.map(e=>({type:"text",text:e.text})),citations:{enabled:e.citations?.enabled??!1}}:{type:"text",text:JSON.stringify(e)});return t.length>0?t:[{type:"text",text:"(no output)"}]}(n)),l=await G(this,on,"m",On).call(this,c,e.id);G(this,on,"m",En).call(this,{event:e,result:c,toolUseId:e.id,name:e.name,isError:r,posted:l,confirmation:t})}finally{X(this,wn,(n=G(this,wn,"f"),--n),"f"),0===G(this,wn,"f")&&G(this,bn,"f")?.call(this)}}},On=async function(e,t){const s=G(this,cn,"f"),n=Date.now();let r,i=0;for(;;){i++,s.signal.throwIfAborted();try{return await this.client.beta.sessions.events.send(this.sessionId,{events:[e]},G(this,on,"m",kn).call(this)),G(this,fn,"f").add(t),!0}catch(o){if(r=o,Fs(o))break;const e=G(this,yn,"f")-(Date.now()-n);if(e<=0)break;const a=Math.min(Js(Bs(i-1,1e3,3e4)),e);G(this,un,"f").warn("tool result send failed; retrying",{tool_use_id:t,attempt:i,backoff_ms:a,error:String(o)}),await oe(a,s.signal)}}return G(this,un,"f").error("failed to send tool result",{tool_use_id:t,attempts:i,error:String(r)}),!1},Pn=async function(){0!==G(this,wn,"f")&&(await Promise.race([new Promise(e=>X(this,bn,e,"f")),oe(3e4)]),X(this,bn,null,"f"),G(this,wn,"f")>0&&G(this,un,"f").warn("drain timeout exceeded"))},e})();var Jn=/* @__PURE__ */(()=>(Dn=/* @__PURE__ */new WeakMap,Un=/* @__PURE__ */new WeakSet,Hn=async function(e,t,s){const n=rt(this.client),r=function(e){if(!e)return null;let t;try{const s=e.replace(/-/g,"+").replace(/_/g,"/"),n=s.padEnd(4*Math.ceil(s.length/4),"=");t=JSON.parse(Ve((e=>{if(void 0!==globalThis.Buffer){const t=globalThis.Buffer.from(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}if("undefined"!=typeof atob){const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s}throw new C("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")})(n)))}catch{return null}if(null===t||"object"!=typeof t||Array.isArray(t))return null;const s=t.sessions_token;return"string"==typeof s&&""!==s?s:null}(e.secret),i=r??t;if(void 0===i)throw new C("handleItem: the work item carried a secret payload but no sessions token could be extracted, and there is no environment key to fall back to; the poller must issue a secret whose payload carries `sessions_token`, or provide the environment key (pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY)");e.secret&&null===r&&n.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 o=Vs(this.client,{authToken:i,helper:"environments-worker"}),a=e.data.id,c=new AbortController,l=Hs(s,c),h=new Xn(c),d=await(import("./node.browser-BbxzpeRq.js"));let u,p;const f=async function(e,t,s,n,r){let i=3e4,o=9e4,a=Date.now(),c="NO_HEARTBEAT";const l=async()=>{const l=new AbortController,h=Hs(s.signal,l),d=setTimeout(()=>l.abort(),i);try{const h=await e.beta.environments.work.heartbeat(t.id,{environment_id:t.environment_id,expected_last_heartbeat:c},{...r,headers:ss([r?.headers]),signal:l.signal});a=Date.now(),c=h.last_heartbeat,h.ttl_seconds>0&&(o=1e3*h.ttl_seconds,i=Math.max(1e3,Math.min(o/2,3e4)),(e=>{u=e,p?._setSendRetryWindow(e)})?.(o)),"stopping"!==h.state&&"stopped"!==h.state||(n.info("heartbeat signals shutdown",{work_id:t.id,state:h.state}),s.finish("control_plane_stop")),h.lease_extended||(n.warn("lease not extended, shutting down",{work_id:t.id}),s.finish("control_plane_stop"))}catch(f){if(s.signal.throwIfAborted(),zs(f,412)){const e=function(e){let t=e instanceof L?e.error:void 0;for(const s of["error","details","current_state"]){if(!se(t))return{};t=t[s]}return se(t)?t:{}}(f);return n.error("lease lost: heartbeat precondition failed",{work_id:t.id,server_state:e.state,server_ttl_seconds:e.ttl_seconds,server_last_heartbeat:e.last_heartbeat}),void s.finish("lease_lost")}if(Fs(f))throw n.error("permanent heartbeat failure",{work_id:t.id,error:String(f)}),s.finish("heartbeat_rejected"),f;if(Date.now()-a>o)return n.error("lease assumed lost: no successful heartbeat in ttl",{work_id:t.id,ttl_ms:o,error:String(f)}),void s.finish("assumed_lost");n.warn("transient heartbeat failure",{work_id:t.id,error:String(f)})}finally{clearTimeout(d),h()}};for(await l();!s.signal.aborted;)await oe(i,s.signal),s.signal.throwIfAborted(),await l()}(o,e,h,n,this.requestOptions).catch(t=>{c.signal.aborted||n.error("heartbeat loop failed",{work_id:e.id,error:String(t)}),c.abort()});let g,m=async()=>{},_=!1;try{if("session"!==e.data.type)return void n.debug("skipping non-session work item",{work_id:e.id,type:e.data.type});const t=await o.beta.sessions.retrieve(a);if(null===r&&null!==this.memorySyncIntervalMs&&function(e){return e.resources.some(e=>"memory_store"===e.type)}(t))throw new d.SessionMemoryError(`cannot mount the session's memories: the work item carried no sessions token (work_id=${e.id}, session_id=${a}); 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 s={workdir:this.workdir,client:o,session:t,...void 0!==this.maxFileBytes?{maxFileBytes:this.maxFileBytes}:{}};try{m=await d.setupSkills(s)}catch(w){n.warn("skill setup failed",{session_id:a,work_id:e.id,error:String(w)})}null!==r&&null!==this.memorySyncIntervalMs?(g=new d.SessionMemoryStores(o,{workdir:this.workdir,...void 0!==this.memorySyncIntervalMs?{syncIntervalMs:this.memorySyncIntervalMs}:{},syncDeletions:this.memorySyncDeletions}),await g.download(t),s.allowedRoots=g.roots,s.readOnlyRoots=g.readOnlyRoots):n.debug("memory stores disabled for this item",{work_id:e.id});const i="function"==typeof this.tools?this.tools(s):this.tools??d.betaAgentToolset20260401(s);p=new Kn(a,{client:o,tools:i,...void 0!==this.maxIdleMs?{maxIdleMs:this.maxIdleMs}:{},...void 0!==this.requestOptions?{requestOptions:this.requestOptions}:{},signal:c.signal}),void 0!==u&&p._setSendRetryWindow(u);for await(const e of p)g&&await g.syncIfDue();_=!c.signal.aborted}finally{try{await m().catch(t=>{n.warn("skill cleanup failed",{session_id:a,work_id:e.id,error:String(t)})})}finally{if(g){const t=d.MEMORY_FLUSH_TIMEOUT_MS;_&&await Vn(g.finish(),t)&&n.warn(`final memory sync cut off after ${t}ms; the flush that follows still uploads changed files`,{session_id:a,work_id:e.id});const s=new AbortController;await Vn(g.flushWrites(s.signal),t)&&(s.abort(),n.warn(`memory flush cut off after ${t}ms; changed files it had not uploaded yet are not saved`,{session_id:a,work_id:e.id})),await g.dispose().catch(t=>{n.warn("memory store cleanup failed",{session_id:a,work_id:e.id,error:String(t)})})}}h.finish("runner_done"),l(),await f,h.lost?n.info("lease lost; released without stopping it",{session_id:a,work_id:e.id}):await async function(e,t,s,n){try{await e.beta.environments.work.stop(t.id,{environment_id:t.environment_id,force:!0},{...n,headers:ss([n?.headers])})}catch(w){zs(w,409)||s.error("force-stop on exit failed",{work_id:t.id,error:String(w)})}}(o,e,n,this.requestOptions)}},class{constructor(e){if(Un.add(this),Dn.set(this,void 0),void 0!==e.unrestrictedPaths)throw new C("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,null!=e.memorySyncIntervalMs&&function(e){if(!(e>=5e3))throw new C(`memorySyncIntervalMs must be at least 5000ms (got ${e}); to run without memory sync, pass \`memorySyncIntervalMs: null\` to the worker instead`)}(e.memorySyncIntervalMs),this.memorySyncIntervalMs=e.memorySyncIntervalMs,this.memorySyncDeletions=e.memorySyncDeletions??"enabled",this.workerId=e.workerId,this.requestOptions=e.requestOptions,X(this,Dn,e.signal,"f")}async run(e){const{environmentId:t,environmentKey:s}=this;if(void 0===t||void 0===s)throw new C("EnvironmentWorker.run: environmentId and environmentKey are required to poll for work");const n=e??G(this,Dn,"f"),r=new Xs({client:this.client,environmentId:t,environmentKey:s,...void 0!==this.workerId?{workerId:this.workerId}:{},...n?{signal:n}:{},...void 0!==this.requestOptions?{requestOptions:this.requestOptions}:{},autoStop:!1});for await(const o of r)try{await G(this,Un,"m",Hn).call(this,o,s,r.signal)}catch(i){if(r.signal?.aborted)throw i;rt(this.client).error("work item failed",{work_id:o.id,error:String(i)})}}async handleItem(e){const t=e?.workId??Ke("ANTHROPIC_WORK_ID"),s=e?.environmentId??Ke("ANTHROPIC_ENVIRONMENT_ID"),n=e?.sessionId??Ke("ANTHROPIC_SESSION_ID"),r=(e?.environmentKey??this.environmentKey??Ke("ANTHROPIC_ENVIRONMENT_KEY"))||void 0,i=e?.workSecret||Ke("ANTHROPIC_WORK_SECRET")||null;if(!t)throw new C("handleItem: workId is required — pass it or set ANTHROPIC_WORK_ID");if(!s)throw new C("handleItem: environmentId is required — pass it or set ANTHROPIC_ENVIRONMENT_ID");if(!n)throw new C("handleItem: sessionId is required — pass it or set ANTHROPIC_SESSION_ID");if(!r&&!i)throw new C("handleItem: environmentKey is required when there is no work secret — pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY");const o={id:t,environment_id:s,secret:i,data:{type:"session",id:n}};await G(this,Un,"m",Hn).call(this,o,r,e?.signal??G(this,Dn,"f"))}}))();async function Vn(e,t){let s;try{return await Promise.race([e.then(()=>!1,()=>!1),new Promise(e=>{s=setTimeout(()=>e(!0),t)})])}finally{void 0!==s&&clearTimeout(s)}}var Xn=/* @__PURE__ */(()=>(zn=/* @__PURE__ */new WeakMap,Fn=/* @__PURE__ */new WeakMap,class{constructor(e){zn.set(this,void 0),Fn.set(this,void 0),X(this,zn,e,"f")}get signal(){return G(this,zn,"f").signal}finish(e){X(this,Fn,G(this,Fn,"f")??e,"f"),G(this,zn,"f").abort()}get lost(){return"lease_lost"===G(this,Fn,"f")||"assumed_lost"===G(this,Fn,"f")}}))(),Gn=/* @__PURE__ */(()=>{class e extends Gt{retrieve(e,t,s){const{environment_id:n,betas:r,workspace_id:i}=t;return this._client.get(os`/v1/environments/${n}/work/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}update(e,t,s){const{environment_id:n,betas:r,workspace_id:i,...o}=t;return this._client.post(os`/v1/environments/${n}/work/${e}?beta=true`,{body:o,...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}list(e,t={},s){const{betas:n,...r}=t??{};return this._client.getAPIList(os`/v1/environments/${e}/work?beta=true`,qt,{query:r,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}ack(e,t,s){const{environment_id:n,betas:r}=t;return this._client.post(os`/v1/environments/${n}/work/${e}/ack?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}heartbeat(e,t,s){const{environment_id:n,desired_ttl_seconds:r,expected_last_heartbeat:i,betas:o}=t;return this._client.post(os`/v1/environments/${n}/work/${e}/heartbeat?beta=true`,{query:{desired_ttl_seconds:r,expected_last_heartbeat:i},...s,headers:ss([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}poll(e,t={},s){const{betas:n,"Anthropic-Worker-ID":r,...i}=t??{};return this._client.get(os`/v1/environments/${e}/work/poll?beta=true`,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"Anthropic-Worker-ID":r}:void 0},s?.headers])})}stats(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/environments/${e}/work/stats?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}stop(e,t,s){const{environment_id:n,betas:r,workspace_id:i,...o}=t;return this._client.post(os`/v1/environments/${n}/work/${e}/stop?beta=true`,{body:o,...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}poller(e){return new Xs({...e,client:this._client})}worker(e){return new Jn({...e,client:this._client})}}return e.WorkPoller=Xs,e.EnvironmentWorker=Jn,e})(),Yn=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.work=new Gn(this._client)}create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/environments?beta=true",{body:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/environments/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}update(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/environments/${e}?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/environments?beta=true",qt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}delete(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.delete(os`/v1/environments/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}archive(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/environments/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Work=Gn,e})(),Qn=class extends Gt{create(e,t,s){const{view:n,betas:r,workspace_id:i,...o}=t;return this._client.post(os`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:n},body:o,...s,headers:ss([{"anthropic-beta":[...r??[],"agent-memory-2026-07-22"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}retrieve(e,t,s){const{memory_store_id:n,betas:r,workspace_id:i,...o}=t;return this._client.get(os`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:o,...s,headers:ss([{"anthropic-beta":[...r??[],"agent-memory-2026-07-22"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}update(e,t,s){const{memory_store_id:n,view:r,betas:i,workspace_id:o,...a}=t;return this._client.post(os`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:{view:r},body:a,...s,headers:ss([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...null!=o?{"anthropic-workspace-id":o}:void 0},s?.headers])})}list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(os`/v1/memory_stores/${e}/memories?beta=true`,qt,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"agent-memory-2026-07-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}delete(e,t,s){const{memory_store_id:n,expected_content_sha256:r,betas:i,workspace_id:o}=t;return this._client.delete(os`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:{expected_content_sha256:r},...s,headers:ss([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...null!=o?{"anthropic-workspace-id":o}:void 0},s?.headers])})}},Zn=class extends Gt{retrieve(e,t,s){const{memory_store_id:n,betas:r,workspace_id:i,...o}=t;return this._client.get(os`/v1/memory_stores/${n}/memory_versions/${e}?beta=true`,{query:o,...s,headers:ss([{"anthropic-beta":[...r??[],"agent-memory-2026-07-22"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(os`/v1/memory_stores/${e}/memory_versions?beta=true`,qt,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"agent-memory-2026-07-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}redact(e,t,s){const{memory_store_id:n,betas:r,workspace_id:i}=t;return this._client.post(os`/v1/memory_stores/${n}/memory_versions/${e}/redact?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"agent-memory-2026-07-22"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}},er=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.memories=new Qn(this._client),this.memoryVersions=new Zn(this._client)}create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/memory_stores?beta=true",{body:r,...t,headers:ss([{"anthropic-beta":[...s??[],"agent-memory-2026-07-22"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/memory_stores/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"agent-memory-2026-07-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}update(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/memory_stores/${e}?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"agent-memory-2026-07-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/memory_stores?beta=true",qt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"agent-memory-2026-07-22"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}delete(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.delete(os`/v1/memory_stores/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"agent-memory-2026-07-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}archive(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/memory_stores/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"agent-memory-2026-07-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Memories=Qn,e.MemoryVersions=Zn,e})(),tr=/* @__PURE__ */(()=>{class e{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new bt;for await(const t of this.iterator)for(const s of e.decode(t))yield JSON.parse(s);for(const t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(t,s){if(!t.body){if(s.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new C("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new C("Attempted to iterate over a response with no body")}return new e(me(t.body),s)}}return e})(),sr=class extends Gt{create(e,t){const{betas:s,user_profile_id:n,workspace_id:r,...i}=e;return this._client.post("/v1/messages/batches?beta=true",{body:i,...t,headers:ss([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...null!=n?{"anthropic-user-profile-id":n}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/messages/batches/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",Nt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}delete(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.delete(os`/v1/messages/batches/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}cancel(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/messages/batches/${e}/cancel?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}async results(e,t={},s){const n=await this.retrieve(e,t,s);if(!n.results_url)throw new C(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);const{betas:r,workspace_id:i}=t??{};return this._client.get(n.results_url,{...s,headers:ss([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>tr.fromResponse(t.response,t.controller))}},nr={"claude-opus-4@20250514":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function rr(e){return e?.output_format??e?.output_config?.format}function ir(e,t,s){const n=rr(t);return t&&"parse"in(n??{})?or(e,t,s):{...e,content:e.content.map(e=>{if("text"===e.type){const t=Object.defineProperty({...e},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(t,"parsed",{get:()=>(s.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null),enumerable:!1})}return e}),parsed_output:null}}function or(e,t,s){let n=null;const r=e.content.map(e=>{if("text"===e.type){const r=function(e,t){const s=rr(e);if("json_schema"!==s?.type)return null;try{return"parse"in s?s.parse(t):JSON.parse(t)}catch(n){throw new C(`Failed to parse structured output: ${n}`)}}(t,e.text);null===n&&(n=r);const i=Object.defineProperty({...e},"parsed_output",{value:r,enumerable:!1});return Object.defineProperty(i,"parsed",{get:()=>(s.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),r),enumerable:!1})}return e});return{...e,content:r,parsed_output:n}}var ar,cr,lr,hr,dr,ur,pr,fr,gr,mr,_r,wr,yr,br,vr,kr,Sr,xr,Rr,Ir,Ar,$r,Tr,Er,Mr,Or,Pr="__json_buf";function Cr(e,t){const s={};for(const i of Object.keys(e))"input"!==i&&(s[i]=e[i]);let n;Object.defineProperty(s,Pr,{value:t,enumerable:!1,writable:!0});let r=!1;return Object.defineProperty(s,"input",{enumerable:!0,configurable:!0,get:()=>(r||(n=t?(e=>JSON.parse((e=>{let t="";return e.map(e=>{"string"===e.type?t+='"'+e.value+'"':t+=e.value}),t})((e=>{let t=[];return e.map(e=>{"brace"===e.type&&("{"===e.value?t.push("}"):t.splice(t.lastIndexOf("}"),1)),"paren"===e.type&&("["===e.value?t.push("]"):t.splice(t.lastIndexOf("]"),1))}),t.length>0&&t.reverse().map(t=>{"}"===t?e.push({type:"brace",value:"}"}):"]"===t&&e.push({type:"paren",value:"]"})}),e})((e=>{let t=[];for(const i of e)"brace"!==i.type&&"paren"!==i.type||("{"===i.value||"["===i.value?t.push(i.value):t.pop());let s=t[t.length-1],n=e.length,r=/^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?$/;for(;n>0;){let t=e[n-1];switch(t.type){case"separator":n--;continue;case"number":if(t.unterminated||!r.test(t.value)){n--;continue}break;case"string":let i=e[n-2];if("{"===s&&("delimiter"===i?.type||"brace"===i?.type&&"{"===i.value)){n--;continue}break;case"delimiter":n--}break}return e.slice(0,n)})((e=>{let t=0,s=[];for(;t<e.length;){let n=e[t];if("\\"===n){t++;continue}if("{"===n){s.push({type:"brace",value:"{"}),t++;continue}if("}"===n){s.push({type:"brace",value:"}"}),t++;continue}if("["===n){s.push({type:"paren",value:"["}),t++;continue}if("]"===n){s.push({type:"paren",value:"]"}),t++;continue}if(":"===n){s.push({type:"separator",value:":"}),t++;continue}if(","===n){s.push({type:"delimiter",value:","}),t++;continue}if('"'===n){const n=t+1;let r=n,i=!1;for(;;){if(r=e.indexOf('"',r),-1===r){i=!0;break}let t=0,s=r-1;for(;s>=n&&"\\"===e[s];)t++,s--;if(t%2==0)break;r++}i?t=e.length:(s.push({type:"string",value:e.slice(n,r)}),t=r+1);continue}if(n&&/\s/.test(n)){t++;continue}let r=/[0-9]/;if(n&&r.test(n)||"-"===n||"."===n){let i="";for("-"===n&&(i+=n,n=e[++t]);n&&(r.test(n)||"."===n||"e"===n||"E"===n||("-"===n||"+"===n)&&("e"===i[i.length-1]||"E"===i[i.length-1]));)i+=n,n=e[++t];s.push({type:"number",value:i,unterminated:t===e.length});continue}let i=/[a-z]/i;if(n&&i.test(n)){let r="";for(;n&&i.test(n)&&t!==e.length;)r+=n,n=e[++t];if("true"!=r&&"false"!=r&&"null"!==r){t++;continue}s.push({type:"name",value:r});continue}t++}return s})(e))))))(t):{},r=!0),n)}),s}function Lr(e){return"tool_use"===e.type||"server_tool_use"===e.type||"mcp_tool_use"===e.type}var Nr,qr,Wr,jr,Ur,Dr,Hr,zr,Fr,Br,Kr,Jr,Vr,Xr,Gr,Yr,Qr,Zr,ei,ti,si,ni,ri,ii,oi,ai,ci,li,hi,di,ui,pi,fi,gi,mi,_i,wi,yi=/* @__PURE__ */(()=>{class e{constructor(e,t){ar.add(this),this.messages=[],this.receivedMessages=[],cr.set(this,void 0),lr.set(this,null),this.controller=new AbortController,hr.set(this,void 0),dr.set(this,()=>{}),ur.set(this,()=>{}),pr.set(this,void 0),fr.set(this,()=>{}),gr.set(this,()=>{}),mr.set(this,{}),_r.set(this,!1),wr.set(this,!1),yr.set(this,!1),br.set(this,!1),vr.set(this,void 0),kr.set(this,void 0),Sr.set(this,void 0),xr.set(this,void 0),Ar.set(this,e=>{if(X(this,wr,!0,"f"),O(e)&&(e=new N),e instanceof N)return X(this,yr,!0,"f"),this._emit("abort",e);if(e instanceof C)return this._emit("error",e);if(e instanceof Error){const t=new C(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new C(String(e)))}),X(this,hr,new Promise((e,t)=>{X(this,dr,e,"f"),X(this,ur,t,"f")}),"f"),X(this,pr,new Promise((e,t)=>{X(this,fr,e,"f"),X(this,gr,t,"f")}),"f"),G(this,hr,"f").catch(()=>{}),G(this,pr,"f").catch(()=>{}),X(this,lr,e,"f"),X(this,xr,t?.logger??console,"f")}get response(){return G(this,vr,"f")}get request_id(){return G(this,kr,"f")}get workspace_id(){return G(this,Sr,"f")}async withResponse(){X(this,br,!0,"f");const e=await G(this,hr,"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(t){const s=new e(null);return s._run(()=>s._fromReadableStream(t)),s}static createMessage(t,s,n,{logger:r}={}){const i=new e(s,{logger:r});for(const e of s.messages)i._addMessageParam(e);return X(i,lr,{...s,stream:!0},"f"),i._run(()=>i._createMessage(t,{...s,stream:!0},{...n,headers:{...n?.headers,[ds]:"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},G(this,Ar,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,s){const n=s?.signal;let r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener("abort",r));try{G(this,ar,"m",$r).call(this);const{response:n,data:r}=await e.create({...t,stream:!0},{...s,signal:this.controller.signal}).withResponse();this._connected(n);for await(const e of r)G(this,ar,"m",Tr).call(this,e);if(r.controller.signal?.aborted)throw new N;G(this,ar,"m",Er).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}_connected(e){this.ended||(X(this,vr,e,"f"),X(this,kr,e?.headers.get("request-id"),"f"),X(this,Sr,e?.headers.get("anthropic-workspace-id"),"f"),G(this,dr,"f").call(this,e),this._emit("connect"))}get ended(){return G(this,_r,"f")}get errored(){return G(this,wr,"f")}get aborted(){return G(this,yr,"f")}abort(){this.controller.abort()}on(e,t){return(G(this,mr,"f")[e]||(G(this,mr,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=G(this,mr,"f")[e];if(!s)return this;const n=s.findIndex(e=>e.listener===t);return n>=0&&s.splice(n,1),this}once(e,t){return(G(this,mr,"f")[e]||(G(this,mr,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{X(this,br,!0,"f"),"error"!==e&&this.once("error",s),this.once(e,t)})}async done(){X(this,br,!0,"f"),await G(this,pr,"f")}get currentMessage(){return G(this,cr,"f")}async finalMessage(){return await this.done(),G(this,ar,"m",Rr).call(this)}async finalText(){return await this.done(),G(this,ar,"m",Ir).call(this)}_emit(e,...t){if(G(this,_r,"f"))return;"end"===e&&(X(this,_r,!0,"f"),G(this,fr,"f").call(this));const s=G(this,mr,"f")[e];if(s&&(G(this,mr,"f")[e]=s.filter(e=>!e.once),s.forEach(({listener:e})=>e(...t))),"abort"===e){const e=t[0];return G(this,br,"f")||s?.length||Promise.reject(e),G(this,ur,"f").call(this,e),G(this,gr,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];G(this,br,"f")||s?.length||Promise.reject(e),G(this,ur,"f").call(this,e),G(this,gr,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",G(this,ar,"m",Rr).call(this))}async _fromReadableStream(e,t){const s=t?.signal;let n;s&&(s.aborted&&this.controller.abort(),n=this.controller.abort.bind(this.controller),s.addEventListener("abort",n));try{G(this,ar,"m",$r).call(this),this._connected(null);const t=kt.fromReadableStream(e,this.controller);for await(const e of t)G(this,ar,"m",Tr).call(this,e);if(t.controller.signal?.aborted)throw new N;G(this,ar,"m",Er).call(this)}finally{s&&n&&s.removeEventListener("abort",n)}}[(cr=/* @__PURE__ */new WeakMap,lr=/* @__PURE__ */new WeakMap,hr=/* @__PURE__ */new WeakMap,dr=/* @__PURE__ */new WeakMap,ur=/* @__PURE__ */new WeakMap,pr=/* @__PURE__ */new WeakMap,fr=/* @__PURE__ */new WeakMap,gr=/* @__PURE__ */new WeakMap,mr=/* @__PURE__ */new WeakMap,_r=/* @__PURE__ */new WeakMap,wr=/* @__PURE__ */new WeakMap,yr=/* @__PURE__ */new WeakMap,br=/* @__PURE__ */new WeakMap,vr=/* @__PURE__ */new WeakMap,kr=/* @__PURE__ */new WeakMap,Sr=/* @__PURE__ */new WeakMap,xr=/* @__PURE__ */new WeakMap,Ar=/* @__PURE__ */new WeakMap,ar=/* @__PURE__ */new WeakSet,Rr=function(){if(0===this.receivedMessages.length)throw new C("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Ir=function(){if(0===this.receivedMessages.length)throw new C("stream ended without producing a Message with role=assistant");const e=this.receivedMessages.at(-1).content.filter(e=>"text"===e.type).map(e=>e.text);if(0===e.length)throw new C("stream ended without producing a content block with type=text");return e.join(" ")},$r=function(){this.ended||X(this,cr,void 0,"f")},Tr=function(e){if(this.ended)return;const t=G(this,ar,"m",Mr).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{const n=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===n.type&&this._emit("text",e.delta.text,n.text||"");break;case"citations_delta":"text"===n.type&&this._emit("citation",e.delta.citation,n.citations??[]);break;case"input_json_delta":if(Lr(n)&&G(this,mr,"f").inputJson?.length){let t;try{t=n.input}catch(s){G(this,Ar,"f").call(this,G(this,ar,"m",Or).call(this,n,s));break}this._emit("inputJson",e.delta.partial_json,t)}break;case"thinking_delta":"thinking"===n.type&&this._emit("thinking",e.delta.thinking,n.thinking);break;case"signature_delta":"thinking"===n.type&&this._emit("signature",n.signature);break;case"compaction_delta":"compaction"===n.type&&n.content&&this._emit("compaction",n.content);break;default:/* @__PURE__ */e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(ir(t,G(this,lr,"f"),{logger:G(this,xr,"f")}),!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":X(this,cr,t,"f")}},Er=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");const e=G(this,cr,"f");if(!e)throw new C("request ended without sending any chunks");return X(this,cr,void 0,"f"),ir(e,G(this,lr,"f"),{logger:G(this,xr,"f")})},Mr=function(e){let t=G(this,cr,"f");if("message_start"===e.type){if(t)throw new C(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new C(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.stop_details=e.delta.stop_details,t.usage.output_tokens=e.usage.output_tokens,null!=e.delta.container&&(t.container=e.delta.container),null!=e.context_management&&(t.context_management=e.context_management),null!=e.input_transformations&&(t.input_transformations=e.input_transformations),null!=e.usage.input_tokens&&(t.usage.input_tokens=e.usage.input_tokens),null!=e.usage.cache_creation_input_tokens&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),null!=e.usage.cache_read_input_tokens&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),null!=e.usage.server_tool_use&&(t.usage.server_tool_use=e.usage.server_tool_use),null!=e.usage.iterations&&(t.usage.iterations=e.usage.iterations),null!=e.usage.fallback_credit&&(t.usage.fallback_credit=e.usage.fallback_credit),null!=e.usage.output_tokens_details&&(t.usage.output_tokens_details=e.usage.output_tokens_details),t;case"content_block_start":return t.content.push(e.content_block),"fallback"===e.content_block.type&&(t.model=e.content_block.to.model),t;case"content_block_delta":{const s=t.content.at(e.index);switch(e.delta.type){case"text_delta":"text"===s?.type&&(t.content[e.index]={...s,text:(s.text||"")+e.delta.text});break;case"citations_delta":"text"===s?.type&&(t.content[e.index]={...s,citations:[...s.citations??[],e.delta.citation]});break;case"input_json_delta":if(s&&Lr(s)){const n=(s.__json_buf||"")+e.delta.partial_json;t.content[e.index]=Cr(s,n)}break;case"thinking_delta":"thinking"===s?.type&&(t.content[e.index]={...s,thinking:s.thinking+e.delta.thinking});break;case"signature_delta":"thinking"===s?.type&&(t.content[e.index]={...s,signature:e.delta.signature});break;case"compaction_delta":if("compaction"===s?.type){const n={...s,content:e.delta.content};"encrypted_content"in e.delta&&(n.encrypted_content=e.delta.encrypted_content),t.content[e.index]=n}break;default:/* @__PURE__ */e.delta}return t}case"content_block_stop":{const n=t.content.at(e.index);if(n&&Lr(n)&&"__json_buf"in n){let e;try{e=n.input}catch(s){e={},G(this,Ar,"f").call(this,G(this,ar,"m",Or).call(this,n,s))}Object.defineProperty(n,"input",{value:e,enumerable:!0,configurable:!0,writable:!0})}return t}}},Or=function(e,t){const s=e[Pr];return new C(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${t}. JSON: ${s}`)},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("streamEvent",s=>{const n=t.shift();n?n.resolve(s):e.push(s)}),this.on("end",()=>{s=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{s=!0;for(const s of t)s.reject(e);t.length=0}),this.on("error",e=>{s=!0;for(const s of t)s.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((e,s)=>t.push({resolve:e,reject:s})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new kt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}return e})(),bi=/* @__PURE__ */(()=>{class e extends yi{constructor(e,t){super(e),Nr.add(this),qr.set(this,void 0),Wr.set(this,0),jr.set(this,[]),Ur.set(this,[]),Dr.set(this,void 0),Hr.set(this,[]),zr.set(this,!1),X(this,qr,t,"f")}get toolCalls(){return G(this,Ur,"f")}static start(t,s,n,r){const i=new e({...s,stream:!0},r);for(const e of s.messages)i._addMessageParam(e);return i._run(()=>i._createMessage(t,{...s,stream:!0},{...n,headers:{...n?.headers,[ds]:"stream"}})),i}_emit(e,...t){var s;if("streamEvent"!==e||this.ended)return void super._emit(e,...t);X(this,Wr,(s=G(this,Wr,"f"),++s),"f");const[n,r]=t,i="content_block_stop"===n.type?r.content[n.index]:void 0,o="tool_use"===i?.type?i:void 0;o&&G(this,Ur,"f").push(o),super._emit(e,...t),G(this,Nr,"m",Fr).call(this,n,o),G(this,Nr,"m",Br).call(this)}[(qr=/* @__PURE__ */new WeakMap,Wr=/* @__PURE__ */new WeakMap,jr=/* @__PURE__ */new WeakMap,Ur=/* @__PURE__ */new WeakMap,Dr=/* @__PURE__ */new WeakMap,Hr=/* @__PURE__ */new WeakMap,zr=/* @__PURE__ */new WeakMap,Nr=/* @__PURE__ */new WeakSet,Symbol.asyncIterator)](){const e=super[Symbol.asyncIterator](),t={handled:G(this,Wr,"f")};G(this,jr,"f").push(t);let s=!1;return{next:async()=>{s&&(s=!1,t.handled++,G(this,Nr,"m",Br).call(this));try{const n=await e.next();return s=!n.done,n.done&&G(this,Nr,"m",Kr).call(this,t),n}catch(n){throw G(this,Nr,"m",Kr).call(this,t),n}},return:async()=>{const s=e.return?.();return G(this,Nr,"m",Kr).call(this,t),await s??{value:void 0,done:!0}}}}}return Fr=function(e,t){if(G(this,zr,"f"))return;if("content_block_start"===e.type&&"fallback"===e.content_block.type)return X(this,zr,!0,"f"),void X(this,Dr,void 0,"f");const s="content_block_start"===e.type||"message_delta"===e.type&&"tool_use"===e.delta.stop_reason;G(this,Dr,"f")&&s&&(G(this,Hr,"f").push({toolUse:G(this,Dr,"f"),event:G(this,Wr,"f")}),X(this,Dr,void 0,"f")),t&&X(this,Dr,t,"f")},Br=function(){if(this.errored||this.controller.signal.aborted)return;const e=Math.min(G(this,Wr,"f"),...G(this,jr,"f").map(e=>e.handled));for(;G(this,Hr,"f")[0]&&G(this,Hr,"f")[0].event<=e;)G(this,qr,"f").call(this,G(this,Hr,"f").shift().toolUse)},Kr=function(e){const t=G(this,jr,"f").indexOf(e);t>=0&&(G(this,jr,"f").splice(t,1),G(this,Nr,"m",Br).call(this))},e})();function vi(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}var ki=/* @__PURE__ */(()=>{class e{constructor(e,t,s){Jr.add(this),this.client=e,Vr.set(this,!1),Xr.set(this,!1),Gr.set(this,void 0),Yr.set(this,void 0),Qr.set(this,void 0),Zr.set(this,void 0),ei.set(this,void 0),ti.set(this,void 0),si.set(this,0),ni.set(this,{status:"idle"}),ri.set(this,void 0),ii.set(this,null),oi.set(this,/* @__PURE__ */new Map),ai.set(this,[]),Si(t),function(e){if("compactionControl"in e&&null!=e.compactionControl)throw new C("`compactionControl` has been removed from the tool runner. Use server-side compaction instead: call `runner.compactBeforeNextTurn()` when the conversation should be compacted.")}(t),xi(t),X(this,Gr,{params:{...t,messages:JSON.parse(JSON.stringify(t.messages))}},"f");const n=gs(t.tools,t.messages);X(this,Yr,{...s,headers:ss([us("BetaToolRunner"),n.length?{[hs]:n.join(", ")}:void 0,s?.headers])},"f"),X(this,ti,vi(),"f")}async*[(Vr=/* @__PURE__ */new WeakMap,Xr=/* @__PURE__ */new WeakMap,Gr=/* @__PURE__ */new WeakMap,Yr=/* @__PURE__ */new WeakMap,Qr=/* @__PURE__ */new WeakMap,Zr=/* @__PURE__ */new WeakMap,ei=/* @__PURE__ */new WeakMap,ti=/* @__PURE__ */new WeakMap,si=/* @__PURE__ */new WeakMap,ni=/* @__PURE__ */new WeakMap,ri=/* @__PURE__ */new WeakMap,ii=/* @__PURE__ */new WeakMap,oi=/* @__PURE__ */new WeakMap,ai=/* @__PURE__ */new WeakMap,Jr=/* @__PURE__ */new WeakSet,Symbol.asyncIterator)](){var e;if(G(this,Vr,"f"))throw new C("Cannot iterate over a consumed stream");X(this,Vr,!0,"f"),X(this,Xr,!0,"f"),X(this,ei,void 0,"f");try{for(;;)try{if(G(this,Gr,"f").params.max_iterations&&G(this,si,"f")>=G(this,Gr,"f").params.max_iterations)break;if(G(this,Jr,"m",_i).call(this),"scheduled"===G(this,ni,"f").status&&"resume"!==Ti(G(this,ii,"f"))){yield*G(this,Jr,"m",di).call(this,G(this,ni,"f").config);continue}X(this,Xr,!1,"f"),X(this,ei,void 0,"f"),X(this,si,(e=G(this,si,"f"),++e),"f"),X(this,Qr,void 0,"f");const{max_iterations:t,runToolsEagerly:s,...n}=G(this,Gr,"f").params;if(yield*G(this,Jr,"m",ci).call(this,n),G(this,Xr,"f"))X(this,ii,null,"f");else{const e=await G(this,Qr,"f"),t=Ti(e.stop_reason);X(this,ii,e.stop_reason,"f"),G(this,Gr,"f").params.messages.push({role:e.role,content:Ai(e.content)});const{container:s}=G(this,Gr,"f").params;if(e.container&&(null==s?G(this,Gr,"f").params.container=e.container.id:"object"==typeof s&&null==s.id&&(G(this,Gr,"f").params.container={...s,id:e.container.id})),"stop"===t){yield*G(this,Jr,"m",gi).call(this);break}if("resume"===t)continue}const r=await G(this,Jr,"m",mi).call(this,G(this,Gr,"f").params.messages.at(-1));if(r)G(this,Gr,"f").params.messages.push(r);else if(!G(this,Xr,"f")){yield*G(this,Jr,"m",gi).call(this);break}}finally{G(this,Zr,"f")?.abort(),X(this,Zr,void 0,"f")}if(await G(this,Jr,"m",hi).call(this),!G(this,Qr,"f"))throw new C("ToolRunner concluded without a message from the server");G(this,ti,"f").resolve(await G(this,Qr,"f"))}catch(t){throw X(this,Vr,!1,"f"),G(this,ti,"f").promise.catch(()=>{}),G(this,ti,"f").reject(t),X(this,ti,vi(),"f"),t}}setMessagesParams(e){const t="function"==typeof e?e(G(this,Gr,"f").params):e;if(Si(t),xi(t),"idle"!==G(this,ni,"f").status&&Ri(t),"in_flight"===G(this,ni,"f").status&&t.messages!==G(this,Gr,"f").params.messages)throw new C("Message params can't be changed while the conversation is being compacted, because the compaction response is about to replace them. Change them after this iteration instead.");G(this,Gr,"f").params=t,X(this,Xr,!0,"f"),X(this,ei,void 0,"f")}setRequestOptions(e){X(this,Yr,"function"==typeof e?e(G(this,Yr,"f")):{...G(this,Yr,"f"),...e},"f")}async generateToolResponse(e=G(this,Yr,"f").signal){const t=await G(this,Qr,"f")??this.params.messages.at(-1);return t?G(this,Jr,"m",mi).call(this,t,e):null}deferToolCall(e){const t="string"==typeof e?e:e.id;G(this,ri,"f")&&!G(this,ri,"f").has(t)&&G(this,ri,"f").set(t,{status:"held"})}get deferredToolCalls(){const e=G(this,Zr,"f"),t=G(this,ri,"f");return e instanceof bi&&t?e.toolCalls.filter(e=>"held"===t.get(e.id)?.status):[]}done(){return G(this,ti,"f").promise}async runUntilDone(){if(!G(this,Vr,"f"))for await(const e of this);return this.done()}get params(){return G(this,Gr,"f").params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}compactBeforeNextTurn(e){"in_flight"!==G(this,ni,"f").status&&(Ri(G(this,Gr,"f").params),X(this,ni,{status:"scheduled",config:e??{type:"summarize"}},"f"))}addTools(...e){for(const t of e)"name"in t&&G(this,oi,"f").set(t.name,"run"in t?t:null),G(this,ai,"f").push({type:"addition",tool:t})}removeTools(...e){for(const t of e){const e="string"==typeof t?t:t.name;G(this,oi,"f").set(e,null),G(this,ai,"f").push({type:"removal",name:e})}}then(e,t){return this.runUntilDone().then(e,t)}}return ci=async function*(e){await G(this,Jr,"m",hi).call(this),X(this,ri,void 0,"f"),e.stream?(X(this,Zr,G(this,Gr,"f").params.runToolsEagerly?G(this,Jr,"m",li).call(this,e):this.client.beta.messages.stream({...e},G(this,Yr,"f")),"f"),X(this,Qr,G(this,Zr,"f").finalMessage(),"f"),G(this,Qr,"f").catch(()=>{}),yield G(this,Zr,"f")):(X(this,Qr,this.client.beta.messages.create({...e,stream:!1},G(this,Yr,"f")),"f"),yield G(this,Qr,"f"))},li=function(e){const t=/* @__PURE__ */new Map;return X(this,ri,t,"f"),bi.start(this.client.beta.messages,e,G(this,Yr,"f"),e=>{if(t.has(e.id))return;const s=Ii(G(this,Jr,"m",ui).call(this),G(this,Jr,"m",pi).call(this),e,G(this,Yr,"f"));s.catch(()=>{}),t.set(e.id,{status:"started",result:s})})},hi=async function(){const e=[...G(this,ri,"f")?.values()??[]].filter(e=>"started"===e.status);await Promise.allSettled(e.map(e=>e.result))},di=async function*(e){Ri(G(this,Gr,"f").params);const{max_iterations:t,runToolsEagerly:s,...n}=G(this,Gr,"f").params,r=function(e){const{context_management:t,stop_sequences:s,output_format:n,...r}=e,i=({format:e,...t})=>t;return"any"!==r.tool_choice?.type&&"tool"!==r.tool_choice?.type||delete r.tool_choice,r.output_config&&(r.output_config=i(r.output_config)),Array.isArray(r.fallbacks)&&(r.fallbacks=r.fallbacks.map(e=>e.output_config?{...e,output_config:i(e.output_config)}:e)),r}(n);X(this,ni,{status:"in_flight"},"f"),X(this,ei,void 0,"f");const i=G(this,Qr,"f");try{yield*G(this,Jr,"m",ci).call(this,{...r,compaction:e});const t=await G(this,Qr,"f");t.content.some(e=>"compaction"===e.type&&e.content)?(G(this,Jr,"m",fi).call(this),G(this,Gr,"f").params.messages=[{role:t.role,content:t.content}]):(rt(this.client).warn("Compaction produced no summary; keeping the conversation as it is."),X(this,Qr,i,"f"))}finally{X(this,ni,{status:"idle"},"f")}},ui=function(){const e=/* @__PURE__ */new Map;for(const t of G(this,Gr,"f").params.tools)"run"in t&&e.set(t.name,t);for(const[t,s]of G(this,oi,"f"))s?e.set(t,s):e.delete(t);return e},pi=function(){const e=new Set(G(this,Jr,"m",ui).call(this).keys());for(const t of[...G(this,Gr,"f").params.messages,G(this,Jr,"m",wi).call(this)])if("string"!=typeof t.content)for(const s of t.content)if("system"===t.role)$i(s,e);else if("assistant"===t.role&&"compaction"===s.type)for(const t of s.tool_changes??[])$i(t,e);return e},fi=function(){const e=G(this,Jr,"m",pi).call(this);for(const t of G(this,Jr,"m",ui).call(this).keys())e.has(t)||G(this,oi,"f").set(t,null)},gi=async function*(){if("scheduled"!==G(this,ni,"f").status)return;const e=G(this,Gr,"f").params.messages.at(-1)?.content;if(Array.isArray(e)&&e.some(e=>"tool_use"===e.type))return rt(this.client).warn("The pending compaction was skipped because the last turn ended with tool calls that were not run. Call `compactBeforeNextTurn()` again if you continue the conversation."),void X(this,ni,{status:"idle"},"f");yield*G(this,Jr,"m",di).call(this,G(this,ni,"f").config)},mi=async function(e,t=G(this,Yr,"f").signal){return void 0!==G(this,ei,"f")||X(this,ei,async function(e,t,s,n,r){if(!s||"assistant"!==s.role||!s.content||"string"==typeof s.content)return null;const i=s.content.filter(e=>"tool_use"===e.type);return 0===i.length?null:{role:"user",content:await Promise.all(i.map(s=>{const i=r?.get(s.id);if("started"===i?.status)return i.result;const o=Ii(e,t,s,n);return r?.set(s.id,{status:"started",result:o}),o}))}}(G(this,Jr,"m",ui).call(this),G(this,Jr,"m",pi).call(this),e,{...G(this,Yr,"f"),signal:t},G(this,ri,"f")),"f"),G(this,ei,"f")},_i=function(){"pause_turn"!==G(this,ii,"f")&&0!==G(this,ai,"f").length&&(G(this,Gr,"f").params.messages.push(G(this,Jr,"m",wi).call(this)),X(this,ai,[],"f"))},wi=function(){const e=[];for(const t of G(this,ai,"f")){if("removal"===t.type){e.push({type:"tool_removal",tool:{type:"tool_reference",name:t.name}});continue}let s=t.tool;if("run"in t.tool){const{run:e,parse:n,close:r,...i}=t.tool;s=i}e.push({type:"tool_addition",tool:{type:"tool_definition",definition:s}})}return{role:"system",content:e}},e})();function Si(e){if("compaction"in e&&null!=e.compaction)throw new C("`compaction` cannot be set on a tool runner: every request in the loop would compact again. Call `runner.compactBeforeNextTurn()` when the conversation should be compacted instead.")}function xi(e){if(e.runToolsEagerly&&!e.stream)throw new TypeError("`runToolsEagerly: true` needs `stream: true` in the tool runner's params, because a reply that isn't streamed arrives whole.")}function Ri(e){if(e.context_management?.edits?.some(e=>e.type.startsWith("compact_")))throw new C("`compactBeforeNextTurn()` can't be used while `context_management` has a compaction edit, because the API doesn't accept a compaction block together with one. Remove the edit first.")}async function Ii(e,t,s,n){const r=t.has(s.name)?e.get(s.name):void 0;if(!r)return function(e){return{type:"tool_result",tool_use_id:e.id,content:`Error: Tool '${e.name}' not found`,is_error:!0}}(s);try{let e=s.input;"parse"in r&&r.parse&&(e=r.parse(e));const t=await r.run(e,{toolUse:s,toolUseBlock:s,signal:n?.signal});return{type:"tool_result",tool_use_id:s.id,content:t}}catch(i){return{type:"tool_result",tool_use_id:s.id,content:i instanceof Nn?i.content:`Error: ${i instanceof Error?i.message:String(i)}`,is_error:!0}}}function Ai(e){return e}function $i(e,t){switch(e.type){case"tool_removal":case"tool_addition":!function(e,t){const s=function(e){switch(e.type){case"tool_reference":return e.name;case"tool_definition":return"name"in e.definition?e.definition.name:void 0;default:return}}(e.tool);void 0!==s&&("tool_removal"===e.type?t.delete(s):t.add(s))}(e,t)}}function Ti(e){if(null===e)return"stop";switch(e){case"tool_use":return"run_tools";case"pause_turn":case"compaction":return"resume";default:return"stop"}}var Ei=["claude-mythos-preview","claude-opus-4-6"],Mi=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.batches=new sr(this._client)}create(e,t){const s=Oi(e),{betas:n,user_profile_id:r,workspace_id:i,...o}=s;o.model,Ei.includes(o.model)&&o.thinking&&o.thinking.type;let a=t?.timeout??this._client._options.timeout;if(!o.stream&&null==a){const e=nr[o.model]??void 0;a=this._client.calculateNonstreamingTimeout(o.max_tokens,e)}const c=ms(o.tools,o.messages);return this._client.post("/v1/messages?beta=true",{body:o,timeout:a??6e5,...t,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-user-profile-id":r}:void 0,...null!=i?{"anthropic-workspace-id":i}:void 0},c,t?.headers]),stream:s.stream??!1})}parse(e,t){return t={...t,headers:ss([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},t?.headers])},this.create(e,t).then(t=>or(t,e,{logger:this._client.logger??console}))}stream(e,t){return yi.createMessage(this,e,t)}countTokens(e,t){const{betas:s,user_profile_id:n,workspace_id:r,...i}=Oi(e);return this._client.post("/v1/messages/count_tokens?beta=true",{body:i,...t,headers:ss([{"anthropic-beta":[...s??[],"token-counting-2024-11-01"].toString(),...null!=n?{"anthropic-user-profile-id":n}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},t?.headers])})}toolRunner(e,t){return new ki(this._client,e,t)}}return e.Batches=sr,e.BetaToolRunner=ki,e.ToolError=Nn,e})();function Oi(e){if(!e.output_format)return e;if(e.output_config?.format)throw new C("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");const{output_format:t,...s}=e;return{...s,output_config:{...e.output_config,format:t}}}var Pi,Ci,Li,Ni,qi,Wi,ji,Ui,Di,Hi,zi,Fi,Bi,Ki,Ji,Vi,Xi,Gi,Yi,Qi,Zi,eo,to,so,no,ro=class extends Gt{retrieve(e,t){return this._client.get(os`/v1/organizations/api_keys/${e}?beta=true`,t)}update(e,t,s){return this._client.post(os`/v1/organizations/api_keys/${e}?beta=true`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/api_keys?beta=true",Nt,{query:e,...t})}},io=class extends Gt{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})}},oo=class extends Gt{create(e,t){return this._client.post("/v1/organizations/external_keys?beta=true",{body:e,...t})}retrieve(e,t){return this._client.get(os`/v1/organizations/external_keys/${e}?beta=true`,t)}update(e,t,s){return this._client.post(os`/v1/organizations/external_keys/${e}?beta=true`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/external_keys?beta=true",qt,{query:e,...t})}delete(e,t){return this._client.delete(os`/v1/organizations/external_keys/${e}?beta=true`,t)}validate(e,t){return this._client.post(os`/v1/organizations/external_keys/${e}/validate?beta=true`,t)}},ao=class extends Gt{create(e,t){return this._client.post("/v1/organizations/invites?beta=true",{body:e,...t})}retrieve(e,t){return this._client.get(os`/v1/organizations/invites/${e}?beta=true`,t)}list(e={},t){return this._client.getAPIList("/v1/organizations/invites?beta=true",Nt,{query:e,...t})}delete(e,t){return this._client.delete(os`/v1/organizations/invites/${e}?beta=true`,t)}},co=class extends Gt{list(e={},t){return this._client.getAPIList("/v1/organizations/rate_limits?beta=true",qt,{query:e,...t})}},lo=class extends Gt{retrieve(e,t){return this._client.get(os`/v1/organizations/users/${e}?beta=true`,t)}update(e,t,s){return this._client.post(os`/v1/organizations/users/${e}?beta=true`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/users?beta=true",Nt,{query:e,...t})}remove(e,t){return this._client.delete(os`/v1/organizations/users/${e}?beta=true`,t)}},ho=class extends Gt{create(e,t){const{betas:s,...n}=e;return this._client.post("/v1/organizations/federation_issuers?beta=true",{body:n,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n}=t??{};return this._client.get(os`/v1/organizations/federation_issuers/${e}?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}update(e,t,s){const{betas:n,...r}=t;return this._client.post(os`/v1/organizations/federation_issuers/${e}?beta=true`,{body:r,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}list(e={},t){const{betas:s,...n}=e??{};return this._client.getAPIList("/v1/organizations/federation_issuers?beta=true",qt,{query:n,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}archive(e,t={},s){const{betas:n}=t??{};return this._client.post(os`/v1/organizations/federation_issuers/${e}/archive?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}},uo=class extends Gt{list(e,t={},s){const{betas:n,...r}=t??{};return this._client.getAPIList(os`/v1/organizations/federation_rules/${e}/workspaces?beta=true`,qt,{query:r,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}add(e,t,s){const{betas:n,...r}=t;return this._client.post(os`/v1/organizations/federation_rules/${e}/workspaces?beta=true`,{body:r,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}remove(e,t,s){const{federation_rule_id:n,betas:r}=t;return this._client.delete(os`/v1/organizations/federation_rules/${n}/workspaces/${e}?beta=true`,{...s,headers:ss([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}},po=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.workspaces=new uo(this._client)}create(e,t){const{betas:s,...n}=e;return this._client.post("/v1/organizations/federation_rules?beta=true",{body:n,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n}=t??{};return this._client.get(os`/v1/organizations/federation_rules/${e}?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}update(e,t,s){const{betas:n,...r}=t;return this._client.post(os`/v1/organizations/federation_rules/${e}?beta=true`,{body:r,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}list(e={},t){const{betas:s,...n}=e??{};return this._client.getAPIList("/v1/organizations/federation_rules?beta=true",qt,{query:n,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}archive(e,t={},s){const{betas:n}=t??{};return this._client.post(os`/v1/organizations/federation_rules/${e}/archive?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}}return e.Workspaces=uo,e})(),fo=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.issuers=new ho(this._client),this.rules=new po(this._client)}}return e.Issuers=ho,e.Rules=po,e})(),go=class extends Gt{list(e,t={},s){const{betas:n,...r}=t??{};return this._client.getAPIList(os`/v1/organizations/service_accounts/${e}/workspaces?beta=true`,qt,{query:r,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}add(e,t,s){const{betas:n,...r}=t;return this._client.post(os`/v1/organizations/service_accounts/${e}/workspaces?beta=true`,{body:r,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}remove(e,t,s){const{service_account_id:n,betas:r}=t;return this._client.delete(os`/v1/organizations/service_accounts/${n}/workspaces/${e}?beta=true`,{...s,headers:ss([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}},mo=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.workspaces=new go(this._client)}create(e,t){const{betas:s,...n}=e;return this._client.post("/v1/organizations/service_accounts?beta=true",{body:n,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n}=t??{};return this._client.get(os`/v1/organizations/service_accounts/${e}?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}update(e,t,s){const{betas:n,...r}=t;return this._client.post(os`/v1/organizations/service_accounts/${e}?beta=true`,{body:r,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}list(e={},t){const{betas:s,...n}=e??{};return this._client.getAPIList("/v1/organizations/service_accounts?beta=true",qt,{query:n,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}archive(e,t={},s){const{betas:n}=t??{};return this._client.post(os`/v1/organizations/service_accounts/${e}/archive?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}}return e.Workspaces=go,e})(),_o=class extends Gt{retrieve(e,t,s){const{workspace_id:n}=t;return this._client.get(os`/v1/organizations/workspaces/${n}/members/${e}?beta=true`,s)}update(e,t,s){const{workspace_id:n,...r}=t;return this._client.post(os`/v1/organizations/workspaces/${n}/members/${e}?beta=true`,{body:r,...s})}list(e,t={},s){return this._client.getAPIList(os`/v1/organizations/workspaces/${e}/members?beta=true`,Nt,{query:t,...s})}add(e,t,s){return this._client.post(os`/v1/organizations/workspaces/${e}/members?beta=true`,{body:t,...s})}remove(e,t,s){const{workspace_id:n}=t;return this._client.delete(os`/v1/organizations/workspaces/${n}/members/${e}?beta=true`,s)}},wo=class extends Gt{list(e,t={},s){return this._client.getAPIList(os`/v1/organizations/workspaces/${e}/rate_limits?beta=true`,qt,{query:t,...s})}},yo=class extends Gt{retrieve(e,t,s){const{workspace_id:n,betas:r}=t;return this._client.get(os`/v1/organizations/workspaces/${n}/service_accounts/${e}?beta=true`,{...s,headers:ss([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}update(e,t,s){const{workspace_id:n,betas:r,...i}=t;return this._client.post(os`/v1/organizations/workspaces/${n}/service_accounts/${e}?beta=true`,{body:i,...s,headers:ss([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}list(e,t={},s){const{betas:n,...r}=t??{};return this._client.getAPIList(os`/v1/organizations/workspaces/${e}/service_accounts?beta=true`,qt,{query:r,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}add(e,t,s){const{betas:n,...r}=t;return this._client.post(os`/v1/organizations/workspaces/${e}/service_accounts?beta=true`,{body:r,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}remove(e,t,s){const{workspace_id:n,betas:r}=t;return this._client.delete(os`/v1/organizations/workspaces/${n}/service_accounts/${e}?beta=true`,{...s,headers:ss([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}},bo=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.rateLimits=new wo(this._client),this.members=new _o(this._client),this.serviceAccounts=new yo(this._client)}create(e,t){const{betas:s,...n}=e;return this._client.post("/v1/organizations/workspaces?beta=true",{body:n,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}retrieve(e,t){return this._client.get(os`/v1/organizations/workspaces/${e}?beta=true`,t)}update(e,t,s){return this._client.post(os`/v1/organizations/workspaces/${e}?beta=true`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/workspaces?beta=true",Nt,{query:e,...t})}archive(e,t){return this._client.post(os`/v1/organizations/workspaces/${e}/archive?beta=true`,t)}}return e.RateLimits=wo,e.Members=_o,e.ServiceAccounts=yo,e})(),vo=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.apiKeys=new ro(this._client),this.externalKeys=new oo(this._client),this.federation=new fo(this._client),this.invites=new ao(this._client),this.serviceAccounts=new mo(this._client),this.users=new lo(this._client),this.workspaces=new bo(this._client),this.rateLimits=new co(this._client),this.complianceSettings=new io(this._client)}retrieve(e){return this._client.get("/v1/organizations/me?beta=true",e)}}return e.APIKeys=ro,e.ExternalKeys=oo,e.Federation=fo,e.Invites=ao,e.ServiceAccounts=mo,e.Users=lo,e.Workspaces=bo,e.RateLimits=co,e.ComplianceSettings=io,e})(),ko=/* @__PURE__ */(()=>{class e extends Gt{list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(os`/v1/sessions/${e}/events?beta=true`,qt,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}send(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/sessions/${e}/events?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}stream(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.get(os`/v1/sessions/${e}/events/stream?beta=true`,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers]),stream:!0})}toolRunner(e,t){return new Kn(e,{...t,client:this._client})}}return e.SessionToolRunner=Kn,e})(),So=class extends Gt{retrieve(e,t,s){const{session_id:n,betas:r,workspace_id:i}=t;return this._client.get(os`/v1/sessions/${n}/resources/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}update(e,t,s){const{session_id:n,betas:r,workspace_id:i,...o}=t;return this._client.post(os`/v1/sessions/${n}/resources/${e}?beta=true`,{body:o,...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(os`/v1/sessions/${e}/resources?beta=true`,qt,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}delete(e,t,s){const{session_id:n,betas:r,workspace_id:i}=t;return this._client.delete(os`/v1/sessions/${n}/resources/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}add(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/sessions/${e}/resources?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},xo=class extends Gt{list(e,t,s){const{session_id:n,betas:r,workspace_id:i,...o}=t;return this._client.getAPIList(os`/v1/sessions/${n}/threads/${e}/events?beta=true`,qt,{query:o,...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}stream(e,t,s){const{session_id:n,betas:r,workspace_id:i,...o}=t;return this._client.get(os`/v1/sessions/${n}/threads/${e}/stream?beta=true`,{query:o,...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers]),stream:!0})}},Ro=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.events=new xo(this._client)}retrieve(e,t,s){const{session_id:n,betas:r,workspace_id:i}=t;return this._client.get(os`/v1/sessions/${n}/threads/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(os`/v1/sessions/${e}/threads?beta=true`,qt,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}archive(e,t,s){const{session_id:n,betas:r,workspace_id:i}=t;return this._client.post(os`/v1/sessions/${n}/threads/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}}return e.Events=xo,e})(),Io=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.events=new ko(this._client),this.resources=new So(this._client),this.threads=new Ro(this._client)}create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/sessions?beta=true",{body:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/sessions/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}update(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/sessions/${e}?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/sessions?beta=true",Wt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}delete(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.delete(os`/v1/sessions/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}archive(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/sessions/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Events=ko,e.Resources=So,e.Threads=Ro,e})(),Ao=class extends Gt{create(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/skills/${e}/versions?beta=true`,zt({body:i,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])},this._client,!1))}retrieve(e,t,s){const{skill_id:n,betas:r,workspace_id:i}=t;return this._client.get(os`/v1/skills/${n}/versions/${e}?beta=true`,{...s,headers:ss([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0,...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(os`/v1/skills/${e}/versions?beta=true`,qt,{query:i,...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}delete(e,t,s){const{skill_id:n,betas:r,workspace_id:i}=t;return this._client.delete(os`/v1/skills/${n}/versions/${e}?beta=true`,{...s,headers:ss([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0,...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}download(e,t,s){const{skill_id:n,betas:r,workspace_id:i}=t;return this._client.get(os`/v1/skills/${n}/versions/${e}/content?beta=true`,{...s,headers:ss([{Accept:"application/binary",...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0,...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers]),__binaryResponse:!0})}},$o=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.versions=new Ao(this._client)}create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/skills?beta=true",zt({body:r,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])},this._client,!1))}retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/skills/${e}?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/skills?beta=true",qt,{query:r,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}delete(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.delete(os`/v1/skills/${e}?beta=true`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Versions=Ao,e})(),To=class extends Gt{create(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/tunnels/${e}/certificates?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"mcp-tunnels-2026-06-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}retrieve(e,t,s){const{tunnel_id:n,betas:r,workspace_id:i}=t;return this._client.get(os`/v1/tunnels/${n}/certificates/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"mcp-tunnels-2026-06-22"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(os`/v1/tunnels/${e}/certificates?beta=true`,qt,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"mcp-tunnels-2026-06-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}archive(e,t,s){const{tunnel_id:n,betas:r,workspace_id:i}=t;return this._client.post(os`/v1/tunnels/${n}/certificates/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"mcp-tunnels-2026-06-22"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}},Eo=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.certificates=new To(this._client)}create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/tunnels?beta=true",{body:r,...t,headers:ss([{"anthropic-beta":[...s??[],"mcp-tunnels-2026-06-22"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/tunnels/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"mcp-tunnels-2026-06-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/tunnels?beta=true",qt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"mcp-tunnels-2026-06-22"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}archive(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/tunnels/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"mcp-tunnels-2026-06-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}revealToken(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/tunnels/${e}/reveal_token?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"mcp-tunnels-2026-06-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}rotateToken(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/tunnels/${e}/rotate_token?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"mcp-tunnels-2026-06-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Certificates=To,e})(),Mo=class extends Gt{create(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/vaults/${e}/credentials?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}retrieve(e,t,s){const{vault_id:n,betas:r,workspace_id:i}=t;return this._client.get(os`/v1/vaults/${n}/credentials/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}update(e,t,s){const{vault_id:n,betas:r,workspace_id:i,...o}=t;return this._client.post(os`/v1/vaults/${n}/credentials/${e}?beta=true`,{body:o,...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(os`/v1/vaults/${e}/credentials?beta=true`,qt,{query:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}delete(e,t,s){const{vault_id:n,betas:r,workspace_id:i}=t;return this._client.delete(os`/v1/vaults/${n}/credentials/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}archive(e,t,s){const{vault_id:n,betas:r,workspace_id:i}=t;return this._client.post(os`/v1/vaults/${n}/credentials/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}mcpOAuthValidate(e,t,s){const{vault_id:n,betas:r,workspace_id:i}=t;return this._client.post(os`/v1/vaults/${n}/credentials/${e}/mcp_oauth_validate?beta=true`,{...s,headers:ss([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}},Oo=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.credentials=new Mo(this._client)}create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/vaults?beta=true",{body:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/vaults/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}update(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(os`/v1/vaults/${e}?beta=true`,{body:i,...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/vaults?beta=true",qt,{query:r,...t,headers:ss([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}delete(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.delete(os`/v1/vaults/${e}?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}archive(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.post(os`/v1/vaults/${e}/archive?beta=true`,{...s,headers:ss([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Credentials=Mo,e})(),Po=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.models=new Os(this._client),this.messages=new Mi(this._client),this.agents=new Ds(this._client),this.environments=new Yn(this._client),this.sessions=new Io(this._client),this.deployments=new cs(this._client),this.deploymentRuns=new as(this._client),this.vaults=new Oo(this._client),this.memoryStores=new er(this._client),this.files=new Ms(this._client),this.skills=new $o(this._client),this.webhooks=new js(this._client),this.userProfiles=new Ps(this._client),this.dreams=new ls(this._client),this.tunnels=new Eo(this._client),this.organization=new vo(this._client)}}return e.Models=Os,e.Messages=Mi,e.Agents=Ds,e.Environments=Yn,e.Sessions=Io,e.Deployments=cs,e.DeploymentRuns=as,e.Vaults=Oo,e.MemoryStores=er,e.Files=Ms,e.Skills=$o,e.Webhooks=js,e.UserProfiles=Ps,e.Dreams=ls,e.Tunnels=Eo,e.Organization=vo,e})(),Co=class extends Gt{create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/complete",{body:r,timeout:this._client._options.timeout??6e5,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers]),stream:e.stream??!1})}},Lo=class extends Gt{list(e={},t){const{workspace_id:s,...n}=e??{};return this._client.getAPIList("/v1/files",qt,{query:n,...t,headers:ss([{...null!=s?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(e,t={},s){const{workspace_id:n}=t??{};return this._client.delete(os`/v1/files/${e}`,{...s,headers:ss([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}download(e,t={},s){const{workspace_id:n}=t??{};return this._client.get(os`/v1/files/${e}/content`,{...s,headers:ss([{Accept:"application/binary",...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},s){const{workspace_id:n}=t??{};return this._client.get(os`/v1/files/${e}`,{...s,headers:ss([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}upload(e,t){const{workspace_id:s,...n}=e;return this._client.post("/v1/files",zt({body:n,...t,headers:ss([{...null!=s?{"anthropic-workspace-id":s}:void 0},_s(n.file),t?.headers])},this._client))}};function No(e){return e?.output_config?.format}function qo(e,t,s){const n=No(t);return t&&"parse"in(n??{})?Wo(e,t):{...e,content:e.content.map(e=>"text"===e.type?Object.defineProperty({...e},"parsed_output",{value:null,enumerable:!1}):e),parsed_output:null}}function Wo(e,t,s){let n=null;const r=e.content.map(e=>{if("text"===e.type){const s=function(e,t){const s=No(e);if("json_schema"!==s?.type)return null;try{return"parse"in s?s.parse(t):JSON.parse(t)}catch(n){throw new C(`Failed to parse structured output: ${n}`)}}(t,e.text);return null===n&&(n=s),Object.defineProperty({...e},"parsed_output",{value:s,enumerable:!1})}return e});return{...e,content:r,parsed_output:n}}function jo(e){return"tool_use"===e.type||"server_tool_use"===e.type}var Uo,Do,Ho,zo,Fo=/* @__PURE__ */(()=>{class e{constructor(e,t){Pi.add(this),this.messages=[],this.receivedMessages=[],Ci.set(this,void 0),Li.set(this,null),this.controller=new AbortController,Ni.set(this,void 0),qi.set(this,()=>{}),Wi.set(this,()=>{}),ji.set(this,void 0),Ui.set(this,()=>{}),Di.set(this,()=>{}),Hi.set(this,{}),zi.set(this,!1),Fi.set(this,!1),Bi.set(this,!1),Ki.set(this,!1),Ji.set(this,void 0),Vi.set(this,void 0),Xi.set(this,void 0),Gi.set(this,void 0),Zi.set(this,e=>{if(X(this,Fi,!0,"f"),O(e)&&(e=new N),e instanceof N)return X(this,Bi,!0,"f"),this._emit("abort",e);if(e instanceof C)return this._emit("error",e);if(e instanceof Error){const t=new C(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new C(String(e)))}),X(this,Ni,new Promise((e,t)=>{X(this,qi,e,"f"),X(this,Wi,t,"f")}),"f"),X(this,ji,new Promise((e,t)=>{X(this,Ui,e,"f"),X(this,Di,t,"f")}),"f"),G(this,Ni,"f").catch(()=>{}),G(this,ji,"f").catch(()=>{}),X(this,Li,e,"f"),X(this,Gi,t?.logger??console,"f")}get response(){return G(this,Ji,"f")}get request_id(){return G(this,Vi,"f")}get workspace_id(){return G(this,Xi,"f")}async withResponse(){X(this,Ki,!0,"f");const e=await G(this,Ni,"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(t){const s=new e(null);return s._run(()=>s._fromReadableStream(t)),s}static createMessage(t,s,n,{logger:r}={}){const i=new e(s,{logger:r});for(const e of s.messages)i._addMessageParam(e);return X(i,Li,{...s,stream:!0},"f"),i._run(()=>i._createMessage(t,{...s,stream:!0},{...n,headers:{...n?.headers,[ds]:"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},G(this,Zi,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,s){const n=s?.signal;let r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener("abort",r));try{G(this,Pi,"m",eo).call(this);const{response:n,data:r}=await e.create({...t,stream:!0},{...s,signal:this.controller.signal}).withResponse();this._connected(n);for await(const e of r)G(this,Pi,"m",to).call(this,e);if(r.controller.signal?.aborted)throw new N;G(this,Pi,"m",so).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}_connected(e){this.ended||(X(this,Ji,e,"f"),X(this,Vi,e?.headers.get("request-id"),"f"),X(this,Xi,e?.headers.get("anthropic-workspace-id"),"f"),G(this,qi,"f").call(this,e),this._emit("connect"))}get ended(){return G(this,zi,"f")}get errored(){return G(this,Fi,"f")}get aborted(){return G(this,Bi,"f")}abort(){this.controller.abort()}on(e,t){return(G(this,Hi,"f")[e]||(G(this,Hi,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=G(this,Hi,"f")[e];if(!s)return this;const n=s.findIndex(e=>e.listener===t);return n>=0&&s.splice(n,1),this}once(e,t){return(G(this,Hi,"f")[e]||(G(this,Hi,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{X(this,Ki,!0,"f"),"error"!==e&&this.once("error",s),this.once(e,t)})}async done(){X(this,Ki,!0,"f"),await G(this,ji,"f")}get currentMessage(){return G(this,Ci,"f")}async finalMessage(){return await this.done(),G(this,Pi,"m",Yi).call(this)}async finalText(){return await this.done(),G(this,Pi,"m",Qi).call(this)}_emit(e,...t){if(G(this,zi,"f"))return;"end"===e&&(X(this,zi,!0,"f"),G(this,Ui,"f").call(this));const s=G(this,Hi,"f")[e];if(s&&(G(this,Hi,"f")[e]=s.filter(e=>!e.once),s.forEach(({listener:e})=>e(...t))),"abort"===e){const e=t[0];return G(this,Ki,"f")||s?.length||Promise.reject(e),G(this,Wi,"f").call(this,e),G(this,Di,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];G(this,Ki,"f")||s?.length||Promise.reject(e),G(this,Wi,"f").call(this,e),G(this,Di,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",G(this,Pi,"m",Yi).call(this))}async _fromReadableStream(e,t){const s=t?.signal;let n;s&&(s.aborted&&this.controller.abort(),n=this.controller.abort.bind(this.controller),s.addEventListener("abort",n));try{G(this,Pi,"m",eo).call(this),this._connected(null);const t=kt.fromReadableStream(e,this.controller);for await(const e of t)G(this,Pi,"m",to).call(this,e);if(t.controller.signal?.aborted)throw new N;G(this,Pi,"m",so).call(this)}finally{s&&n&&s.removeEventListener("abort",n)}}[(Ci=/* @__PURE__ */new WeakMap,Li=/* @__PURE__ */new WeakMap,Ni=/* @__PURE__ */new WeakMap,qi=/* @__PURE__ */new WeakMap,Wi=/* @__PURE__ */new WeakMap,ji=/* @__PURE__ */new WeakMap,Ui=/* @__PURE__ */new WeakMap,Di=/* @__PURE__ */new WeakMap,Hi=/* @__PURE__ */new WeakMap,zi=/* @__PURE__ */new WeakMap,Fi=/* @__PURE__ */new WeakMap,Bi=/* @__PURE__ */new WeakMap,Ki=/* @__PURE__ */new WeakMap,Ji=/* @__PURE__ */new WeakMap,Vi=/* @__PURE__ */new WeakMap,Xi=/* @__PURE__ */new WeakMap,Gi=/* @__PURE__ */new WeakMap,Zi=/* @__PURE__ */new WeakMap,Pi=/* @__PURE__ */new WeakSet,Yi=function(){if(0===this.receivedMessages.length)throw new C("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Qi=function(){if(0===this.receivedMessages.length)throw new C("stream ended without producing a Message with role=assistant");const e=this.receivedMessages.at(-1).content.filter(e=>"text"===e.type).map(e=>e.text);if(0===e.length)throw new C("stream ended without producing a content block with type=text");return e.join(" ")},eo=function(){this.ended||X(this,Ci,void 0,"f")},to=function(e){if(this.ended)return;const t=G(this,Pi,"m",no).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{const s=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===s.type&&this._emit("text",e.delta.text,s.text||"");break;case"citations_delta":"text"===s.type&&this._emit("citation",e.delta.citation,s.citations??[]);break;case"input_json_delta":jo(s)&&G(this,Hi,"f").inputJson?.length&&this._emit("inputJson",e.delta.partial_json,s.input);break;case"thinking_delta":"thinking"===s.type&&this._emit("thinking",e.delta.thinking,s.thinking);break;case"signature_delta":"thinking"===s.type&&this._emit("signature",s.signature);break;default:/* @__PURE__ */e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(qo(t,G(this,Li,"f"),G(this,Gi,"f")),!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":X(this,Ci,t,"f")}},so=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");const e=G(this,Ci,"f");if(!e)throw new C("request ended without sending any chunks");return X(this,Ci,void 0,"f"),qo(e,G(this,Li,"f"),G(this,Gi,"f"))},no=function(e){let t=G(this,Ci,"f");if("message_start"===e.type){if(t)throw new C(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new C(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.stop_details=e.delta.stop_details,t.usage.output_tokens=e.usage.output_tokens,null!=e.delta.container&&(t.container=e.delta.container),null!=e.usage.input_tokens&&(t.usage.input_tokens=e.usage.input_tokens),null!=e.usage.cache_creation_input_tokens&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),null!=e.usage.cache_read_input_tokens&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),null!=e.usage.server_tool_use&&(t.usage.server_tool_use=e.usage.server_tool_use),null!=e.usage.output_tokens_details&&(t.usage.output_tokens_details=e.usage.output_tokens_details),t;case"content_block_start":return t.content.push({...e.content_block}),t;case"content_block_delta":{const s=t.content.at(e.index);switch(e.delta.type){case"text_delta":"text"===s?.type&&(t.content[e.index]={...s,text:(s.text||"")+e.delta.text});break;case"citations_delta":"text"===s?.type&&(t.content[e.index]={...s,citations:[...s.citations??[],e.delta.citation]});break;case"input_json_delta":if(s&&jo(s)){const n=(s.__json_buf||"")+e.delta.partial_json;t.content[e.index]=Cr(s,n)}break;case"thinking_delta":"thinking"===s?.type&&(t.content[e.index]={...s,thinking:s.thinking+e.delta.thinking});break;case"signature_delta":"thinking"===s?.type&&(t.content[e.index]={...s,signature:e.delta.signature});break;default:/* @__PURE__ */e.delta}return t}case"content_block_stop":{const s=t.content.at(e.index);return s&&jo(s)&&"__json_buf"in s&&Object.defineProperty(s,"input",{value:s.input,enumerable:!0,configurable:!0,writable:!0}),t}}},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("streamEvent",s=>{const n=t.shift();n?n.resolve(s):e.push(s)}),this.on("end",()=>{s=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{s=!0;for(const s of t)s.reject(e);t.length=0}),this.on("error",e=>{s=!0;for(const s of t)s.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((e,s)=>t.push({resolve:e,reject:s})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new kt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}return e})(),Bo=class extends Gt{create(e,t){const{user_profile_id:s,workspace_id:n,...r}=e;return this._client.post("/v1/messages/batches",{body:r,...t,headers:ss([{...null!=s?{"anthropic-user-profile-id":s}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}retrieve(e,t={},s){const{workspace_id:n}=t??{};return this._client.get(os`/v1/messages/batches/${e}`,{...s,headers:ss([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}list(e={},t){const{workspace_id:s,...n}=e??{};return this._client.getAPIList("/v1/messages/batches",Nt,{query:n,...t,headers:ss([{...null!=s?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(e,t={},s){const{workspace_id:n}=t??{};return this._client.delete(os`/v1/messages/batches/${e}`,{...s,headers:ss([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}cancel(e,t={},s){const{workspace_id:n}=t??{};return this._client.post(os`/v1/messages/batches/${e}/cancel`,{...s,headers:ss([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}async results(e,t={},s){const n=await this.retrieve(e,t,s);if(!n.results_url)throw new C(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);const{workspace_id:r}=t??{};return this._client.get(n.results_url,{...s,headers:ss([{Accept:"application/binary",...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>tr.fromResponse(t.response,t.controller))}},Ko=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.batches=new Bo(this._client)}create(e,t){const{user_profile_id:s,workspace_id:n,...r}=e;r.model,Jo.includes(r.model)&&r.thinking&&r.thinking.type;let i=t?.timeout??this._client._options.timeout;if(!r.stream&&null==i){const e=nr[r.model]??void 0;i=this._client.calculateNonstreamingTimeout(r.max_tokens,e)}const o=ms(r.tools,r.messages);return this._client.post("/v1/messages",{body:r,timeout:i??6e5,...t,headers:ss([{...null!=s?{"anthropic-user-profile-id":s}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},o,t?.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then(t=>Wo(t,e,this._client.logger??console))}stream(e,t){return Fo.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){const{user_profile_id:s,workspace_id:n,...r}=e;return this._client.post("/v1/messages/count_tokens",{body:r,...t,headers:ss([{...null!=s?{"anthropic-user-profile-id":s}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}}return e.Batches=Bo,e})(),Jo=["claude-mythos-preview","claude-opus-4-6"],Vo=class extends Gt{retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(os`/v1/models/${e}`,{...s,headers:ss([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/models",Nt,{query:r,...t,headers:ss([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}},Xo=class extends Gt{create(e,t,s){const{workspace_id:n,...r}=t;return this._client.post(os`/v1/skills/${e}/versions`,zt({body:r,...s,headers:ss([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])},this._client,!1))}retrieve(e,t,s){const{skill_id:n,workspace_id:r}=t;return this._client.get(os`/v1/skills/${n}/versions/${e}`,{...s,headers:ss([{...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e,t={},s){const{workspace_id:n,...r}=t??{};return this._client.getAPIList(os`/v1/skills/${e}/versions`,qt,{query:r,...s,headers:ss([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}delete(e,t,s){const{skill_id:n,workspace_id:r}=t;return this._client.delete(os`/v1/skills/${n}/versions/${e}`,{...s,headers:ss([{...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},Go=/* @__PURE__ */(()=>{class e extends Gt{constructor(){super(...arguments),this.versions=new Xo(this._client)}create(e,t){const{workspace_id:s,...n}=e;return this._client.post("/v1/skills",zt({body:n,...t,headers:ss([{...null!=s?{"anthropic-workspace-id":s}:void 0},t?.headers])},this._client,!1))}retrieve(e,t={},s){const{workspace_id:n}=t??{};return this._client.get(os`/v1/skills/${e}`,{...s,headers:ss([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}list(e={},t){const{workspace_id:s,...n}=e??{};return this._client.getAPIList("/v1/skills",qt,{query:n,...t,headers:ss([{...null!=s?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(e,t={},s){const{workspace_id:n}=t??{};return this._client.delete(os`/v1/skills/${e}`,{...s,headers:ss([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}}return e.Versions=Xo,e})(),Yo=/* @__PURE__ */(()=>{class e{get credentials(){return this._authState.provider}constructor({baseURL:e=Ke("ANTHROPIC_BASE_URL"),apiKey:t,authToken:s,webhookKey:n=Ke("ANTHROPIC_WEBHOOK_SIGNING_KEY")??null,...r}={}){if(Uo.add(this),this._requestAuthFlags=/* @__PURE__ */new WeakMap,Ho.set(this,void 0),void 0===t&&(t=null!=r.profile?null:Ke("ANTHROPIC_API_KEY")??null),void 0===s&&(s=null!=r.profile?null:Ke("ANTHROPIC_AUTH_TOKEN")??null),null!=r.profile&&(null!=r.credentials||null!=r.config))throw new TypeError("Pass at most one of `profile`, `credentials`, or `config`.");const i={apiKey:t,authToken:s,webhookKey:n,...r,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new C("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");this.baseURL=i.baseURL,this._baseURLIsExplicit=r.__baseURLIsExplicit??!!e,this.timeout=i.timeout??Do.DEFAULT_TIMEOUT,this.logger=i.logger??console,this.logLevel="warn",this.logLevel=Ge(i.logLevel,"ClientOptions.logLevel",rt(this))??Ge(Ke("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",rt(this))??"warn",this.fetchOptions=i.fetchOptions,this.maxRetries=re("maxRetries",i.maxRetries??2),this.fetch=i.fetch??function(){if("undefined"!=typeof fetch)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`")}(),X(this,Ho,_e,"f"),this.middleware=[...i.middleware??[]];const o=Ke("ANTHROPIC_CUSTOM_HEADERS");if(o){const e={};for(const t of o.split("\n")){const s=t.indexOf(":");s>=0&&(e[t.substring(0,s).trim()]=t.substring(s+1).trim())}i.defaultHeaders={...e,...i.defaultHeaders}}const a=r.__auth;if(delete i.__auth,delete i.__baseURLIsExplicit,this._options=i,this.apiKey="string"==typeof t?t:null,this.authToken=s,this.webhookKey=n,a)this._authState=a,!this._baseURLIsExplicit&&a.baseURL&&(this.baseURL=a.baseURL);else if(this._authState={provider:null,tokenCache:null,resolution:null,error:null,extraHeaders:{}},null==this.apiKey&&null==this.authToken){const e=i.credentials??null;if(e)this._authState.provider=e,this._authState.tokenCache=this._makeTokenCache(e);else if(null!=i.config){const e=wt(i.config,this._credentialResolverOptions());this._authState.provider=e.provider,this._authState.tokenCache=this._makeTokenCache(e.provider),this._authState.extraHeaders=e.extraHeaders,this._applyCredentialBaseURL(e.baseURL)}else null!=i.profile?this._authState.resolution=this._resolveDefaultCredentials(i.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=>{rt(this).debug("credential cache write failed (best-effort)",e)},onSafetyWarning:e=>{rt(this).warn(e)}}}_credentialsFetch(){return Et(this.fetch,this.middleware,void 0,this)}_makeTokenCache(e){return new Be(e,e=>{rt(this).debug("advisory token refresh failed; serving cached token",e)})}withOptions(e){const t="credentials"in e||"config"in e||"profile"in e,s="apiKey"in e||"authToken"in e||t,n={...this._options,...this._baseURLIsExplicit?{baseURL:this.baseURL}:{},maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,middleware:this.middleware,apiKey:this.apiKey,authToken:this.authToken,webhookKey:this.webhookKey,credentials:this.credentials,...t?{credentials:void 0,config:void 0,profile:void 0}:{},...e,__auth:s?void 0:this._authState,__baseURLIsExplicit:"baseURL"in e||this._baseURLIsExplicit};return new this.constructor(n)}async _resolveDefaultCredentials(e){try{const t=await async function(e,t){const s=await(async e=>{var t,s;const n=await ft();if(null===n)return null;const r=e??await mt();if(null===r)return null;ht(r);const{fs:i,path:o}=await(import("./node.browser-CE0N-lmH.js")),a=o.join(n,"configs",`${r}.json`);let c,l;try{c=await i.promises.readFile(a,"utf-8")}catch(d){if("ENOENT"!==d?.code)throw new Error(`failed to read config file ${a}: ${d}`);c=null}if(null===c){const e=Ke("ANTHROPIC_ORGANIZATION_ID"),t=Ke("ANTHROPIC_IDENTITY_TOKEN_FILE"),s=Ke("ANTHROPIC_FEDERATION_RULE_ID");return s&&e?{fromFile:!1,config:{organization_id:e,workspace_id:Ke("ANTHROPIC_WORKSPACE_ID"),base_url:Ke("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:s,service_account_id:Ke("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:t?{source:"file",path:t}:void 0,scope:Ke("ANTHROPIC_SCOPE")}}}:null}try{l=JSON.parse(c)}catch(d){throw new Error(`failed to parse config file ${a}: ${d}`)}if(!l.authentication)throw new Error(`config file ${a} is missing "authentication"`);const h=l.authentication.type;if("oidc_federation"!==h&&"user_oauth"!==h)throw new Error(`authentication.type "${h}" is not a known authentication type`);if(l.organization_id??(l.organization_id=Ke("ANTHROPIC_ORGANIZATION_ID")),l.workspace_id??(l.workspace_id=Ke("ANTHROPIC_WORKSPACE_ID")),l.base_url??(l.base_url=Ke("ANTHROPIC_BASE_URL")),(t=l.authentication).scope??(t.scope=Ke("ANTHROPIC_SCOPE")),"oidc_federation"===l.authentication.type){if(!l.authentication.identity_token){const e=Ke("ANTHROPIC_IDENTITY_TOKEN_FILE");e&&(l.authentication.identity_token={source:"file",path:e})}l.authentication.federation_rule_id||(l.authentication.federation_rule_id=Ke("ANTHROPIC_FEDERATION_RULE_ID")??""),(s=l.authentication).service_account_id??(s.service_account_id=Ke("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:l,fromFile:!0}})(t);if(!s)return null;const{config:n,fromFile:r}=s;return wt(n.authentication.credentials_path||!r?n:{...n,authentication:{...n.authentication,credentials_path:await pt(n,t)??void 0}},e)}(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(null!=e)throw new C(`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&&null==this.apiKey){const t=await this._authState.tokenCache.getToken();return this._authFlags(e).usedTokenCache=!0,ss([{Authorization:`Bearer ${t}`}])}return ss([await this.apiKeyAuth(e),await this.bearerAuth(e)])}}async apiKeyAuth(e){if(null!=this.apiKey)return ss([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(null!=this.authToken)return ss([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return function(e){return function(e,t={}){let s=e;const n=function(e=$e){if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.encodeDotInKeys&&"boolean"!=typeof e.encodeDotInKeys)throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");const t=e.charset||$e.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let s=we;if(void 0!==e.format){if(!ve(be,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const n=be[s];let r,i=$e.filter;if(("function"==typeof e.filter||Q(e.filter))&&(i=e.filter),r=e.arrayFormat&&e.arrayFormat in Ie?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":$e.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const o=void 0===e.allowDots?1==!!e.encodeDotInKeys||$e.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:$e.addQueryPrefix,allowDots:o,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:$e.allowEmptyArrays,arrayFormat:r,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:$e.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?$e.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:$e.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:$e.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:$e.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:$e.encodeValuesOnly,filter:i,format:s,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:$e.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:$e.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:$e.strictNullHandling}}(t);let r,i;"function"==typeof n.filter?(i=n.filter,s=i("",s)):Q(n.filter)&&(i=n.filter,r=i);const o=[];if("object"!=typeof s||null===s)return"";const a=Ie[n.arrayFormat],c="comma"===a&&n.commaRoundTrip;r||(r=Object.keys(s)),n.sort&&r.sort(n.sort);const l=/* @__PURE__ */new WeakMap;for(let u=0;u<r.length;++u){const e=r[u];n.skipNulls&&null===s[e]||Ae(o,Ee(s[e],e,a,c,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,l))}const h=o.join(n.delimiter);let d=!0===n.addQueryPrefix?"?":"";return n.charsetSentinel&&("iso-8859-1"===n.charset?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),h.length>0?d+h:""}(e,{arrayFormat:"brackets"})}(e)}getUserAgent(){return`Anthropic/JS ${ae}`}makeStatusError(e,t,s,n){return L.generate(e,t,s,n)}buildURL(e,t,s){const n=!G(this,Uo,"m",zo).call(this)&&s||this.baseURL,r=(e=>Y.test(e))(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),o=Object.fromEntries(r.searchParams);return te(i)&&te(o)||(t={...o,...i,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new C("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 6e5}async prepareOptions(e){}async prepareRequest(e,{url:t,options:s}){if(this._authState.tokenCache&&null==this.apiKey){const t=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(const[e,n]of Object.entries(this._authState.extraHeaders))t.has(e)||t.set(e,n);const s=t.get("anthropic-beta")?.split(",").map(e=>e.trim());s?.includes("oauth-2025-04-20")||t.set("anthropic-beta",[...s??[],Oe].join(",")),e.headers=t}}backendMiddleware(){return[]}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,s){return this.request(Promise.resolve(s).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new Pt(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){const n=await e;let r=re("maxRetries",n.maxRetries??this.maxRetries);this.isStreamBody(n.body)&&(r=0),null==t&&(t=r,this._requestAuthFlags.delete(n)),await this.prepareOptions(n);const{req:i,url:o,timeout:a}=await this.buildRequest(n,{retryCount:r-t}),c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=void 0===s?"":`, retryOf: ${s}`,h=Date.now();if(n.signal?.aborted)throw new N;const d=new AbortController,u=await this.fetchWithTimeout(o,i,a,d,n,{requestLogID:c,retryOfRequestLogID:s}).catch(P),p=Date.now();if(u instanceof globalThis.Error){pe(d);const e=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new N;const r=O(u)||/timed? ?out/i.test(String(u)+("cause"in u?String(u.cause):"")),i=this.middleware.length>0||!!n.middleware?.length||this.backendMiddleware().length>0;if(i&&!r&&!function(e){const t=/* @__PURE__ */new Set;for(;"object"==typeof e&&null!==e&&!t.has(e);){if(t.add(e),Tt(e)||O(e)||e instanceof q||e instanceof j)return!0;e=e.cause}return!1}(u))throw rt(this).info(`[${c}] middleware error (not retryable)`),ot(rt(this),`[${c}] middleware error (not retryable)`,{retryOfRequestLogID:s,url:o,durationMs:p-h,message:u.message}),u;if(t)return rt(this).info(`[${c}] connection ${r?"timed out":"failed"} - ${e}`),ot(rt(this),`[${c}] connection ${r?"timed out":"failed"} (${e})`,{retryOfRequestLogID:s,url:o,durationMs:p-h,message:u.message}),this.retryRequest(n,t,s??c);if(rt(this).info(`[${c}] connection ${r?"timed out":"failed"} - error; no more retries left`),ot(rt(this),`[${c}] connection ${r?"timed out":"failed"} (error; no more retries left)`,{retryOfRequestLogID:s,url:o,durationMs:p-h,message:u.message}),r)throw new W;if(i&&!Tt(u))throw u;throw new q({cause:u})}const f=`[${c}${l}${[...u.headers.entries()].filter(([e])=>"request-id"===e||"anthropic-workspace-id"===e).map(([e,t])=>", "+e+": "+JSON.stringify(t)).join("")}] ${i.method} ${o} ${u.ok?"succeeded":"failed"} with status ${u.status} in ${p-h}ms`;if(!u.ok){const e=await this.shouldRetry(u,n);if(t&&e){const e=`retrying, ${t} attempts remaining`;return await async function(e){if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void(await(e[Symbol.asyncIterator]().return?.()));const t=e.getReader(),s=t.cancel();t.releaseLock(),await s}(u.body),pe(d),rt(this).info(`${f} - ${e}`),ot(rt(this),`[${c}] response error (${e})`,{retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,durationMs:p-h}),this.retryRequest(n,t,s??c,u.headers)}const r=e?"error; no more retries left":"error; not retryable";rt(this).info(`${f} - ${r}`);const i=await u.text().catch(e=>P(e).message),o=ie(i),a=o?void 0:i;throw ot(rt(this),`[${c}] response error (${r})`,{retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,message:a,durationMs:Date.now()-h}),pe(d),this.makeStatusError(u.status,o,a,u.headers)}return rt(this).info(f),ot(rt(this),`[${c}] response start`,{retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,durationMs:p-h}),function(e,t){de.has(t)&&ue?.register(e,t,t)}(u.body??u,d),{response:u,options:n,controller:d,requestLogID:c,retryOfRequestLogID:s,startTime:h}}getAPIList(e,t,s){return this.requestAPIList(t,s&&"then"in s?s.then(t=>({method:"get",path:e,...t})):{method:"get",path:e,...s})}requestAPIList(e,t){const s=this.makeRequest(t,null,void 0);return new Lt(this,s,e)}async fetchWithTimeout(e,t,s,n,r,i){const{signal:o,method:a,...c}=t||{},l=this._makeAbort(n);o&&(o.addEventListener("abort",l,{once:!0}),function(e,t,s){de.set(e,function(e,t){return()=>e.removeEventListener("abort",t)}(t,s))}(n,o,l));const h=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||"object"==typeof c.body&&null!==c.body&&Symbol.asyncIterator in c.body,d={signal:n.signal,...h?{duplex:"half"}:{},method:"GET",...c};a&&(d.method=a.toUpperCase());const u=this.fetch,p=async(e,t)=>{const n=setTimeout(l,s);try{return await u.call(void 0,e,t)}finally{clearTimeout(n)}},f=void 0===r?p:async(e,t={})=>{const s="string"==typeof e?e:e instanceof URL?e.href:e.url;return t.headers=t.headers instanceof Headers?t.headers:new Headers(t.headers),await this.prepareRequest(t,{url:s,options:r}),i&&ot(rt(this),`[${i.requestLogID}] sending request`,{retryOfRequestLogID:i.retryOfRequestLogID,method:t.method,url:s,options:r,headers:t.headers}),p(e,t)},g=r?.middleware,m=this.backendMiddleware(),_=g?.length||m.length?[...this.middleware,...g??[],...m]:this.middleware;return await Et(f,_,r,this)(e,d)}async shouldRetry(e,t){const s=this._authFlags(t);if(401===e.status&&this._authState.tokenCache&&s.usedTokenCache&&!s.didRefreshFor401)return s.didRefreshFor401=!0,this._authState.tokenCache.invalidate(),!0;const n=e.headers.get("x-should-retry");return"true"===n||"false"!==n&&(408===e.status||409===e.status||429===e.status||e.status>=500)}async retryRequest(e,t,s,n){let r;const i=n?.get("retry-after-ms");if(i){const e=parseFloat(i);Number.isNaN(e)||(r=e)}const o=n?.get("retry-after");if(o&&!r){const e=parseFloat(o);r=Number.isNaN(e)?Date.parse(o)-Date.now():1e3*e}if(void 0===r||!(r>0&&r<=2**31-1)){const s=e.maxRetries??this.maxRetries;r=this.calculateDefaultRetryTimeoutMillis(t,s)}return await oe(r,e.signal??void 0),this.makeRequest(e,t-1,s)}calculateDefaultRetryTimeoutMillis(e,t){const s=t-e;return Math.min(.5*Math.pow(2,s),8)*(1-.25*Math.random())*1e3}calculateNonstreamingTimeout(e,t){const s=6e5;if(36e5*e/128e3>s||null!=t&&e>t)throw new C("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 s}async buildRequest(e,{retryCount:t=0}={}){const s={...e},{method:n,path:r,query:i,defaultBaseURL:o}=s;this._authState.resolution&&await this._authState.resolution,!this._baseURLIsExplicit&&this._authState.baseURL&&this.baseURL!==this._authState.baseURL&&(this.baseURL=this._authState.baseURL);const a=this.buildURL(r,i,o);"timeout"in s&&re("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:c,body:l}=this.buildBody({options:s});return{req:{method:n,headers:await this.buildHeaders({options:e,method:n,bodyHeaders:c,retryCount:t,timeout:s.timeout}),...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...s.fetchOptions??{}},url:a,timeout:s.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:s,retryCount:n,timeout:r}){const i=ss([{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),"X-Stainless-Timeout":String(Math.trunc(r/1e3)),...he(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(i),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=ss([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:this.isStreamBody(e)?{bodyHeaders:void 0,body:ge(e)}:"object"==typeof e&&"application/x-www-form-urlencoded"===s.values.get("content-type")?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:G(this,Ho,"f").call(this,{body:e,headers:s})}isStreamBody(e){return!!(globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)||"object"==typeof e&&null!==e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)}}return Do=e,Ho=/* @__PURE__ */new WeakMap,Uo=/* @__PURE__ */new WeakSet,zo=function(){return"https://api.anthropic.com"!==this.baseURL},e.Anthropic=Do,e.DEFAULT_TIMEOUT=6e5,e.AnthropicError=C,e.APIError=L,e.APIConnectionError=q,e.APIConnectionTimeoutError=W,e.APIUserAbortError=N,e.NotFoundError=z,e.ConflictError=F,e.RateLimitError=K,e.BadRequestError=U,e.AuthenticationError=D,e.InternalServerError=J,e.PermissionDeniedError=H,e.UnprocessableEntityError=B,e.toFile=Vt,e.HUMAN_PROMPT="\\n\\nHuman:",e.AI_PROMPT="\\n\\nAssistant:",e})(),Qo=/* @__PURE__ */(()=>{class e extends Yo{constructor(){super(...arguments),this.completions=new Co(this),this.messages=new Ko(this),this.models=new Vo(this),this.files=new Lo(this),this.skills=new Go(this),this.beta=new Po(this)}}return e.Completions=Co,e.Messages=Ko,e.Models=Vo,e.Files=Lo,e.Skills=Go,e.Beta=Po,e})(),Zo=/* @__PURE__ */e({stream:()=>ya,streamSimple:()=>ba});function ea(e,t){return e||("long"===b("PI_CACHE_RETENTION",t)?"long":"short")}var ta=new Map(["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"].map(e=>[e.toLowerCase(),e])),sa=e=>ta.get(e.toLowerCase())??e,na=(e,t)=>{if(t&&t.length>0){const s=e.toLowerCase(),n=t.find(e=>e.name.toLowerCase()===s);if(n)return n.name}return e};function ra(e){return{type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}}}function ia(e){if(!e.some(e=>"image"===e.type))return I(e.map(e=>e.text).join("\n"));const t=e.map(e=>"text"===e.type?{type:"text",text:I(e.text)}:ra(e));return t.some(e=>"text"===e.type)||t.unshift({type:"text",text:"(see attached image)"}),t}var oa={name:"__pi_deferred_placeholder__",description:"Reserved placeholder. Never available. Never call this.",input_schema:{type:"object",properties:{},required:[]},defer_loading:!0};function aa(e){const t="openrouter"===e.provider||e.baseUrl.includes("openrouter.ai");return{supportsEagerToolInputStreaming:e.compat?.supportsEagerToolInputStreaming??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0,sendSessionAffinityHeaders:e.compat?.sendSessionAffinityHeaders??t,sessionAffinityFormat:e.compat?.sessionAffinityFormat??(t?"openrouter":void 0),supportsCacheControlOnTools:e.compat?.supportsCacheControlOnTools??!0,supportsTemperature:e.compat?.supportsTemperature??!0,allowEmptySignature:e.compat?.allowEmptySignature??!1,supportsStrictTools:e.compat?.supportsStrictTools??!1,supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,supportsMidConvoToolChanges:e.compat?.supportsMidConvoToolChanges??!1}}function ca(...e){const t={};for(const s of e)s&&Object.assign(t,s);return t}function la(e,t){if(!e)return!1;const s=t.toLowerCase();for(const[n,r]of Object.entries(e))if(n.toLowerCase()===s&&null!==r&&r.trim().length>0)return!0;return!1}function ha(e,t){return!!e||la(t,"authorization")||la(t,"x-api-key")||la(t,"cf-aig-authorization")}function da(e,t,s){if(!ha(t,s))throw new Error(`No API key for provider: ${e}`)}var ua,pa=class extends Qo{_shouldResolveDefaultCredentials(){return!1}};function fa(e,t,s,n){if("anthropic"!==e.provider||ha(t,s))return;const r=b(h,n),i=b(l,n),a=b(u,n);return r&&i&&a?{organization_id:i,workspace_id:b(d,n),authentication:{type:"oidc_federation",federation_rule_id:r,service_account_id:b(o,n),identity_token:{source:"file",path:a}}}:void 0}var ga=/* @__PURE__ */new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);function ma(e){if(!e.event&&0===e.data.length)return null;const t={event:e.event,data:e.data.join("\n"),raw:[...e.raw]};return e.event=null,e.data=[],e.raw=[],t}function _a(e,t){if(""===e)return ma(t);if(t.raw.push(e),e.startsWith(":"))return null;const s=e.indexOf(":"),n=-1===s?e:e.slice(0,s);let r=-1===s?"":e.slice(s+1);return r.startsWith(" ")&&(r=r.slice(1)),"event"===n?t.event=r:"data"===n&&t.data.push(r),null}function wa(e){const t=function(e){const t=e.indexOf("\r"),s=e.indexOf("\n");return-1===t?s:-1===s?t:Math.min(t,s)}(e);if(-1===t)return null;let s=t+1;return"\r"===e[t]&&"\n"===e[s]&&(s+=1),{line:e.slice(0,t),rest:e.slice(s)}}var ya=(e,t,n)=>{const i=new r,o=p(t,aa(e).supportsMidConvoSystemMessages),l=c(o.messages);return(async()=>{const t={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let c,h,d,u=e;if(n?.client)c=n.client,h=!1;else{const t=n?.apiKey,r=fa(e,t,n?.headers,n?.env);let i;if(r||da(e.provider,t,n?.headers),"github-copilot"===e.provider){const e=w(o.messages);i=v({messages:o.messages,hasImages:e})}const a="none"===ea(n?.cacheRetention,n?.env)?void 0:n?.sessionId,l=function(e,t,n,r,i,o,a,c){if("github-copilot"===e.provider)return{client:new pa({apiKey:null,authToken:t??null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:r,defaultHeaders:ca(s(e,c),{accept:"application/json","anthropic-dangerous-direct-browser-access":"true"},e.headers,i,n)}),isOAuthToken:!1};if(t&&function(e){return e.includes("sk-ant-oat")}(t))return{client:new pa({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:r,defaultHeaders:ca({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","user-agent":"claude-cli/2.1.280","x-app":"cli"},e.headers,n)}),isOAuthToken:!0};const l=aa(e),h={};o&&l.sendSessionAffinityHeaders&&(h["openrouter"===l.sessionAffinityFormat?"x-session-id":"x-session-affinity"]=o);const d=ca(s(e,c),{accept:"application/json","anthropic-dangerous-direct-browser-access":"true"},h,e.headers,n);if(a){const t=JSON.stringify([e.baseUrl,a]);return ua?.key===t&&ua.fetch===r||(ua={key:t,fetch:r,client:new pa({apiKey:null,authToken:null,config:a,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:r})}),{client:ua.client.withOptions({defaultHeaders:d}),isOAuthToken:!1}}return{client:new pa({apiKey:t??null,authToken:null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:r,defaultHeaders:d}),isOAuthToken:!1}}(e,t,n?.headers,n?.fetch,i,a,r,n?.identity);c=l.client,h=l.isOAuthToken}const p={...n?.signal?{signal:n.signal}:{},...void 0!==n?.timeoutMs?{timeout:n.timeoutMs}:{},maxRetries:0};let g,b=!1;for(;;){n?.signal?.throwIfAborted();const s=va(e,o,h,n,b);s.providerThinkingLevel&&(t.providerThinkingLevel=s.providerThinkingLevel);let i=s.params;const a=await(n?.onPayload?.(i,e));void 0!==a&&(i={...a,stream:!0});try{g=await S(()=>c.beta.messages.create(i,p).asResponse(),{maxRetries:n?.maxRetries,maxRetryDelayMs:n?.maxRetryDelayMs,signal:n?.signal});break}catch(r){if(n?.signal?.aborted||b||!s.hasPreferredStrictTools||!(r instanceof Qo.APIError)||400!==r.status||"invalid_request_error"!==r.type||!["The compiled grammar is too large","Too many strict tools (","Schemas contains too many parameters with union types ("].some(e=>r.message.includes(e)))throw r;b=!0,f(t,{type:"anthropic_strict_tools_fallback",timestamp:Date.now(),error:{message:r.message},details:{reason:"strict_tool_limits_exceeded"}})}}await(n?.onResponse?.({status:g.status,headers:k(g.headers)},e)),i.push({type:"start",partial:t});const x=t.content;for await(const s of async function*(e,t){if(!e.body)throw new Error("Attempted to iterate over an Anthropic response with no body");let s=!1,n=!1;for await(const i of async function*(e,t){const s=e.getReader(),n=new TextDecoder,r={event:null,data:[],raw:[]};let i="";try{for(;;){if(t?.aborted)throw new Error("Request was aborted");const{value:e,done:o}=await s.read();if(o)break;i+=n.decode(e,{stream:!0});let a=wa(i);for(;a;){i=a.rest;const e=_a(a.line,r);e&&(yield e),a=wa(i)}}i+=n.decode();let e=wa(i);for(;e;){i=e.rest;const t=_a(e.line,r);t&&(yield t),e=wa(i)}if(i.length>0){const e=_a(i,r);e&&(yield e)}const o=ma(r);o&&(yield o)}finally{s.releaseLock()}}(e.body,t)){if("error"===i.event)throw new Error(i.data);if(ga.has(i.event??""))try{const e=_(i.data);"message_start"===e.type?s=!0:"message_stop"===e.type&&(n=!0),yield e}catch(r){const t=r instanceof Error?r.message:String(r);throw new Error(`Could not parse Anthropic SSE event ${i.event}: ${t}; data=${i.data}; raw=${i.raw.join("\\n")}`)}}if(s&&!n)throw new Error("Anthropic stream ended before message_stop")}(g,n?.signal))if(await(n?.onProviderStreamEvent?.(s,e)),"message_start"===s.type){t.responseId=s.message.id;const n=s.message.input_transformations;Array.isArray(n)&&(d=n);const r=s.message.model;r!==e.id&&(t.responseModel=r);const i=r===e.id?void 0:e.compat?.allowedFallbackModels?.find(t=>t.provider===e.provider&&t.model===r)?.cost;u=i?{...e,id:r,cost:i}:e,t.usage.input=s.message.usage.input_tokens||0,t.usage.output=s.message.usage.output_tokens||0,t.usage.cacheRead=s.message.usage.cache_read_input_tokens||0,t.usage.cacheWrite=s.message.usage.cache_creation_input_tokens||0,t.usage.cacheWrite1h=s.message.usage.cache_creation?.ephemeral_1h_input_tokens||0,t.usage.totalTokens=t.usage.input+t.usage.output+t.usage.cacheRead+t.usage.cacheWrite,a(u,t.usage)}else if("content_block_start"===s.type){if("fallback"===s.content_block.type){if(t.content.length>0)throw new Error("Anthropic performed an unsupported mid-output model fallback");continue}if("text"===s.content_block.type){const e={type:"text",text:s.content_block.text??"",index:s.index};t.content.push(e),i.push({type:"text_start",contentIndex:t.content.length-1,partial:t})}else if("thinking"===s.content_block.type){const e={type:"thinking",thinking:s.content_block.thinking??"",thinkingSignature:s.content_block.signature??"",index:s.index};t.content.push(e),i.push({type:"thinking_start",contentIndex:t.content.length-1,partial:t})}else if("redacted_thinking"===s.content_block.type){const e={type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:s.content_block.data,redacted:!0,index:s.index};t.content.push(e),i.push({type:"thinking_start",contentIndex:t.content.length-1,partial:t})}else if("tool_use"===s.content_block.type){const e={type:"toolCall",id:s.content_block.id,name:h?na(s.content_block.name,l):s.content_block.name,arguments:s.content_block.input??{},partialJson:"",index:s.index};t.content.push(e),i.push({type:"toolcall_start",contentIndex:t.content.length-1,partial:t})}}else if("content_block_delta"===s.type){if("text_delta"===s.delta.type){const e=x.findIndex(e=>e.index===s.index),n=x[e];n&&"text"===n.type&&(n.text+=s.delta.text,i.push({type:"text_delta",contentIndex:e,delta:s.delta.text,partial:t}))}else if("thinking_delta"===s.delta.type){const e=x.findIndex(e=>e.index===s.index),n=x[e];n&&"thinking"===n.type&&(n.thinking+=s.delta.thinking,i.push({type:"thinking_delta",contentIndex:e,delta:s.delta.thinking,partial:t}))}else if("input_json_delta"===s.delta.type){const e=x.findIndex(e=>e.index===s.index),n=x[e];n&&"toolCall"===n.type&&(n.partialJson+=s.delta.partial_json,n.arguments=m(n.partialJson),i.push({type:"toolcall_delta",contentIndex:e,delta:s.delta.partial_json,partial:t}))}else if("signature_delta"===s.delta.type){const e=x[x.findIndex(e=>e.index===s.index)];e&&"thinking"===e.type&&(e.thinkingSignature=e.thinkingSignature||"",e.thinkingSignature+=s.delta.signature)}}else if("content_block_stop"===s.type){const e=x.findIndex(e=>e.index===s.index),n=x[e];n&&(delete n.index,"text"===n.type?i.push({type:"text_end",contentIndex:e,content:n.text,partial:t}):"thinking"===n.type?i.push({type:"thinking_end",contentIndex:e,content:n.thinking,partial:t}):"toolCall"===n.type&&(Object.assign(n,y(n.partialJson)),delete n.partialJson,i.push({type:"toolcall_end",contentIndex:e,toolCall:n,partial:t})))}else if("message_delta"===s.type){const e=s.input_transformations;if(Array.isArray(e)&&(d=e),s.delta.stop_reason){t.rawStopReason=s.delta.stop_reason;const e=Ta(s.delta.stop_reason,s.delta.stop_details);t.stopReason=e.stopReason,e.errorMessage&&(t.errorMessage=e.errorMessage)}if(s.usage){null!=s.usage.input_tokens&&(t.usage.input=s.usage.input_tokens),null!=s.usage.output_tokens&&(t.usage.output=s.usage.output_tokens),null!=s.usage.cache_read_input_tokens&&(t.usage.cacheRead=s.usage.cache_read_input_tokens),null!=s.usage.cache_creation_input_tokens&&(t.usage.cacheWrite=s.usage.cache_creation_input_tokens);const e=s.usage.cache_creation;null!=e?.ephemeral_1h_input_tokens&&(t.usage.cacheWrite1h=e.ephemeral_1h_input_tokens);const n=s.usage.output_tokens_details?.thinking_tokens;null!=n&&(t.usage.reasoning=n)}t.usage.totalTokens=t.usage.input+t.usage.output+t.usage.cacheRead+t.usage.cacheWrite,a(u,t.usage)}if(n?.signal?.aborted)throw new Error("Request was aborted");if("pending"===t.stopReason)throw new Error("Anthropic stream ended without a stop reason");if("aborted"===t.stopReason||"error"===t.stopReason)throw new Error(t.errorMessage||"An unknown error occurred");d&&d.length>0&&f(t,{type:"anthropic_input_transformations",timestamp:Date.now(),details:{transformations:d.map(e=>({type:e.type??void 0,path:e.path??void 0,reason:e.reason??void 0}))}}),i.push({type:"done",reason:t.stopReason,message:t}),i.end()}catch(r){for(const e of t.content)delete e.index,delete e.partialJson;t.stopReason=n?.signal?.aborted?"aborted":"error",t.errorMessage=r instanceof Error?r.message:JSON.stringify(r),i.push({type:"error",reason:t.stopReason,error:t}),i.end()}})(),i},ba=(e,t,s)=>{fa(e,s?.apiKey,s?.headers,s?.env)||da(e.provider,s?.apiKey,s?.headers);const n={...A(e,t,s,s?.apiKey),toolChoice:s?.toolChoice};if(!s?.reasoning)return ya(e,t,{...n,thinkingEnabled:!1});if(!0===e.compat?.forceAdaptiveThinking){const r=function(e,t){const s=t?e.thinkingLevelMap?.[t]:void 0;if("string"==typeof s)return s;switch(t){case"minimal":case"low":return"low";case"medium":return"medium";default:return"high"}}(e,s.reasoning);return ya(e,t,{...n,thinkingEnabled:!0,effort:r})}const r=E(n.maxTokens,e.maxTokens,s.reasoning,s.thinkingBudgets),i=x(e,t,r.maxTokens);return ya(e,t,{...n,maxTokens:i,thinkingEnabled:!0,thinkingBudgetTokens:Math.min(r.thinkingBudget,Math.max(0,i-1024))})};function va(e,t,s,r,o=!1){const{cacheControl:a}=function(e,t,s){const n=ea(t,s);if("none"===n)return{retention:n};const r="long"===n&&aa(e).supportsLongCacheRetention?"1h":void 0;return{retention:n,cacheControl:{type:"ephemeral",...r&&{ttl:r}}}}(e,r?.cacheRetention,r?.env),l=aa(e),h=i(t.messages),d=h?g(h):"",u=T(t.messages,e,ka),p=h?u.slice(1):u;let f=!1;const m=(e,t)=>{const n=function(e,t,s,n,r,i=!1){return e?e.map((o,a)=>{const c=o.constrainedSampling,l=i&&c&&"json_schema"===c.type&&"prefer"===c.strict?void 0:$(o,n,$a),h=R(o,l),d=h,u={type:"object",properties:d.properties??{},required:d.required??[]},p=!0===l?{...h,...u}:u;return{name:t?sa(o.name):o.name,description:o.description,...s?{eager_input_streaming:!0}:{},...!0===l?{strict:!0}:{},input_schema:p,...r&&a===e.length-1?{cache_control:r}:{}}}):[]}(e,s,l.supportsEagerToolInputStreaming,l.supportsStrictTools,t,o);return n.some((t,s)=>{const n=e[s].constrainedSampling;return!0===t.strict&&n&&"json_schema"===n.type&&"prefer"===n.strict})&&(f=!0),n},_=h?.toolsAdded??[],w=l.supportsMidConvoSystemMessages&&l.supportsMidConvoToolChanges&&_.length>0,y=e.reasoning&&!1===r?.thinkingEnabled&&null!==e.thinkingLevelMap?.off,b=!0===e.compat?.supportsMidConvoEffort&&!y,v=function(e,t,s,r=!1,i,o){const a=[],c=/* @__PURE__ */new Map,l=[],h=()=>{a.push(...l),l.length=0};for(let d=0;d<e.length;d++){const s=e[d];if("system"===s.role){const e=n(s),r=[];if(e.length>0&&r.push({type:"text",text:I(e)}),o){const e=s.toolsAdded??[],n=new Set(e.map(e=>e.name));for(const i of s.toolsRemoved??[])n.has(i.name)||r.push({type:"tool_removal",tool:{type:"tool_reference",name:t?sa(i.name):i.name}});for(const t of o(e))r.push({type:"tool_addition",tool:{type:"tool_definition",definition:t}})}r.length>0&&l.push({role:"system",content:r})}else if("user"===s.role)if("string"==typeof s.content)s.content.trim().length>0&&a.push({role:"user",content:I(s.content)});else{const e=s.content.map(e=>"text"===e.type?{type:"text",text:I(e.text)}:ra(e)).filter(e=>"text"!==e.type||e.text.trim().length>0);if(0===e.length)continue;a.push({role:"user",content:e})}else if("assistant"===s.role){h();const e=[];for(const i of s.content)if("text"===i.type){if(0===i.text.trim().length)continue;e.push({type:"text",text:I(i.text)})}else if("thinking"===i.type){if(i.redacted){e.push({type:"redacted_thinking",data:i.thinkingSignature});continue}const t=i.thinkingSignature,s=!!t&&t.trim().length>0;if(0===i.thinking.trim().length&&!s)continue;s?e.push({type:"thinking",thinking:I(i.thinking),signature:t}):e.push(r?{type:"thinking",thinking:I(i.thinking),signature:""}:{type:"text",text:I(i.thinking)})}else"toolCall"===i.type&&e.push({type:"tool_use",id:i.id,name:t?sa(i.name):i.name,input:i.arguments??{}});if(0===e.length)continue;const n=a.length;a.push({role:"assistant",content:e}),void 0!==i&&"anthropic-messages"===s.api&&s.provider===i&&xa(s.providerThinkingLevel)&&c.set(n,s.providerThinkingLevel)}else if("toolResult"===s.role){const t=[],s=[];let n=d;for(;n<e.length&&"toolResult"===e[n].role;){const r=e[n],i=M(r);t.push(Sa(r,i?.content)),i&&s.push({type:"text",text:i.caption},...i.images.map(ra)),n++}d=n-1,a.push({role:"user",content:[...t,...s]})}}if(h(),s&&a.length>0){const e=a[a.length-1];if("user"===e.role||"system"===e.role)if(Array.isArray(e.content)){const t=e.content[e.content.length-1];!t||"text"!==t.type&&"image"!==t.type&&"tool_result"!==t.type&&"tool_addition"!==t.type&&"tool_removal"!==t.type||(t.cache_control=s)}else"string"==typeof e.content&&(e.content=[{type:"text",text:e.content,cache_control:s}])}return{messages:a,assistantLevels:c}}(p,s,a,l.allowEmptySignature,b?e.provider:void 0,w?m:void 0),k=r?.effort??"high",S=function(e,t,s,n,r){let i;for(const a of[e.headers,r?.headers])for(const[e,t]of Object.entries(a??{}))"anthropic-beta"===e.toLowerCase()&&(i=t);if(null===i)return[];if(void 0!==i)return[...new Set(i.split(",").map(e=>e.trim()).filter(e=>e.length>0))];const o=[];return s&&o.push("claude-code-20250219","oauth-2025-04-20"),function(e,t){return c(t.messages).length>0&&!aa(e).supportsEagerToolInputStreaming}(e,t)&&o.push("fine-grained-tool-streaming-2025-05-14"),e.reasoning&&!0===r?.thinkingEnabled&&(r.interleavedThinking??!0)&&!0!==e.compat?.forceAdaptiveThinking&&o.push("interleaved-thinking-2025-05-14"),function(e){return(e.compat?.allowedFallbackModels?.length??0)>0}(e)&&o.push("server-side-fallback-2026-07-01"),!0===e.compat?.supportsMidConvoEffort&&o.push("mid-conversation-output-config-2026-07-01","thinking-binding-controls-2026-08-01"),n&&o.push("inline-tools-2026-09-15"),[...new Set(o)]}(e,t,s,w,r),x={model:e.id,messages:b?Ra(v,k):v.messages,max_tokens:r?.maxTokens??e.maxTokens,stream:!0,...S.length>0?{betas:S}:{}};s?(x.system=[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude.",...a?{cache_control:a}:{}}],d&&x.system.push({type:"text",text:I(d),...a?{cache_control:a}:{}})):d&&(x.system=[{type:"text",text:I(d),...a?{cache_control:a}:{}}]),void 0!==r?.temperature&&!r?.thinkingEnabled&&!0!==e.compat?.supportsMidConvoEffort&&l.supportsTemperature&&(x.temperature=r.temperature);const A=l.supportsCacheControlOnTools?a:void 0;if(w)x.tools=[...m(_,A),oa];else{const e=c(t.messages);e.length>0&&(x.tools=m(e,A))}if(y)x.thinking={type:"disabled"};else if(b)x.thinking={type:"adaptive",display:r?.thinkingDisplay??"summarized",block_binding:{prefix_mismatch_behavior:"drop_block"}},x.output_config={effort:"high"};else if(e.reasoning&&r?.thinkingEnabled){const t=r.thinkingDisplay??"summarized";!0===e.compat?.forceAdaptiveThinking?(x.thinking={type:"adaptive",display:t},r.effort&&(x.output_config={effort:r.effort})):x.thinking={type:"enabled",budget_tokens:r.thinkingBudgetTokens||1024,display:t}}if(r?.metadata){const e=r.metadata.user_id;"string"==typeof e&&(x.metadata={user_id:e})}r?.toolChoice&&("string"==typeof r.toolChoice?x.tool_choice={type:r.toolChoice}:x.tool_choice=r.toolChoice);const E=e.compat?.allowedFallbackModels;return E&&E.length>0&&(x.fallbacks=E.map(e=>({model:e.model}))),{params:x,hasPreferredStrictTools:f,providerThinkingLevel:b?k:void 0}}function ka(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function Sa(e,t=e.content){return{type:"tool_result",tool_use_id:e.toolCallId,content:ia(t),is_error:e.isError}}function xa(e){return"low"===e||"medium"===e||"high"===e||"xhigh"===e||"max"===e}function Ra(e,t){const s=[];for(let n=0;n<e.messages.length;n++){const t=e.assistantLevels.get(n);void 0!==t&&s.push({role:"system",content:[],output_config:{effort:t}}),s.push(e.messages[n])}return s.push({role:"system",content:[],output_config:{effort:t}}),s}var Ia=/* @__PURE__ */new Set(["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","maxItems","uniqueItems","minContains","maxContains","minProperties","maxProperties"]),Aa=/* @__PURE__ */new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),$a=(e,t)=>!(!Ia.has(e)&&("minItems"===e?0===t||1===t:"format"!==e||"string"==typeof t&&Aa.has(t)));function Ta(e,t){switch(e){case"end_turn":case"pause_turn":case"stop_sequence":return{stopReason:"stop"};case"max_tokens":return{stopReason:"length"};case"tool_use":return{stopReason:"toolUse"};case"refusal":return{stopReason:"error",errorMessage:t?.explanation||"The model refused to complete the request"};case"sensitive":return{stopReason:"error",errorMessage:"Provider stopped with: sensitive"};default:throw new Error(`Unhandled stop reason: ${e}`)}}export{V as n,C as r,ya as stream,ba as streamSimple,Zo as t};