@hintergrund/ui 0.3.24 → 0.3.25

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-WNHmnFyz.js";import{E 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-CrhAF8vt.js";import{a as m,i as _,n as w,o as y,r as b,t as v}from"./github-copilot-headers-CdUV5uSi.js";import{n as k,o as S,t as x}from"./provider-retry-B2k3qccC.js";import{n as I,t as R}from"./openrouter-cost-BcsrXcCZ.js";import{_ as A,a as $,g as T,i as E,m as M,n as O,p as P,r as C,t as L}from"./transform-messages-K0xRLnN6.js";var N=/* @__PURE__ */new Set;function q(e){return N.add(e),()=>{N.delete(e)}}function W(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var j=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)},U=/* @__PURE__ */(()=>{class e extends Error{}return e})(),D=class e extends U{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 z({message:n,cause:j(s)});const i=s,o=i?.error?.type;return 400===t?new K(t,i,n,r,o):401===t?new J(t,i,n,r,o):403===t?new V(t,i,n,r,o):404===t?new X(t,i,n,r,o):409===t?new G(t,i,n,r,o):422===t?new Y(t,i,n,r,o):429===t?new Q(t,i,n,r,o):t>=500?new Z(t,i,n,r,o):new e(t,i,n,r,o)}},H=class extends D{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},z=class extends D{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},F=class extends z{constructor({message:e}={}){super({message:e??"Request timed out."})}},B=class extends U{constructor(e,{cause:t}={}){super(e??"Retryable error."),void 0!==t&&(this.cause=t)}},K=class extends D{},J=class extends D{},V=class extends D{},X=class extends D{},G=class extends D{},Y=class extends D{},Q=class extends D{},Z=class extends D{},ee=5e3;function te(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 se(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 ne=/^[a-z][a-z0-9+.-]*:/i,re=e=>(re=Array.isArray)(e),ie=re;function oe(e){return"object"!=typeof e?{}:e??{}}function ae(e){if(!e)return!0;for(const t in e)return!1;return!0}function ce(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}var le,he=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new U(`${e} must be an integer`);if(t<0)throw new U(`${e} must be a positive integer`);return t},de=e=>{try{return JSON.parse(e)}catch(t){return}},ue=(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})}),pe="0.129.0",fe=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",ge=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",me=()=>le??(le=(()=>{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":pe,"X-Stainless-OS":ge(Deno.build.os),"X-Stainless-Arch":fe(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":pe,"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":pe,"X-Stainless-OS":ge(globalThis.process.platform??"unknown"),"X-Stainless-Arch":fe(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":pe,"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":pe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}})()),_e=/* @__PURE__ */new WeakMap,we="function"==typeof globalThis.FinalizationRegistry?new globalThis.FinalizationRegistry(e=>ye(e)):null;function ye(e){const t=_e.get(e);t&&(_e.delete(e),we?.unregister(e),t())}function be(...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 ve(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return be({start(){},async pull(e){const{done:s,value:n}=await t.next();s?e.close():e.enqueue(n)},async cancel(){await(t.return?.())}})}function ke(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 Se=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),xe="RFC3986",Ie=e=>String(e),Re={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:Ie},Ae=(e,t)=>(Ae=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty))(e,t),$e=/* @__PURE__ */(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),Te=1024;function Ee(e,t){if(re(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}var Me,Oe={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},Pe=function(e,t){Array.prototype.push.apply(e,re(t)?t:[t])},Ce={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+=Te){const e=i.length>=Te?i.slice(a,a+Te):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]=$e[n]:n<2048?t[t.length]=$e[192|n>>6]+$e[128|63&n]:n<55296||n>=57344?t[t.length]=$e[224|n>>12]+$e[128|n>>6&63]+$e[128|63&n]:(s+=1,n=65536+((1023&n)<<10|1023&e.charCodeAt(s)),t[t.length]=$e[240|n>>18]+$e[128|n>>12&63]+$e[128|n>>6&63]+$e[128|63&n])}o+=t.join("")}return o},encodeValuesOnly:!1,format:xe,formatter:Ie,indices:!1,serializeDate:e=>(Me??(Me=Function.prototype.call.bind(Date.prototype.toISOString)))(e),skipNulls:!1,strictNullHandling:!1},Le={};function Ne(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(Le))&&!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(Le)&&(b=0)}if("function"==typeof l?w=l(t,w):w instanceof Date?w=u?.(w):"comma"===s&&re(w)&&(w=Ee(w,function(e){return e instanceof Date?u?.(e):e})),null===w){if(i)return c&&!g?c(t,Ce.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,Ce.encoder,m,"key",p);return[f?.(e)+"="+f?.(c(w,Ce.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&&re(w))g&&c&&(w=Ee(w,c)),x=[{value:w.length>0?w.join(",")||null:void 0}];else if(re(l))x=l;else{const e=Object.keys(w);x=h?e.sort(h):e}const I=a?String(t).replace(/\./g,"%2E"):String(t),R=n&&re(w)&&1===w.length?I+"[]":I;if(r&&re(w)&&0===w.length)return R+"[]";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=re(w)?"function"==typeof s?s(R,v):R:R+(d?"."+v:"["+v+"]");_.set(e,b);const I=/* @__PURE__ */new WeakMap;I.set(Le,_),Pe(S,Ne(y,k,s,n,r,i,o,a,"comma"===s&&g&&re(w)?null:c,l,h,d,u,p,f,g,m,I))}return S}var qe="/v1/oauth/token",We="oauth-2025-04-20",je=1<<20;function Ue(e){if(!e)return;let t;try{t=new URL(e)}catch(n){throw new Je(`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 Je(`Refusing to send credential over non-https token endpoint "${e}"`)}async function De(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>je){const e=je-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 Je(`Token endpoint returned non-JSON response (status ${e.status})`,e.status,Fe(s),t)}if(!n.access_token)throw new Je(`Token endpoint response missing access_token: ${JSON.stringify(Fe(n))}`,e.status,Fe(n),t);if(n.token_type&&"bearer"!==n.token_type.toLowerCase())throw new Je(`Token endpoint response: unsupported token_type "${n.token_type}" (want Bearer)`,e.status,Fe(n),t);return n}var He=2e3,ze=/* @__PURE__ */new Set(["error","error_description","error_uri"]);function Fe(e){if(null==e)return e;if("string"==typeof e){let t;try{t=JSON.parse(e)}catch{return e.length<=He?e:e.slice(0,He)+`... <${e.length-He} more chars>`}return JSON.stringify(Fe(t))}if("object"==typeof e&&!Array.isArray(e)){const t={};for(const[s,n]of Object.entries(e))ze.has(s)&&(t[s]=n);return t}return null}async function Be(e,t=e=>{}){if("undefined"==typeof process)return;const{fs:s}=await(import("./node.browser-Aw6ESngp.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 Je(`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 Je(`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 Ke(e,t){const{fs:s,path:n}=await(import("./node.browser-Aw6ESngp.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 Je=class extends U{constructor(e,t=null,s=null,n=null){super(e),this.statusCode=t,this.body=s,this.requestId=n}};function Ve(){return Math.floor(Date.now()/1e3)}var Xe,Ge,Ye=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-Ve();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||Ve()-this.lastAdvisoryError<5||this.doRefresh().catch(e=>{this.lastAdvisoryError=Ve(),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}},Qe=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 Ze(e){let t;return(Xe??(t=new globalThis.TextEncoder,Xe=t.encode.bind(t)))(e)}function et(e){let t;return(Ge??(t=new globalThis.TextDecoder,Ge=t.decode.bind(t)))(e)}var tt={off:0,error:200,warn:300,info:400,debug:500},st=(e,t,s)=>{var n,r;if(e)return n=tt,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(tt))}`)};function nt(){}function rt(e,t,s){return!t||tt[e]>tt[s]?nt:t[e].bind(t)}var it,ot,at={error:nt,warn:nt,info:nt,debug:nt},ct=/* @__PURE__ */new WeakMap;function lt(e,t){const s=ct.get(e);if(s&&s[0]===t)return s[1];const n={error:rt("error",e,t),warn:rt("warn",e,t),info:rt("info",e,t),debug:rt("debug",e,t)};return ct.set(e,[t,n]),n}function ht(e){const t=e.logger,s=e.logLevel??"off";return t?lt(t,s):at}function dt(){const e=Qe("ANTHROPIC_LOG");return ot&&e===it||(it=e,ot=lt(console,st(e,"process.env['ANTHROPIC_LOG']",lt(console,"warn"))??"warn")),ot}function ut(e,t,s){e.debug!==nt&&e.debug(t,pt(s))}var pt=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),ft=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return ft=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))},gt=/^[A-Za-z0-9_.-]+$/;function mt(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(!gt.test(e))throw new Error(`profile name "${e}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var _t,wt,yt=async(e,t)=>{if(e?.authentication.credentials_path)return e.authentication.credentials_path;const s=await bt();if(!s)return null;const n=t??await kt();if(!n)return null;mt(n);const{path:r}=await(import("./node.browser-Aw6ESngp.js"));return r.join(s,"credentials",`${n}.json`)},bt=async()=>{if(!vt())return null;const{path:e}=await(import("./node.browser-Aw6ESngp.js")),t=Qe("ANTHROPIC_CONFIG_DIR");if(t)return t;if("Windows"===me()["X-Stainless-OS"]){const t=Qe("APPDATA");if(t)return e.join(t,"Anthropic");const s=Qe("USERPROFILE");return s?e.join(s,"AppData","Roaming","Anthropic"):null}const s=Qe("XDG_CONFIG_HOME");if(s)return e.join(s,"anthropic");const n=Qe("HOME");return n?e.join(n,".config","anthropic"):null},vt=()=>{const e=me()["X-Stainless-Runtime"];return"node"===e||"deno"===e},kt=async()=>{const e=await bt();if(!e)return null;const t=Qe("ANTHROPIC_PROFILE");if(t)return t;const{fs:s,path:n}=await(import("./node.browser-Aw6ESngp.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 St(e){if(!e)throw new U("Identity token file path is empty");return async()=>{const{fs:t}=await(import("./node.browser-Aw6ESngp.js"));let s;try{s=await t.promises.readFile(e,"utf-8")}catch(r){throw new U(`Failed to read identity token file at ${e}: ${r}`)}const n=s.trim();if(!n)throw new U(`Identity token file at ${e} is empty`);return n}}function xt(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 Je(`identity_token.source "${t}" is not supported by this SDK version (only "file")`);if(!e.identity_token.path)throw new Je('identity_token.source "file" requires a non-empty path');return St(e.identity_token.path)}const t=Qe("ANTHROPIC_IDENTITY_TOKEN_FILE");if(t)return St(t);const s=Qe("ANTHROPIC_IDENTITY_TOKEN");return s?function(e){if(!e)throw new U("Identity token value is empty");return()=>e}(s):null}(r);if(!i)throw new Je("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 Je("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 Je("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");const o=function(e){return async()=>{Ue(e.baseURL);const t=await e.identityTokenProvider();if(t.length>16384)throw new Je(`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}${qe}`;let r;try{r=await e.fetch(n,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${We},oidc-federation-2026-04-01`,"User-Agent":e.userAgent||"anthropic-sdk-typescript/0.129.0 oidcFederationProvider"},body:JSON.stringify(s)})}catch(c){throw new Je(`Failed to reach token endpoint ${n}: ${c}`)}const i=r.headers.get("Request-Id");if(!r.ok){const t=Fe(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 Je(`Token exchange failed with status ${r.status}${i?` (request-id ${i})`:""}: ${t}${s}`,r.status,t,i)}const o=await De(r,i),a=Number(o.expires_in);if(!Number.isFinite(a))throw new Je(`Token endpoint response missing required fields: ${JSON.stringify(Fe(o))}`,r.status,Fe(o),i);return{token:o.access_token,expiresAt:Ve()+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-Aw6ESngp.js"));let o;await Be(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||Ve()<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 Ke(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 Je("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-Aw6ESngp.js"));let n,r;await Be(e.credentialsPath,e.onSafetyWarning);try{n=await s.promises.readFile(e.credentialsPath,"utf-8")}catch(m){throw new Je(`Credentials file not found at ${e.credentialsPath}: ${m}`)}try{r=JSON.parse(n)}catch(m){throw new Je(`Credentials file at ${e.credentialsPath} is not valid JSON: ${m}`)}const i=r.access_token;if(!i)throw new Je(`Credentials file at ${e.credentialsPath} must include 'access_token'`);const o=r.expires_at;if(!t?.forceRefresh&&(null==o||Ve()<o-30))return{token:i,expiresAt:o??null};const a=r.refresh_token;if(!e.clientId||!a)throw new Je(`Access token at ${e.credentialsPath} has expired and no refresh is available (client_id ${e.clientId?"set":"empty"}, refresh_token ${a?"set":"empty"})`);Ue(e.baseURL);const c={grant_type:"refresh_token",refresh_token:a,client_id:e.clientId},l=`${e.baseURL}${qe}`;let h;try{h=await e.fetch(l,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":We,"User-Agent":e.userAgent||"anthropic-sdk-typescript/0.129.0 userOAuthProvider"},body:JSON.stringify(c)})}catch(m){throw new Je(`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 Je(`User OAuth refresh failed (HTTP ${h.status}): ${Fe(e)}`,h.status,Fe(e),d)}const u=await De(h,d),p=Number(u.expires_in);if(!Number.isFinite(p))throw new Je(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(Fe(u))}`,h.status,Fe(u),d);const f=Ve()+p,g=u.refresh_token||a;return await Ke(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 Je(`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 It,Rt=/* @__PURE__ */(()=>{class e{constructor(){_t.set(this,void 0),wt.set(this,void 0),te(this,_t,/* @__PURE__ */new Uint8Array,"f"),te(this,wt,null,"f")}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?Ze(e):e;te(this,_t,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}([se(this,_t,"f"),t]),"f");const s=[];let n;for(;null!=(n=At(se(this,_t,"f"),se(this,wt,"f")));){if(n.carriage&&null==se(this,wt,"f")){te(this,wt,n.index,"f");continue}if(null!=se(this,wt,"f")&&(n.index!==se(this,wt,"f")+1||n.carriage)){s.push(et(se(this,_t,"f").subarray(0,se(this,wt,"f")-1))),te(this,_t,se(this,_t,"f").subarray(se(this,wt,"f")),"f"),te(this,wt,null,"f");continue}const e=null!==se(this,wt,"f")?n.preceding-1:n.preceding,t=et(se(this,_t,"f").subarray(0,e));s.push(t),te(this,_t,se(this,_t,"f").subarray(n.index),"f"),te(this,wt,null,"f")}return s}flush(){return se(this,_t,"f").length?this.decode("\n"):[]}}return _t=/* @__PURE__ */new WeakMap,wt=/* @__PURE__ */new WeakMap,e.NEWLINE_CHARS=/* @__PURE__ */new Set(["\n","\r"]),e.NEWLINE_REGEXP=/\r\n|[\n\r]/g,e})();function At(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 $t=/* @__PURE__ */(()=>{class e{constructor(e,t,s){this.iterator=e,It.set(this,void 0),this.controller=t,te(this,It,s,"f")}static rawEvents(e,t=new AbortController){return Tt(e,t)}static fromSSEResponse(t,s,n){let r=!1;const i=n?ht(n):console;return new e(async function*(){if(r)throw new U("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let e=!1;try{for await(const e of Tt(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=de(e.data)??e.data,n=s?.error?.type;throw new D(void 0,s,void 0,t.headers,n)}}e=!0}catch(n){if(W(n))return;throw n}finally{e||s.abort(),ye(s)}},s,n)}static fromReadableStream(t,s,n){let r=!1;return new e(async function*(){if(r)throw new U("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 Rt,s=ke(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(W(n))return;throw n}finally{e||s.abort(),ye(s)}},s,n)}[(It=/* @__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,se(this,It,"f")),new e(()=>r(s),this.controller,se(this,It,"f"))]}toReadableStream(){const e=this;let t;return be({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=Ze(JSON.stringify(s)+"\n");e.enqueue(r)}catch(s){e.error(s)}},async cancel(){await(t.return?.())}})}}return e})();async function*Tt(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new U("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 U("Attempted to iterate over a response with no body")}const s=new Et,n=new Rt,r=ke(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 Et=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 Mt(e,t){const{response:s,requestLogID:n,retryOfRequestLogID:r,startTime:i}=t,o=await(async()=>{if(t.options.stream)return ht(e).debug("response",s.status,s.url,s.headers,s.body),$t.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 Ot(await s.json(),s)}return await s.text()})().finally(()=>{t.options.stream||t.options.__binaryResponse||ye(t.controller)});return ut(ht(e),`[${n}] response parsed`,{retryOfRequestLogID:r,url:s.url,status:s.status,body:o,durationMs:Date.now()-i}),o}function Ot(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 Pt,Ct=/* @__PURE__ */new WeakSet;function Lt(e){return"object"==typeof e&&null!==e&&Ct.has(e)}function Nt(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=j(n);throw Ct.add(e),e}};const i=function(e,t){const s=/* @__PURE__ */new WeakMap;return{options:e,logger:t?ht(t):dt(),parse(n){if(e?.stream&&n.ok)return qt(n,e,t);let r=s.get(n);return r||(r=qt(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 U("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 qt(e,t,s){if(e.bodyUsed||e.body?.locked)throw new U("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 $t.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 Ot(await e.clone().json(),e)}return await e.clone().text()}var Wt,jt=/* @__PURE__ */(()=>{class e extends Promise{constructor(e,t,s=Mt){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=s,Pt.set(this,void 0),te(this,Pt,e,"f")}_thenUnwrap(t){return new e(se(this,Pt,"f"),this.responsePromise,async(e,s)=>Ot(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(se(this,Pt,"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 Pt=/* @__PURE__ */new WeakMap,e})(),Ut=/* @__PURE__ */(()=>{class e{constructor(e,t,s,n){Wt.set(this,void 0),te(this,Wt,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 U("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await se(this,Wt,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Wt=/* @__PURE__ */new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}return e})(),Dt=/* @__PURE__ */(()=>{class e extends jt{constructor(e,t,s){super(e,t,async(e,t)=>new s(e,t.response,await Mt(e,t),t.options))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}return e})(),Ht=class extends Ut{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:{...oe(this.options.query),before_id:e}}:null}const e=this.last_id;return e?{...this.options,query:{...oe(this.options.query),after_id:e}}:null}},zt=class extends Ut{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:{...oe(this.options.query),page:e}}:null}},Ft=class extends Ut{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:{...oe(this.options.query),page:e}}:null}},Bt=()=>{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 Kt(e,t,s){return Bt(),new File(e,t??"",s)}function Jt(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 Vt=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],Xt=async(e,t,s=!0)=>({...e,body:await Yt(e.body,t,s)}),Gt=/* @__PURE__ */new WeakMap,Yt=async(e,t,s=!0)=>{if(!(await function(e){const t="function"==typeof e?e:e.fetch,s=Gt.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 Gt.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])=>Qt(n,e,t,s))),n},Qt=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,Kt([await s.blob()],Jt(s,n),r))}else if(Vt(s))e.append(t,Kt([await new Response(ve(s)).blob()],Jt(s,n)));else if(s instanceof Blob){const r="undefined"!=typeof File&&s instanceof File?s.name:Jt(s,n);e.append(t,Kt([s],r,{type:s.type}))}else if(Array.isArray(s))await Promise.all(s.map(s=>Qt(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])=>Qt(e,`${t}[${s}]`,r,n)))}}},Zt=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 es(e,t,s){if(Bt(),e=await e,t||(t=e instanceof File?e.name:Jt(e,!0)),(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&Zt(e))(e))return e instanceof File&&null==t&&null==s?e:Kt([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()),Kt(await ts(n),t,s)}const n=await ts(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 Kt(n,t,s)}async function ts(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Zt(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else{if(!Vt(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 ts(s))}return t}var ss=class{constructor(e){this._client=e}},ns=Symbol.for("brand.privateNullableHeaders");function*rs(e){if(!e)return;if(ns 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():ie(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=ie(n[1])?n[1]:[n[1]];let r=!1;for(const n of t)void 0!==n&&(s&&!r&&(r=!0,yield[e,is]),yield[e,n])}}var is=Symbol("clear"),os=/* @__PURE__ */new Set(["x-stainless-helper"]),as=(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(", ")},cs=e=>{const t=new Headers,s=/* @__PURE__ */new Set;for(const n of e){const e=/* @__PURE__ */new Set;for(const[r,i]of rs(n)){const n=r.toLowerCase();if(os.has(n)){if(i===is)continue;null===i?(t.delete(r),s.add(n)):(t.set(r,as(t.get(r),i)),s.delete(n))}else(i!==is&&e.has(n)||(t.delete(r),e.add(n),i!==is))&&(null===i?(t.delete(r),s.add(n)):(t.append(r,i),s.delete(n)))}}return{[ns]:!0,values:t,nulls:s}};function ls(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var hs=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.create(null)),ds=(e=ls)=>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??hs)??hs)?.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 U(`Path parameters result in path with invalid segments:\n${r.map(e=>e.error).join("\n")}\n${i}\n${t}`)}return i},us=/* @__PURE__ */ds(ls),ps=class extends ss{retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(us`/v1/deployment_runs/${e}?beta=true`,{...s,headers:cs([{"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",zt,{query:r,...t,headers:cs([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}},fs=class extends ss{create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/deployments?beta=true",{body:r,...t,headers:cs([{"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(us`/v1/deployments/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/deployments/${e}?beta=true`,{body:i,...s,headers:cs([{"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",zt,{query:r,...t,headers:cs([{"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(us`/v1/deployments/${e}/archive?beta=true`,{...s,headers:cs([{"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(us`/v1/deployments/${e}/pause?beta=true`,{...s,headers:cs([{"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(us`/v1/deployments/${e}/run?beta=true`,{...s,headers:cs([{"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(us`/v1/deployments/${e}/unpause?beta=true`,{...s,headers:cs([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},gs=class extends ss{create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/dreams?beta=true",{body:r,...t,headers:cs([{"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(us`/v1/dreams/${e}?beta=true`,{...s,headers:cs([{"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",zt,{query:r,...t,headers:cs([{"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(us`/v1/dreams/${e}/archive?beta=true`,{...s,headers:cs([{"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(us`/v1/dreams/${e}/cancel?beta=true`,{...s,headers:cs([{"anthropic-beta":[...n??[],"dreaming-2026-04-21"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},ms="x-stainless-helper",_s="x-stainless-helper-method";function ws(e){return{[ms]:e}}var ys=Symbol("anthropic.sdk.stainlessHelper");function bs(e){return"object"==typeof e&&null!==e&&ys in e}function vs(e,t){const s=/* @__PURE__ */new Set;if(e)for(const n of e)bs(n)&&s.add(n[ys]);if(t)for(const n of t){bs(n)&&s.add(n[ys]);const e=n.content;if(Array.isArray(e))for(const t of e){bs(t)&&s.add(t[ys]);const e=t?.tool?.definition;bs(e)&&s.add(e[ys])}}return Array.from(s)}function ks(e,t){const s=vs(e,t);return 0===s.length?{}:{[ms]:s.join(", ")}}function Ss(e){return bs(e)?{[ms]:e[ys]}:{}}var xs,Is,Rs,As,$s,Ts,Es,Ms,Os,Ps,Cs,Ls,Ns,qs=class extends ss{list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/files?beta=true",zt,{query:r,...t,headers:cs([{...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(us`/v1/files/${e}?beta=true`,{...s,headers:cs([{...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(us`/v1/files/${e}/content?beta=true`,{...s,headers:cs([{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(us`/v1/files/${e}?beta=true`,{...s,headers:cs([{...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",Xt({body:r,...t,headers:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},Ss(r.file),t?.headers])},this._client))}},Ws=class extends ss{retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(us`/v1/models/${e}?beta=true`,{...s,headers:cs([{...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",Ht,{query:r,...t,headers:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}},js=class extends ss{create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/user_profiles?beta=true",{body:r,...t,headers:cs([{"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(us`/v1/user_profiles/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/user_profiles/${e}?beta=true`,{body:i,...s,headers:cs([{"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",zt,{query:r,...t,headers:cs([{"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(us`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...s,headers:cs([{"anthropic-beta":[...n??[],"user-profiles-2026-08-18"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},Us=/* @__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)}}),Ds=/* @__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)}),Hs=/* @__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}}),zs=/* @__PURE__ */t(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Webhook=e.WebhookVerificationError=void 0;var t=Us(),s=Ds(),n=Hs(),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_"}),Fs=zs(),Bs=class extends ss{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 Fs.Webhook(n).verify(e,s),JSON.parse(e)}},Ks=class extends ss{list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(us`/v1/agents/${e}/versions?beta=true`,zt,{query:i,...s,headers:cs([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},Js=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.versions=new Ks(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:cs([{"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(us`/v1/agents/${e}?beta=true`,{query:i,...s,headers:cs([{"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(us`/v1/agents/${e}?beta=true`,{body:i,...s,headers:cs([{"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",zt,{query:r,...t,headers:cs([{"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(us`/v1/agents/${e}/archive?beta=true`,{...s,headers:cs([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Versions=Ks,e})();function Vs(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 Xs(e,t){return e instanceof D&&e.status===t}function Gs(e){return function(e){return e instanceof D&&"number"==typeof e.status&&e.status>=400&&e.status<500}(e)&&!Xs(e,408)&&!Xs(e,409)&&!Xs(e,429)}function Ys(e,t,s){return Math.min(t*2**e,s)}function Qs(e,t){return e+Math.random()*(t-e)}function Zs(e){return e*(1-.25*Math.random())}function en(e,{authToken:t,helper:s}){if(!t)throw new U(`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=cs([o,r,{[ms]:s}]);return e.withOptions({apiKey:null,authToken:t,baseURL:e.baseURL,credentials:void 0,defaultHeaders:a})}var tn=/* @__PURE__ */(()=>{class e{constructor(e){xs.set(this,void 0),Is.set(this,!1),Rs.set(this,void 0),As.set(this,void 0),$s.set(this,void 0),Ts.set(this,void 0),Es.set(this,void 0),Ms.set(this,void 0),Os.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}-${ft()}`:ft()}(),te(this,xs,en(e.client,{authToken:e.environmentKey,helper:"environments-work-poller"}),"f"),te(this,$s,e.autoStop??!0,"f"),te(this,Ts,e.drain??!1,"f"),te(this,Es,void 0===e.blockMs?999:e.blockMs,"f"),te(this,Ms,e.reclaimOlderThanMs??null,"f"),te(this,Os,e.requestOptions,"f"),te(this,Rs,new AbortController,"f"),te(this,As,Vs(e.signal,se(this,Rs,"f")),"f")}get signal(){return se(this,Rs,"f").signal}abort(){se(this,Rs,"f").abort()}async*[(xs=/* @__PURE__ */new WeakMap,Is=/* @__PURE__ */new WeakMap,Rs=/* @__PURE__ */new WeakMap,As=/* @__PURE__ */new WeakMap,$s=/* @__PURE__ */new WeakMap,Ts=/* @__PURE__ */new WeakMap,Es=/* @__PURE__ */new WeakMap,Ms=/* @__PURE__ */new WeakMap,Os=/* @__PURE__ */new WeakMap,Symbol.asyncIterator)](){if(se(this,Is,"f"))throw new U("Cannot iterate over a consumed WorkPoller");te(this,Is,!0,"f");const e=ht(this.client);e.info("poller starting",{component:"work-poller",environment_id:this.environmentId});const t=new Un(e,this.environmentId);try{let n=0;for(;!se(this,Rs,"f").signal.aborted;){let r;try{r=await se(this,xs,"f").beta.environments.work.poll(this.environmentId,{"Anthropic-Worker-ID":this.workerId,...null!==se(this,Es,"f")?{block_ms:se(this,Es,"f")}:{},...null!==se(this,Ms,"f")?{reclaim_older_than_ms:se(this,Ms,"f")}:{}},{headers:cs([se(this,Os,"f")?.headers]),signal:se(this,Rs,"f").signal})}catch(s){if(se(this,Rs,"f").signal.aborted)return;if(Gs(s))throw e.error("poll failed permanently, stopping poller",{error:String(s)}),s;const t=Zs(sn(n));e.warn("poll failed, backing off",{error:String(s),backoff_ms:t}),n++,await ue(t,se(this,Rs,"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 se(this,xs,"f").beta.environments.work.ack(r.id,{environment_id:r.environment_id},{headers:cs([se(this,Os,"f")?.headers]),signal:se(this,Rs,"f").signal})}catch(s){e.error("ack failed",{work_id:r.id,error:String(s)});continue}try{yield r}finally{if(se(this,$s,"f"))try{await se(this,xs,"f").beta.environments.work.stop(r.id,{environment_id:r.environment_id},{headers:cs([se(this,Os,"f")?.headers])})}catch(s){Xs(s,409)||e.warn("stop failed",{work_id:r.id,error:String(s)})}}}else{if(se(this,Ts,"f"))return;t.onEmptyPoll(),await ue(Qs(1e3,3e3),se(this,Rs,"f").signal)}}}finally{se(this,As,"f").call(this)}}}return e})();function sn(e){return Ys(e,1e3,6e4)}var nn,rn,on,an,cn,ln,hn,dn,un,pn,fn,gn,mn,_n,wn,yn,bn,vn,kn,Sn,xn,In,Rn,An,$n,Tn,En,Mn,On,Pn,Cn,Ln,Nn,qn,Wn,jn,Un=/* @__PURE__ */(()=>(Ps=/* @__PURE__ */new WeakMap,Cs=/* @__PURE__ */new WeakMap,Ls=/* @__PURE__ */new WeakMap,Ns=/* @__PURE__ */new WeakMap,class{constructor(e,t){Ps.set(this,void 0),Cs.set(this,void 0),Ls.set(this,void 0),Ns.set(this,0),te(this,Ps,e,"f"),te(this,Cs,t,"f")}onEmptyPoll(){const e=Date.now(),t={component:"work-poller",environment_id:se(this,Cs,"f")};void 0===se(this,Ls,"f")?(te(this,Ls,te(this,Ns,e,"f"),"f"),se(this,Ps,"f").info("idle; polling for work",t)):e-se(this,Ns,"f")>=3e5?(te(this,Ns,e,"f"),se(this,Ps,"f").info(`still polling; idle for ${Math.round((e-se(this,Ls,"f"))/1e3)}s`,t)):se(this,Ps,"f").debug("poll returned no work",t)}onClaim(){te(this,Ls,void 0,"f")}}))(),Dn=/* @__PURE__ */(()=>(nn=/* @__PURE__ */new WeakMap,rn=/* @__PURE__ */new WeakMap,on=/* @__PURE__ */new WeakMap,class{constructor(){nn.set(this,[]),rn.set(this,[]),on.set(this,!1)}push(e){if(se(this,on,"f"))return!1;const t=se(this,rn,"f").shift();return t?t({done:!1,value:e}):se(this,nn,"f").push(e),!0}close(){if(!se(this,on,"f"))for(te(this,on,!0,"f");se(this,rn,"f").length>0;)se(this,rn,"f").shift()({done:!0,value:void 0})}next(e){return se(this,nn,"f").length>0?Promise.resolve({done:!1,value:se(this,nn,"f").shift()}):se(this,on,"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=se(this,rn,"f").indexOf(s);e>=0&&se(this,rn,"f").splice(e,1),t({done:!0,value:void 0})};se(this,rn,"f").push(s),e?.addEventListener("abort",n,{once:!0})})}tryShift(){return se(this,nn,"f").shift()}}))(),Hn=/* @__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 zn(e){return"name"in e?e.name:"mcp_server_name"in e?e.mcp_server_name:e.type}function Fn(e){return e instanceof Hn?e.content:`Error: ${e instanceof Error?e.message:String(e)}`}function Bn(e){return"session.status_idle"===e.type&&"end_turn"===e.stop_reason?.type}var Kn,Jn,Vn,Xn,Gn,Yn=/* @__PURE__ */(()=>(an=/* @__PURE__ */new WeakMap,cn=/* @__PURE__ */new WeakMap,ln=/* @__PURE__ */new WeakMap,hn=/* @__PURE__ */new WeakMap,dn=/* @__PURE__ */new WeakMap,class{constructor(e,t){an.set(this,void 0),cn.set(this,void 0),ln.set(this,/* @__PURE__ */new Set),hn.set(this,!1),dn.set(this,void 0),te(this,an,e,"f"),te(this,cn,t,"f")}noteEvent(e){"user.tool_confirmation"!==e.type&&(Bn(e)?this.arm():this.disarm())}block(e){se(this,ln,"f").add(e),void 0!==se(this,dn,"f")&&(te(this,hn,!0,"f"),clearTimeout(se(this,dn,"f")),te(this,dn,void 0,"f"))}unblock(e){se(this,ln,"f").delete(e),0===se(this,ln,"f").size&&se(this,hn,"f")&&this.arm()}arm(){se(this,an,"f")<=0||(se(this,ln,"f").size>0?te(this,hn,!0,"f"):(te(this,hn,!1,"f"),void 0!==se(this,dn,"f")&&clearTimeout(se(this,dn,"f")),te(this,dn,setTimeout(se(this,cn,"f"),se(this,an,"f")),"f")))}disarm(){te(this,hn,!1,"f"),void 0!==se(this,dn,"f")&&(clearTimeout(se(this,dn,"f")),te(this,dn,void 0,"f"))}}))(),Qn=/* @__PURE__ */(()=>{class e{constructor(e,t){un.add(this),pn.set(this,!1),fn.set(this,void 0),gn.set(this,void 0),mn.set(this,void 0),_n.set(this,void 0),wn.set(this,void 0),yn.set(this,/* @__PURE__ */new Set),bn.set(this,/* @__PURE__ */new Set),vn.set(this,/* @__PURE__ */new Map),kn.set(this,/* @__PURE__ */new Map),Sn.set(this,new Dn),xn.set(this,0),In.set(this,3e5),Rn.set(this,null),An.set(this,void 0),this.client=t.client,this.sessionId=e,this.tools=t.tools,this.maxIdleMs=t.maxIdleMs??6e4,te(this,wn,ht(t.client),"f"),te(this,_n,new Map(t.tools.map(e=>[zn(e),e])),"f"),te(this,fn,new AbortController,"f"),te(this,gn,Vs(t.signal,se(this,fn,"f")),"f"),te(this,mn,t.requestOptions,"f"),te(this,An,new Yn(this.maxIdleMs,()=>{se(this,wn,"f").info("session idle after end_turn; stopping",{component:"session-tool-runner",session_id:this.sessionId,max_idle_ms:this.maxIdleMs}),se(this,fn,"f").abort()}),"f")}get signal(){return se(this,fn,"f").signal}abort(){se(this,fn,"f").abort()}_setSendRetryWindow(e){te(this,In,e,"f")}async*[(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,kn=/* @__PURE__ */new WeakMap,Sn=/* @__PURE__ */new WeakMap,xn=/* @__PURE__ */new WeakMap,In=/* @__PURE__ */new WeakMap,Rn=/* @__PURE__ */new WeakMap,An=/* @__PURE__ */new WeakMap,un=/* @__PURE__ */new WeakSet,Symbol.asyncIterator)](){if(se(this,pn,"f"))throw new U("Cannot iterate over a consumed SessionToolRunner");te(this,pn,!0,"f"),se(this,wn,"f").info("session tool runner starting",{component:"session-tool-runner",session_id:this.sessionId});const e=se(this,un,"m",Tn).call(this).catch(e=>{se(this,fn,"f").signal.aborted||se(this,wn,"f").error("stream loop failed",{error:String(e)}),se(this,fn,"f").abort()});try{for(;;){const e=await se(this,Sn,"f").next(se(this,fn,"f").signal);if(e.done)break;yield e.value}let t;for(await e;void 0!==(t=se(this,Sn,"f").tryShift());)yield t}finally{se(this,fn,"f").abort(),se(this,An,"f").disarm(),await e;try{await se(this,un,"m",jn).call(this)}catch(t){se(this,wn,"f").warn("drain failed",{error:String(t)})}se(this,Sn,"f").close();for(const e of this.tools)try{await(e.close?.())}catch(t){se(this,wn,"f").warn("tool.close failed",{tool:zn(e),error:String(t)})}se(this,gn,"f").call(this)}}}return $n=function(){return{...se(this,mn,"f"),headers:cs([ws("session-tool-runner"),se(this,mn,"f")?.headers]),signal:se(this,fn,"f").signal}},Tn=async function(){const e=se(this,fn,"f");let t=500;for(;!e.signal.aborted;){try{const e=await this.client.beta.sessions.events.stream(this.sessionId,{},se(this,un,"m",$n).call(this));await se(this,un,"m",En).call(this);for await(const s of e)if(t=500,await se(this,un,"m",On).call(this,s))return}catch(s){if(e.signal.throwIfAborted(),Gs(s))throw se(this,wn,"f").error("permanent stream failure, shutting down",{error:String(s)}),e.abort(),s;se(this,wn,"f").warn("stream disconnected, reconnecting",{error:String(s),backoff_ms:t})}e.signal.throwIfAborted(),await ue(t,e.signal),t=Math.min(2*t,1e4)}},En=async function(){const e=se(this,fn,"f"),t=[];let s=!1;try{for await(const e of this.client.beta.sessions.events.list(this.sessionId,{limit:1e3},se(this,un,"m",$n).call(this)))se(this,un,"m",Mn).call(this,e,t),s=Bn(e)}catch(i){e.signal.throwIfAborted(),se(this,wn,"f").warn("reconcile list failed",{error:String(i)});for(const e of t)se(this,yn,"f").delete(e.id);return}const n=t.filter(e=>!se(this,bn,"f").has(e.id));se(this,An,"f").disarm();for(const o of n)await se(this,un,"m",Pn).call(this,o);for(const o of[...se(this,kn,"f").values()]){const e=se(this,vn,"f").get(o.id);void 0!==e&&await se(this,un,"m",Ln).call(this,o,e)}const r=n.filter(e=>!se(this,bn,"f").has(e.id)&&!se(this,kn,"f").has(e.id));s&&0===r.length?se(this,An,"f").arm():se(this,An,"f").disarm()},Mn=function(e,t){"agent.tool_use"===e.type||"agent.custom_tool_use"===e.type?(se(this,yn,"f").add(e.id),se(this,bn,"f").has(e.id)||t.push(e)):"user.tool_result"===e.type?se(this,bn,"f").add(e.tool_use_id):"user.custom_tool_result"===e.type?se(this,bn,"f").add(e.custom_tool_use_id):"user.tool_confirmation"===e.type&&(se(this,bn,"f").has(e.tool_use_id)||se(this,vn,"f").set(e.tool_use_id,e.result))},On=async function(e){switch(se(this,An,"f").noteEvent(e),e.type){case"agent.tool_use":case"agent.custom_tool_use":return se(this,yn,"f").has(e.id)||(se(this,yn,"f").add(e.id),await se(this,un,"m",Pn).call(this,e)),!1;case"user.tool_confirmation":return await se(this,un,"m",Cn).call(this,e),!1;case"user.tool_result":return se(this,bn,"f").add(e.tool_use_id),!1;case"user.custom_tool_result":return se(this,bn,"f").add(e.custom_tool_use_id),!1;case"session.status_terminated":case"session.deleted":return se(this,wn,"f").info("session terminated",{component:"session-tool-runner",session_id:this.sessionId}),se(this,fn,"f").abort(),!0;default:return!1}},Pn=async function(e){const t=e.evaluated_permission,s="deny"===t?"deny":se(this,vn,"f").get(e.id);void 0!==s?await se(this,un,"m",Ln).call(this,e,s):void 0===t||"allow"===t?await se(this,un,"m",qn).call(this,e,void 0):se(this,kn,"f").has(e.id)||(se(this,wn,"f").info("tool call awaiting confirmation; holding",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),se(this,kn,"f").set(e.id,e),se(this,An,"f").block(e.id))},Cn=async function(e){se(this,vn,"f").set(e.tool_use_id,e.result);const t=se(this,kn,"f").get(e.tool_use_id);void 0!==t&&await se(this,un,"m",Ln).call(this,t,e.result)},Ln=async function(e,t){const s=se(this,kn,"f").delete(e.id);if("allow"!==t)s&&se(this,An,"f").unblock(e.id),se(this,bn,"f").add(e.id),se(this,wn,"f").info("tool call denied; not executing",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),se(this,un,"m",Nn).call(this,{event:e,toolUseId:e.id,name:e.name,isError:!1,posted:!1,confirmation:"deny"});else{se(this,wn,"f").info("tool call confirmed",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),s||se(this,An,"f").block(e.id);try{await se(this,un,"m",qn).call(this,e,"allow")}finally{se(this,An,"f").unblock(e.id)}}},Nn=function(e){se(this,Sn,"f").push(e)},qn=async function(e,t){var s,n;if(!se(this,bn,"f").has(e.id)){se(this,wn,"f").info("executing tool",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),te(this,xn,(s=se(this,xn,"f"),++s),"f");try{const s=se(this,_n,"f").get(e.name);if(!s)return se(this,wn,"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 se(this,un,"m",Nn).call(this,{event:e,toolUseId:e.id,name:e.name,isError:!1,posted:!1,confirmation:t});let n,r;const i=new AbortController,o=Vs(se(this,fn,"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:Fn(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 se(this,un,"m",Wn).call(this,c,e.id);se(this,un,"m",Nn).call(this,{event:e,result:c,toolUseId:e.id,name:e.name,isError:r,posted:l,confirmation:t})}finally{te(this,xn,(n=se(this,xn,"f"),--n),"f"),0===se(this,xn,"f")&&se(this,Rn,"f")?.call(this)}}},Wn=async function(e,t){const s=se(this,fn,"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]},se(this,un,"m",$n).call(this)),se(this,bn,"f").add(t),!0}catch(o){if(r=o,Gs(o))break;const e=se(this,In,"f")-(Date.now()-n);if(e<=0)break;const a=Math.min(Zs(Ys(i-1,1e3,3e4)),e);se(this,wn,"f").warn("tool result send failed; retrying",{tool_use_id:t,attempt:i,backoff_ms:a,error:String(o)}),await ue(a,s.signal)}}return se(this,wn,"f").error("failed to send tool result",{tool_use_id:t,attempts:i,error:String(r)}),!1},jn=async function(){0!==se(this,xn,"f")&&(await Promise.race([new Promise(e=>te(this,Rn,e,"f")),ue(3e4)]),te(this,Rn,null,"f"),se(this,xn,"f")>0&&se(this,wn,"f").warn("drain timeout exceeded"))},e})();var Zn=/* @__PURE__ */(()=>(Jn=/* @__PURE__ */new WeakMap,Kn=/* @__PURE__ */new WeakSet,Vn=async function(e,t,s){const n=ht(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(et((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 U("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 U("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=en(this.client,{authToken:i,helper:"environments-worker"}),a=e.data.id,c=new AbortController,l=Vs(s,c),h=new tr(c),d=await(import("./node.browser-CWS7vASg.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=Vs(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:cs([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(),Xs(f,412)){const e=function(e){let t=e instanceof D?e.error:void 0;for(const s of["error","details","current_state"]){if(!ce(t))return{};t=t[s]}return ce(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(Gs(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 ue(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 Qn(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 er(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 er(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:cs([n?.headers])})}catch(w){Xs(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(Kn.add(this),Jn.set(this,void 0),void 0!==e.unrestrictedPaths)throw new U("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 U(`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,te(this,Jn,e.signal,"f")}async run(e){const{environmentId:t,environmentKey:s}=this;if(void 0===t||void 0===s)throw new U("EnvironmentWorker.run: environmentId and environmentKey are required to poll for work");const n=e??se(this,Jn,"f"),r=new tn({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 se(this,Kn,"m",Vn).call(this,o,s,r.signal)}catch(i){if(r.signal?.aborted)throw i;ht(this.client).error("work item failed",{work_id:o.id,error:String(i)})}}async handleItem(e){const t=e?.workId??Qe("ANTHROPIC_WORK_ID"),s=e?.environmentId??Qe("ANTHROPIC_ENVIRONMENT_ID"),n=e?.sessionId??Qe("ANTHROPIC_SESSION_ID"),r=(e?.environmentKey??this.environmentKey??Qe("ANTHROPIC_ENVIRONMENT_KEY"))||void 0,i=e?.workSecret||Qe("ANTHROPIC_WORK_SECRET")||null;if(!t)throw new U("handleItem: workId is required — pass it or set ANTHROPIC_WORK_ID");if(!s)throw new U("handleItem: environmentId is required — pass it or set ANTHROPIC_ENVIRONMENT_ID");if(!n)throw new U("handleItem: sessionId is required — pass it or set ANTHROPIC_SESSION_ID");if(!r&&!i)throw new U("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 se(this,Kn,"m",Vn).call(this,o,r,e?.signal??se(this,Jn,"f"))}}))();async function er(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 tr=/* @__PURE__ */(()=>(Xn=/* @__PURE__ */new WeakMap,Gn=/* @__PURE__ */new WeakMap,class{constructor(e){Xn.set(this,void 0),Gn.set(this,void 0),te(this,Xn,e,"f")}get signal(){return se(this,Xn,"f").signal}finish(e){te(this,Gn,se(this,Gn,"f")??e,"f"),se(this,Xn,"f").abort()}get lost(){return"lease_lost"===se(this,Gn,"f")||"assumed_lost"===se(this,Gn,"f")}}))(),sr=/* @__PURE__ */(()=>{class e extends ss{retrieve(e,t,s){const{environment_id:n,betas:r,workspace_id:i}=t;return this._client.get(us`/v1/environments/${n}/work/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/environments/${n}/work/${e}?beta=true`,{body:o,...s,headers:cs([{"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(us`/v1/environments/${e}/work?beta=true`,zt,{query:r,...s,headers:cs([{"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(us`/v1/environments/${n}/work/${e}/ack?beta=true`,{...s,headers:cs([{"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(us`/v1/environments/${n}/work/${e}/heartbeat?beta=true`,{query:{desired_ttl_seconds:r,expected_last_heartbeat:i},...s,headers:cs([{"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(us`/v1/environments/${e}/work/poll?beta=true`,{query:i,...s,headers:cs([{"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(us`/v1/environments/${e}/work/stats?beta=true`,{...s,headers:cs([{"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(us`/v1/environments/${n}/work/${e}/stop?beta=true`,{body:o,...s,headers:cs([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}poller(e){return new tn({...e,client:this._client})}worker(e){return new Zn({...e,client:this._client})}}return e.WorkPoller=tn,e.EnvironmentWorker=Zn,e})(),nr=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.work=new sr(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:cs([{"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(us`/v1/environments/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/environments/${e}?beta=true`,{body:i,...s,headers:cs([{"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",zt,{query:r,...t,headers:cs([{"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(us`/v1/environments/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/environments/${e}/archive?beta=true`,{...s,headers:cs([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Work=sr,e})(),rr=class extends ss{create(e,t,s){const{view:n,betas:r,workspace_id:i,...o}=t;return this._client.post(us`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:n},body:o,...s,headers:cs([{"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(us`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:o,...s,headers:cs([{"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(us`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:{view:r},body:a,...s,headers:cs([{"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(us`/v1/memory_stores/${e}/memories?beta=true`,zt,{query:i,...s,headers:cs([{"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(us`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:{expected_content_sha256:r},...s,headers:cs([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...null!=o?{"anthropic-workspace-id":o}:void 0},s?.headers])})}},ir=class extends ss{retrieve(e,t,s){const{memory_store_id:n,betas:r,workspace_id:i,...o}=t;return this._client.get(us`/v1/memory_stores/${n}/memory_versions/${e}?beta=true`,{query:o,...s,headers:cs([{"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(us`/v1/memory_stores/${e}/memory_versions?beta=true`,zt,{query:i,...s,headers:cs([{"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(us`/v1/memory_stores/${n}/memory_versions/${e}/redact?beta=true`,{...s,headers:cs([{"anthropic-beta":[...r??[],"agent-memory-2026-07-22"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}},or=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.memories=new rr(this._client),this.memoryVersions=new ir(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:cs([{"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(us`/v1/memory_stores/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/memory_stores/${e}?beta=true`,{body:i,...s,headers:cs([{"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",zt,{query:r,...t,headers:cs([{"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(us`/v1/memory_stores/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/memory_stores/${e}/archive?beta=true`,{...s,headers:cs([{"anthropic-beta":[...n??[],"agent-memory-2026-07-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Memories=rr,e.MemoryVersions=ir,e})(),ar=/* @__PURE__ */(()=>{class e{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new Rt;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 U("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 U("Attempted to iterate over a response with no body")}return new e(ke(t.body),s)}}return e})(),cr=class extends ss{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:cs([{"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(us`/v1/messages/batches/${e}?beta=true`,{...s,headers:cs([{"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",Ht,{query:r,...t,headers:cs([{"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(us`/v1/messages/batches/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/messages/batches/${e}/cancel?beta=true`,{...s,headers:cs([{"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 U(`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:cs([{"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)=>ar.fromResponse(t.response,t.controller))}},lr={"claude-opus-4@20250514":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function hr(e){return e?.output_format??e?.output_config?.format}function dr(e,t,s){const n=hr(t);return t&&"parse"in(n??{})?ur(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 ur(e,t,s){let n=null;const r=e.content.map(e=>{if("text"===e.type){const r=function(e,t){const s=hr(e);if("json_schema"!==s?.type)return null;try{return"parse"in s?s.parse(t):JSON.parse(t)}catch(n){throw new U(`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 pr,fr,gr,mr,_r,wr,yr,br,vr,kr,Sr,xr,Ir,Rr,Ar,$r,Tr,Er,Mr,Or,Pr,Cr,Lr,Nr,qr,Wr,jr="__json_buf";function Ur(e,t){const s={};for(const i of Object.keys(e))"input"!==i&&(s[i]=e[i]);let n;Object.defineProperty(s,jr,{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 Dr(e){return"tool_use"===e.type||"server_tool_use"===e.type||"mcp_tool_use"===e.type}var 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,bi,vi,ki,Si,xi,Ii=/* @__PURE__ */(()=>{class e{constructor(e,t){pr.add(this),this.messages=[],this.receivedMessages=[],fr.set(this,void 0),gr.set(this,null),this.controller=new AbortController,mr.set(this,void 0),_r.set(this,()=>{}),wr.set(this,()=>{}),yr.set(this,void 0),br.set(this,()=>{}),vr.set(this,()=>{}),kr.set(this,{}),Sr.set(this,!1),xr.set(this,!1),Ir.set(this,!1),Rr.set(this,!1),Ar.set(this,void 0),$r.set(this,void 0),Tr.set(this,void 0),Er.set(this,void 0),Pr.set(this,e=>{if(te(this,xr,!0,"f"),W(e)&&(e=new H),e instanceof H)return te(this,Ir,!0,"f"),this._emit("abort",e);if(e instanceof U)return this._emit("error",e);if(e instanceof Error){const t=new U(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new U(String(e)))}),te(this,mr,new Promise((e,t)=>{te(this,_r,e,"f"),te(this,wr,t,"f")}),"f"),te(this,yr,new Promise((e,t)=>{te(this,br,e,"f"),te(this,vr,t,"f")}),"f"),se(this,mr,"f").catch(()=>{}),se(this,yr,"f").catch(()=>{}),te(this,gr,e,"f"),te(this,Er,t?.logger??console,"f")}get response(){return se(this,Ar,"f")}get request_id(){return se(this,$r,"f")}get workspace_id(){return se(this,Tr,"f")}async withResponse(){te(this,Rr,!0,"f");const e=await se(this,mr,"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 te(i,gr,{...s,stream:!0},"f"),i._run(()=>i._createMessage(t,{...s,stream:!0},{...n,headers:{...n?.headers,[_s]:"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},se(this,Pr,"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{se(this,pr,"m",Cr).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)se(this,pr,"m",Lr).call(this,e);if(r.controller.signal?.aborted)throw new H;se(this,pr,"m",Nr).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}_connected(e){this.ended||(te(this,Ar,e,"f"),te(this,$r,e?.headers.get("request-id"),"f"),te(this,Tr,e?.headers.get("anthropic-workspace-id"),"f"),se(this,_r,"f").call(this,e),this._emit("connect"))}get ended(){return se(this,Sr,"f")}get errored(){return se(this,xr,"f")}get aborted(){return se(this,Ir,"f")}abort(){this.controller.abort()}on(e,t){return(se(this,kr,"f")[e]||(se(this,kr,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=se(this,kr,"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(se(this,kr,"f")[e]||(se(this,kr,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{te(this,Rr,!0,"f"),"error"!==e&&this.once("error",s),this.once(e,t)})}async done(){te(this,Rr,!0,"f"),await se(this,yr,"f")}get currentMessage(){return se(this,fr,"f")}async finalMessage(){return await this.done(),se(this,pr,"m",Mr).call(this)}async finalText(){return await this.done(),se(this,pr,"m",Or).call(this)}_emit(e,...t){if(se(this,Sr,"f"))return;"end"===e&&(te(this,Sr,!0,"f"),se(this,br,"f").call(this));const s=se(this,kr,"f")[e];if(s&&(se(this,kr,"f")[e]=s.filter(e=>!e.once),s.forEach(({listener:e})=>e(...t))),"abort"===e){const e=t[0];return se(this,Rr,"f")||s?.length||Promise.reject(e),se(this,wr,"f").call(this,e),se(this,vr,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];se(this,Rr,"f")||s?.length||Promise.reject(e),se(this,wr,"f").call(this,e),se(this,vr,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",se(this,pr,"m",Mr).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{se(this,pr,"m",Cr).call(this),this._connected(null);const t=$t.fromReadableStream(e,this.controller);for await(const e of t)se(this,pr,"m",Lr).call(this,e);if(t.controller.signal?.aborted)throw new H;se(this,pr,"m",Nr).call(this)}finally{s&&n&&s.removeEventListener("abort",n)}}[(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,Ir=/* @__PURE__ */new WeakMap,Rr=/* @__PURE__ */new WeakMap,Ar=/* @__PURE__ */new WeakMap,$r=/* @__PURE__ */new WeakMap,Tr=/* @__PURE__ */new WeakMap,Er=/* @__PURE__ */new WeakMap,Pr=/* @__PURE__ */new WeakMap,pr=/* @__PURE__ */new WeakSet,Mr=function(){if(0===this.receivedMessages.length)throw new U("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Or=function(){if(0===this.receivedMessages.length)throw new U("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 U("stream ended without producing a content block with type=text");return e.join(" ")},Cr=function(){this.ended||te(this,fr,void 0,"f")},Lr=function(e){if(this.ended)return;const t=se(this,pr,"m",qr).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(Dr(n)&&se(this,kr,"f").inputJson?.length){let t;try{t=n.input}catch(s){se(this,Pr,"f").call(this,se(this,pr,"m",Wr).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(dr(t,se(this,gr,"f"),{logger:se(this,Er,"f")}),!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":te(this,fr,t,"f")}},Nr=function(){if(this.ended)throw new U("stream has ended, this shouldn't happen");const e=se(this,fr,"f");if(!e)throw new U("request ended without sending any chunks");return te(this,fr,void 0,"f"),dr(e,se(this,gr,"f"),{logger:se(this,Er,"f")})},qr=function(e){let t=se(this,fr,"f");if("message_start"===e.type){if(t)throw new U(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new U(`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&&Dr(s)){const n=(s.__json_buf||"")+e.delta.partial_json;t.content[e.index]=Ur(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&&Dr(n)&&"__json_buf"in n){let e;try{e=n.input}catch(s){e={},se(this,Pr,"f").call(this,se(this,pr,"m",Wr).call(this,n,s))}Object.defineProperty(n,"input",{value:e,enumerable:!0,configurable:!0,writable:!0})}return t}}},Wr=function(e,t){const s=e[jr];return new U(`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 $t(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}return e})(),Ri=/* @__PURE__ */(()=>{class e extends Ii{constructor(e,t){super(e),Hr.add(this),zr.set(this,void 0),Fr.set(this,0),Br.set(this,[]),Kr.set(this,[]),Jr.set(this,void 0),Vr.set(this,[]),Xr.set(this,!1),te(this,zr,t,"f")}get toolCalls(){return se(this,Kr,"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,[_s]:"stream"}})),i}_emit(e,...t){var s;if("streamEvent"!==e||this.ended)return void super._emit(e,...t);te(this,Fr,(s=se(this,Fr,"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&&se(this,Kr,"f").push(o),super._emit(e,...t),se(this,Hr,"m",Gr).call(this,n,o),se(this,Hr,"m",Yr).call(this)}[(zr=/* @__PURE__ */new WeakMap,Fr=/* @__PURE__ */new WeakMap,Br=/* @__PURE__ */new WeakMap,Kr=/* @__PURE__ */new WeakMap,Jr=/* @__PURE__ */new WeakMap,Vr=/* @__PURE__ */new WeakMap,Xr=/* @__PURE__ */new WeakMap,Hr=/* @__PURE__ */new WeakSet,Symbol.asyncIterator)](){const e=super[Symbol.asyncIterator](),t={handled:se(this,Fr,"f")};se(this,Br,"f").push(t);let s=!1;return{next:async()=>{s&&(s=!1,t.handled++,se(this,Hr,"m",Yr).call(this));try{const n=await e.next();return s=!n.done,n.done&&se(this,Hr,"m",Qr).call(this,t),n}catch(n){throw se(this,Hr,"m",Qr).call(this,t),n}},return:async()=>{const s=e.return?.();return se(this,Hr,"m",Qr).call(this,t),await s??{value:void 0,done:!0}}}}}return Gr=function(e,t){if(se(this,Xr,"f"))return;if("content_block_start"===e.type&&"fallback"===e.content_block.type)return te(this,Xr,!0,"f"),void te(this,Jr,void 0,"f");const s="content_block_start"===e.type||"message_delta"===e.type&&"tool_use"===e.delta.stop_reason;se(this,Jr,"f")&&s&&(se(this,Vr,"f").push({toolUse:se(this,Jr,"f"),event:se(this,Fr,"f")}),te(this,Jr,void 0,"f")),t&&te(this,Jr,t,"f")},Yr=function(){if(this.errored||this.controller.signal.aborted)return;const e=Math.min(se(this,Fr,"f"),...se(this,Br,"f").map(e=>e.handled));for(;se(this,Vr,"f")[0]&&se(this,Vr,"f")[0].event<=e;)se(this,zr,"f").call(this,se(this,Vr,"f").shift().toolUse)},Qr=function(e){const t=se(this,Br,"f").indexOf(e);t>=0&&(se(this,Br,"f").splice(t,1),se(this,Hr,"m",Yr).call(this))},e})();function Ai(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}var $i=/* @__PURE__ */(()=>{class e{constructor(e,t,s){Zr.add(this),this.client=e,ei.set(this,!1),ti.set(this,!1),si.set(this,void 0),ni.set(this,void 0),ri.set(this,void 0),ii.set(this,void 0),oi.set(this,void 0),ai.set(this,void 0),ci.set(this,0),li.set(this,{status:"idle"}),hi.set(this,void 0),di.set(this,null),ui.set(this,/* @__PURE__ */new Map),pi.set(this,[]),Ti(t),function(e){if("compactionControl"in e&&null!=e.compactionControl)throw new U("`compactionControl` has been removed from the tool runner. Use server-side compaction instead: call `runner.compactBeforeNextTurn()` when the conversation should be compacted.")}(t),Ei(t),te(this,si,{params:{...t,messages:JSON.parse(JSON.stringify(t.messages))}},"f");const n=vs(t.tools,t.messages);te(this,ni,{...s,headers:cs([ws("BetaToolRunner"),n.length?{[ms]:n.join(", ")}:void 0,s?.headers])},"f"),te(this,ai,Ai(),"f")}async*[(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,ci=/* @__PURE__ */new WeakMap,li=/* @__PURE__ */new WeakMap,hi=/* @__PURE__ */new WeakMap,di=/* @__PURE__ */new WeakMap,ui=/* @__PURE__ */new WeakMap,pi=/* @__PURE__ */new WeakMap,Zr=/* @__PURE__ */new WeakSet,Symbol.asyncIterator)](){var e;if(se(this,ei,"f"))throw new U("Cannot iterate over a consumed stream");te(this,ei,!0,"f"),te(this,ti,!0,"f"),te(this,oi,void 0,"f");try{for(;;)try{if(se(this,si,"f").params.max_iterations&&se(this,ci,"f")>=se(this,si,"f").params.max_iterations)break;if(se(this,Zr,"m",Si).call(this),"scheduled"===se(this,li,"f").status&&"resume"!==Li(se(this,di,"f"))){yield*se(this,Zr,"m",_i).call(this,se(this,li,"f").config);continue}te(this,ti,!1,"f"),te(this,oi,void 0,"f"),te(this,ci,(e=se(this,ci,"f"),++e),"f"),te(this,ri,void 0,"f");const{max_iterations:t,runToolsEagerly:s,...n}=se(this,si,"f").params;if(yield*se(this,Zr,"m",fi).call(this,n),se(this,ti,"f"))te(this,di,null,"f");else{const e=await se(this,ri,"f"),t=Li(e.stop_reason);te(this,di,e.stop_reason,"f"),se(this,si,"f").params.messages.push({role:e.role,content:Pi(e.content)});const{container:s}=se(this,si,"f").params;if(e.container&&(null==s?se(this,si,"f").params.container=e.container.id:"object"==typeof s&&null==s.id&&(se(this,si,"f").params.container={...s,id:e.container.id})),"stop"===t){yield*se(this,Zr,"m",vi).call(this);break}if("resume"===t)continue}const r=await se(this,Zr,"m",ki).call(this,se(this,si,"f").params.messages.at(-1));if(r)se(this,si,"f").params.messages.push(r);else if(!se(this,ti,"f")){yield*se(this,Zr,"m",vi).call(this);break}}finally{se(this,ii,"f")?.abort(),te(this,ii,void 0,"f")}if(await se(this,Zr,"m",mi).call(this),!se(this,ri,"f"))throw new U("ToolRunner concluded without a message from the server");se(this,ai,"f").resolve(await se(this,ri,"f"))}catch(t){throw te(this,ei,!1,"f"),se(this,ai,"f").promise.catch(()=>{}),se(this,ai,"f").reject(t),te(this,ai,Ai(),"f"),t}}setMessagesParams(e){const t="function"==typeof e?e(se(this,si,"f").params):e;if(Ti(t),Ei(t),"idle"!==se(this,li,"f").status&&Mi(t),"in_flight"===se(this,li,"f").status&&t.messages!==se(this,si,"f").params.messages)throw new U("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.");se(this,si,"f").params=t,te(this,ti,!0,"f"),te(this,oi,void 0,"f")}setRequestOptions(e){te(this,ni,"function"==typeof e?e(se(this,ni,"f")):{...se(this,ni,"f"),...e},"f")}async generateToolResponse(e=se(this,ni,"f").signal){const t=await se(this,ri,"f")??this.params.messages.at(-1);return t?se(this,Zr,"m",ki).call(this,t,e):null}deferToolCall(e){const t="string"==typeof e?e:e.id;se(this,hi,"f")&&!se(this,hi,"f").has(t)&&se(this,hi,"f").set(t,{status:"held"})}get deferredToolCalls(){const e=se(this,ii,"f"),t=se(this,hi,"f");return e instanceof Ri&&t?e.toolCalls.filter(e=>"held"===t.get(e.id)?.status):[]}done(){return se(this,ai,"f").promise}async runUntilDone(){if(!se(this,ei,"f"))for await(const e of this);return this.done()}get params(){return se(this,si,"f").params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}compactBeforeNextTurn(e){"in_flight"!==se(this,li,"f").status&&(Mi(se(this,si,"f").params),te(this,li,{status:"scheduled",config:e??{type:"summarize"}},"f"))}addTools(...e){for(const t of e)"name"in t&&se(this,ui,"f").set(t.name,"run"in t?t:null),se(this,pi,"f").push({type:"addition",tool:t})}removeTools(...e){for(const t of e){const e="string"==typeof t?t:t.name;se(this,ui,"f").set(e,null),se(this,pi,"f").push({type:"removal",name:e})}}then(e,t){return this.runUntilDone().then(e,t)}}return fi=async function*(e){await se(this,Zr,"m",mi).call(this),te(this,hi,void 0,"f"),e.stream?(te(this,ii,se(this,si,"f").params.runToolsEagerly?se(this,Zr,"m",gi).call(this,e):this.client.beta.messages.stream({...e},se(this,ni,"f")),"f"),te(this,ri,se(this,ii,"f").finalMessage(),"f"),se(this,ri,"f").catch(()=>{}),yield se(this,ii,"f")):(te(this,ri,this.client.beta.messages.create({...e,stream:!1},se(this,ni,"f")),"f"),yield se(this,ri,"f"))},gi=function(e){const t=/* @__PURE__ */new Map;return te(this,hi,t,"f"),Ri.start(this.client.beta.messages,e,se(this,ni,"f"),e=>{if(t.has(e.id))return;const s=Oi(se(this,Zr,"m",wi).call(this),se(this,Zr,"m",yi).call(this),e,se(this,ni,"f"));s.catch(()=>{}),t.set(e.id,{status:"started",result:s})})},mi=async function(){const e=[...se(this,hi,"f")?.values()??[]].filter(e=>"started"===e.status);await Promise.allSettled(e.map(e=>e.result))},_i=async function*(e){Mi(se(this,si,"f").params);const{max_iterations:t,runToolsEagerly:s,...n}=se(this,si,"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);te(this,li,{status:"in_flight"},"f"),te(this,oi,void 0,"f");const i=se(this,ri,"f");try{yield*se(this,Zr,"m",fi).call(this,{...r,compaction:e});const t=await se(this,ri,"f");t.content.some(e=>"compaction"===e.type&&e.content)?(se(this,Zr,"m",bi).call(this),se(this,si,"f").params.messages=[{role:t.role,content:t.content}]):(ht(this.client).warn("Compaction produced no summary; keeping the conversation as it is."),te(this,ri,i,"f"))}finally{te(this,li,{status:"idle"},"f")}},wi=function(){const e=/* @__PURE__ */new Map;for(const t of se(this,si,"f").params.tools)"run"in t&&e.set(t.name,t);for(const[t,s]of se(this,ui,"f"))s?e.set(t,s):e.delete(t);return e},yi=function(){const e=new Set(se(this,Zr,"m",wi).call(this).keys());for(const t of[...se(this,si,"f").params.messages,se(this,Zr,"m",xi).call(this)])if("string"!=typeof t.content)for(const s of t.content)if("system"===t.role)Ci(s,e);else if("assistant"===t.role&&"compaction"===s.type)for(const t of s.tool_changes??[])Ci(t,e);return e},bi=function(){const e=se(this,Zr,"m",yi).call(this);for(const t of se(this,Zr,"m",wi).call(this).keys())e.has(t)||se(this,ui,"f").set(t,null)},vi=async function*(){if("scheduled"!==se(this,li,"f").status)return;const e=se(this,si,"f").params.messages.at(-1)?.content;if(Array.isArray(e)&&e.some(e=>"tool_use"===e.type))return ht(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 te(this,li,{status:"idle"},"f");yield*se(this,Zr,"m",_i).call(this,se(this,li,"f").config)},ki=async function(e,t=se(this,ni,"f").signal){return void 0!==se(this,oi,"f")||te(this,oi,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=Oi(e,t,s,n);return r?.set(s.id,{status:"started",result:o}),o}))}}(se(this,Zr,"m",wi).call(this),se(this,Zr,"m",yi).call(this),e,{...se(this,ni,"f"),signal:t},se(this,hi,"f")),"f"),se(this,oi,"f")},Si=function(){"pause_turn"!==se(this,di,"f")&&0!==se(this,pi,"f").length&&(se(this,si,"f").params.messages.push(se(this,Zr,"m",xi).call(this)),te(this,pi,[],"f"))},xi=function(){const e=[];for(const t of se(this,pi,"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 Ti(e){if("compaction"in e&&null!=e.compaction)throw new U("`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 Ei(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 Mi(e){if(e.context_management?.edits?.some(e=>e.type.startsWith("compact_")))throw new U("`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 Oi(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 Hn?i.content:`Error: ${i instanceof Error?i.message:String(i)}`,is_error:!0}}}function Pi(e){return e}function Ci(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 Li(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 Ni=["claude-mythos-preview","claude-opus-4-6"],qi=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.batches=new cr(this._client)}create(e,t){const s=Wi(e),{betas:n,user_profile_id:r,workspace_id:i,...o}=s;o.model,Ni.includes(o.model)&&o.thinking&&o.thinking.type;let a=t?.timeout??this._client._options.timeout;if(!o.stream&&null==a){const e=lr[o.model]??void 0;a=this._client.calculateNonstreamingTimeout(o.max_tokens,e)}const c=ks(o.tools,o.messages);return this._client.post("/v1/messages?beta=true",{body:o,timeout:a??6e5,...t,headers:cs([{...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:cs([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},t?.headers])},this.create(e,t).then(t=>ur(t,e,{logger:this._client.logger??console}))}stream(e,t){return Ii.createMessage(this,e,t)}countTokens(e,t){const{betas:s,user_profile_id:n,workspace_id:r,...i}=Wi(e);return this._client.post("/v1/messages/count_tokens?beta=true",{body:i,...t,headers:cs([{"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 $i(this._client,e,t)}}return e.Batches=cr,e.BetaToolRunner=$i,e.ToolError=Hn,e})();function Wi(e){if(!e.output_format)return e;if(e.output_config?.format)throw new U("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 ji,Ui,Di,Hi,zi,Fi,Bi,Ki,Ji,Vi,Xi,Gi,Yi,Qi,Zi,eo,to,so,no,ro,io,oo,ao,co,lo,ho=class extends ss{retrieve(e,t){return this._client.get(us`/v1/organizations/api_keys/${e}?beta=true`,t)}update(e,t,s){return this._client.post(us`/v1/organizations/api_keys/${e}?beta=true`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/api_keys?beta=true",Ht,{query:e,...t})}},uo=class extends ss{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})}},po=class extends ss{create(e,t){return this._client.post("/v1/organizations/external_keys?beta=true",{body:e,...t})}retrieve(e,t){return this._client.get(us`/v1/organizations/external_keys/${e}?beta=true`,t)}update(e,t,s){return this._client.post(us`/v1/organizations/external_keys/${e}?beta=true`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/external_keys?beta=true",zt,{query:e,...t})}delete(e,t){return this._client.delete(us`/v1/organizations/external_keys/${e}?beta=true`,t)}validate(e,t){return this._client.post(us`/v1/organizations/external_keys/${e}/validate?beta=true`,t)}},fo=class extends ss{create(e,t){return this._client.post("/v1/organizations/invites?beta=true",{body:e,...t})}retrieve(e,t){return this._client.get(us`/v1/organizations/invites/${e}?beta=true`,t)}list(e={},t){return this._client.getAPIList("/v1/organizations/invites?beta=true",Ht,{query:e,...t})}delete(e,t){return this._client.delete(us`/v1/organizations/invites/${e}?beta=true`,t)}},go=class extends ss{list(e={},t){return this._client.getAPIList("/v1/organizations/rate_limits?beta=true",zt,{query:e,...t})}},mo=class extends ss{retrieve(e,t){return this._client.get(us`/v1/organizations/users/${e}?beta=true`,t)}update(e,t,s){return this._client.post(us`/v1/organizations/users/${e}?beta=true`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/users?beta=true",Ht,{query:e,...t})}remove(e,t){return this._client.delete(us`/v1/organizations/users/${e}?beta=true`,t)}},_o=class extends ss{create(e,t){const{betas:s,...n}=e;return this._client.post("/v1/organizations/federation_issuers?beta=true",{body:n,...t,headers:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n}=t??{};return this._client.get(us`/v1/organizations/federation_issuers/${e}?beta=true`,{...s,headers:cs([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}update(e,t,s){const{betas:n,...r}=t;return this._client.post(us`/v1/organizations/federation_issuers/${e}?beta=true`,{body:r,...s,headers:cs([{...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",zt,{query:n,...t,headers:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}archive(e,t={},s){const{betas:n}=t??{};return this._client.post(us`/v1/organizations/federation_issuers/${e}/archive?beta=true`,{...s,headers:cs([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}},wo=class extends ss{list(e,t={},s){const{betas:n,...r}=t??{};return this._client.getAPIList(us`/v1/organizations/federation_rules/${e}/workspaces?beta=true`,zt,{query:r,...s,headers:cs([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}add(e,t,s){const{betas:n,...r}=t;return this._client.post(us`/v1/organizations/federation_rules/${e}/workspaces?beta=true`,{body:r,...s,headers:cs([{...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(us`/v1/organizations/federation_rules/${n}/workspaces/${e}?beta=true`,{...s,headers:cs([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}},yo=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.workspaces=new wo(this._client)}create(e,t){const{betas:s,...n}=e;return this._client.post("/v1/organizations/federation_rules?beta=true",{body:n,...t,headers:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n}=t??{};return this._client.get(us`/v1/organizations/federation_rules/${e}?beta=true`,{...s,headers:cs([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}update(e,t,s){const{betas:n,...r}=t;return this._client.post(us`/v1/organizations/federation_rules/${e}?beta=true`,{body:r,...s,headers:cs([{...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",zt,{query:n,...t,headers:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}archive(e,t={},s){const{betas:n}=t??{};return this._client.post(us`/v1/organizations/federation_rules/${e}/archive?beta=true`,{...s,headers:cs([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}}return e.Workspaces=wo,e})(),bo=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.issuers=new _o(this._client),this.rules=new yo(this._client)}}return e.Issuers=_o,e.Rules=yo,e})(),vo=class extends ss{list(e,t={},s){const{betas:n,...r}=t??{};return this._client.getAPIList(us`/v1/organizations/service_accounts/${e}/workspaces?beta=true`,zt,{query:r,...s,headers:cs([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}add(e,t,s){const{betas:n,...r}=t;return this._client.post(us`/v1/organizations/service_accounts/${e}/workspaces?beta=true`,{body:r,...s,headers:cs([{...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(us`/v1/organizations/service_accounts/${n}/workspaces/${e}?beta=true`,{...s,headers:cs([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}},ko=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.workspaces=new vo(this._client)}create(e,t){const{betas:s,...n}=e;return this._client.post("/v1/organizations/service_accounts?beta=true",{body:n,...t,headers:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n}=t??{};return this._client.get(us`/v1/organizations/service_accounts/${e}?beta=true`,{...s,headers:cs([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}update(e,t,s){const{betas:n,...r}=t;return this._client.post(us`/v1/organizations/service_accounts/${e}?beta=true`,{body:r,...s,headers:cs([{...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",zt,{query:n,...t,headers:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}archive(e,t={},s){const{betas:n}=t??{};return this._client.post(us`/v1/organizations/service_accounts/${e}/archive?beta=true`,{...s,headers:cs([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}}return e.Workspaces=vo,e})(),So=class extends ss{retrieve(e,t,s){const{workspace_id:n}=t;return this._client.get(us`/v1/organizations/workspaces/${n}/members/${e}?beta=true`,s)}update(e,t,s){const{workspace_id:n,...r}=t;return this._client.post(us`/v1/organizations/workspaces/${n}/members/${e}?beta=true`,{body:r,...s})}list(e,t={},s){return this._client.getAPIList(us`/v1/organizations/workspaces/${e}/members?beta=true`,Ht,{query:t,...s})}add(e,t,s){return this._client.post(us`/v1/organizations/workspaces/${e}/members?beta=true`,{body:t,...s})}remove(e,t,s){const{workspace_id:n}=t;return this._client.delete(us`/v1/organizations/workspaces/${n}/members/${e}?beta=true`,s)}},xo=class extends ss{list(e,t={},s){return this._client.getAPIList(us`/v1/organizations/workspaces/${e}/rate_limits?beta=true`,zt,{query:t,...s})}},Io=class extends ss{retrieve(e,t,s){const{workspace_id:n,betas:r}=t;return this._client.get(us`/v1/organizations/workspaces/${n}/service_accounts/${e}?beta=true`,{...s,headers:cs([{...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(us`/v1/organizations/workspaces/${n}/service_accounts/${e}?beta=true`,{body:i,...s,headers:cs([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}list(e,t={},s){const{betas:n,...r}=t??{};return this._client.getAPIList(us`/v1/organizations/workspaces/${e}/service_accounts?beta=true`,zt,{query:r,...s,headers:cs([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}add(e,t,s){const{betas:n,...r}=t;return this._client.post(us`/v1/organizations/workspaces/${e}/service_accounts?beta=true`,{body:r,...s,headers:cs([{...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(us`/v1/organizations/workspaces/${n}/service_accounts/${e}?beta=true`,{...s,headers:cs([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}},Ro=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.rateLimits=new xo(this._client),this.members=new So(this._client),this.serviceAccounts=new Io(this._client)}create(e,t){const{betas:s,...n}=e;return this._client.post("/v1/organizations/workspaces?beta=true",{body:n,...t,headers:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}retrieve(e,t){return this._client.get(us`/v1/organizations/workspaces/${e}?beta=true`,t)}update(e,t,s){return this._client.post(us`/v1/organizations/workspaces/${e}?beta=true`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/workspaces?beta=true",Ht,{query:e,...t})}archive(e,t){return this._client.post(us`/v1/organizations/workspaces/${e}/archive?beta=true`,t)}}return e.RateLimits=xo,e.Members=So,e.ServiceAccounts=Io,e})(),Ao=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.apiKeys=new ho(this._client),this.externalKeys=new po(this._client),this.federation=new bo(this._client),this.invites=new fo(this._client),this.serviceAccounts=new ko(this._client),this.users=new mo(this._client),this.workspaces=new Ro(this._client),this.rateLimits=new go(this._client),this.complianceSettings=new uo(this._client)}retrieve(e){return this._client.get("/v1/organizations/me?beta=true",e)}}return e.APIKeys=ho,e.ExternalKeys=po,e.Federation=bo,e.Invites=fo,e.ServiceAccounts=ko,e.Users=mo,e.Workspaces=Ro,e.RateLimits=go,e.ComplianceSettings=uo,e})(),$o=/* @__PURE__ */(()=>{class e extends ss{list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(us`/v1/sessions/${e}/events?beta=true`,zt,{query:i,...s,headers:cs([{"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(us`/v1/sessions/${e}/events?beta=true`,{body:i,...s,headers:cs([{"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(us`/v1/sessions/${e}/events/stream?beta=true`,{query:i,...s,headers:cs([{"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 Qn(e,{...t,client:this._client})}}return e.SessionToolRunner=Qn,e})(),To=class extends ss{retrieve(e,t,s){const{session_id:n,betas:r,workspace_id:i}=t;return this._client.get(us`/v1/sessions/${n}/resources/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/sessions/${n}/resources/${e}?beta=true`,{body:o,...s,headers:cs([{"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(us`/v1/sessions/${e}/resources?beta=true`,zt,{query:i,...s,headers:cs([{"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(us`/v1/sessions/${n}/resources/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/sessions/${e}/resources?beta=true`,{body:i,...s,headers:cs([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},Eo=class extends ss{list(e,t,s){const{session_id:n,betas:r,workspace_id:i,...o}=t;return this._client.getAPIList(us`/v1/sessions/${n}/threads/${e}/events?beta=true`,zt,{query:o,...s,headers:cs([{"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(us`/v1/sessions/${n}/threads/${e}/stream?beta=true`,{query:o,...s,headers:cs([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers]),stream:!0})}},Mo=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.events=new Eo(this._client)}retrieve(e,t,s){const{session_id:n,betas:r,workspace_id:i}=t;return this._client.get(us`/v1/sessions/${n}/threads/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/sessions/${e}/threads?beta=true`,zt,{query:i,...s,headers:cs([{"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(us`/v1/sessions/${n}/threads/${e}/archive?beta=true`,{...s,headers:cs([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}}return e.Events=Eo,e})(),Oo=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.events=new $o(this._client),this.resources=new To(this._client),this.threads=new Mo(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:cs([{"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(us`/v1/sessions/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/sessions/${e}?beta=true`,{body:i,...s,headers:cs([{"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",Ft,{query:r,...t,headers:cs([{"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(us`/v1/sessions/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/sessions/${e}/archive?beta=true`,{...s,headers:cs([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Events=$o,e.Resources=To,e.Threads=Mo,e})(),Po=class extends ss{create(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(us`/v1/skills/${e}/versions?beta=true`,Xt({body:i,...s,headers:cs([{...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(us`/v1/skills/${n}/versions/${e}?beta=true`,{...s,headers:cs([{...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(us`/v1/skills/${e}/versions?beta=true`,zt,{query:i,...s,headers:cs([{...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(us`/v1/skills/${n}/versions/${e}?beta=true`,{...s,headers:cs([{...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(us`/v1/skills/${n}/versions/${e}/content?beta=true`,{...s,headers:cs([{Accept:"application/binary",...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0,...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers]),__binaryResponse:!0})}},Co=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.versions=new Po(this._client)}create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/skills?beta=true",Xt({body:r,...t,headers:cs([{...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(us`/v1/skills/${e}?beta=true`,{...s,headers:cs([{...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",zt,{query:r,...t,headers:cs([{...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(us`/v1/skills/${e}?beta=true`,{...s,headers:cs([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Versions=Po,e})(),Lo=class extends ss{create(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(us`/v1/tunnels/${e}/certificates?beta=true`,{body:i,...s,headers:cs([{"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(us`/v1/tunnels/${n}/certificates/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/tunnels/${e}/certificates?beta=true`,zt,{query:i,...s,headers:cs([{"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(us`/v1/tunnels/${n}/certificates/${e}/archive?beta=true`,{...s,headers:cs([{"anthropic-beta":[...r??[],"mcp-tunnels-2026-06-22"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}},No=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.certificates=new Lo(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:cs([{"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(us`/v1/tunnels/${e}?beta=true`,{...s,headers:cs([{"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",zt,{query:r,...t,headers:cs([{"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(us`/v1/tunnels/${e}/archive?beta=true`,{...s,headers:cs([{"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(us`/v1/tunnels/${e}/reveal_token?beta=true`,{...s,headers:cs([{"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(us`/v1/tunnels/${e}/rotate_token?beta=true`,{body:i,...s,headers:cs([{"anthropic-beta":[...n??[],"mcp-tunnels-2026-06-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Certificates=Lo,e})(),qo=class extends ss{create(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(us`/v1/vaults/${e}/credentials?beta=true`,{body:i,...s,headers:cs([{"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(us`/v1/vaults/${n}/credentials/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/vaults/${n}/credentials/${e}?beta=true`,{body:o,...s,headers:cs([{"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(us`/v1/vaults/${e}/credentials?beta=true`,zt,{query:i,...s,headers:cs([{"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(us`/v1/vaults/${n}/credentials/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/vaults/${n}/credentials/${e}/archive?beta=true`,{...s,headers:cs([{"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(us`/v1/vaults/${n}/credentials/${e}/mcp_oauth_validate?beta=true`,{...s,headers:cs([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}},Wo=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.credentials=new qo(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:cs([{"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(us`/v1/vaults/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/vaults/${e}?beta=true`,{body:i,...s,headers:cs([{"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",zt,{query:r,...t,headers:cs([{"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(us`/v1/vaults/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/vaults/${e}/archive?beta=true`,{...s,headers:cs([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Credentials=qo,e})(),jo=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.models=new Ws(this._client),this.messages=new qi(this._client),this.agents=new Js(this._client),this.environments=new nr(this._client),this.sessions=new Oo(this._client),this.deployments=new fs(this._client),this.deploymentRuns=new ps(this._client),this.vaults=new Wo(this._client),this.memoryStores=new or(this._client),this.files=new qs(this._client),this.skills=new Co(this._client),this.webhooks=new Bs(this._client),this.userProfiles=new js(this._client),this.dreams=new gs(this._client),this.tunnels=new No(this._client),this.organization=new Ao(this._client)}}return e.Models=Ws,e.Messages=qi,e.Agents=Js,e.Environments=nr,e.Sessions=Oo,e.Deployments=fs,e.DeploymentRuns=ps,e.Vaults=Wo,e.MemoryStores=or,e.Files=qs,e.Skills=Co,e.Webhooks=Bs,e.UserProfiles=js,e.Dreams=gs,e.Tunnels=No,e.Organization=Ao,e})(),Uo=class extends ss{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:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers]),stream:e.stream??!1})}},Do=class extends ss{list(e={},t){const{workspace_id:s,...n}=e??{};return this._client.getAPIList("/v1/files",zt,{query:n,...t,headers:cs([{...null!=s?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(e,t={},s){const{workspace_id:n}=t??{};return this._client.delete(us`/v1/files/${e}`,{...s,headers:cs([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}download(e,t={},s){const{workspace_id:n}=t??{};return this._client.get(us`/v1/files/${e}/content`,{...s,headers:cs([{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(us`/v1/files/${e}`,{...s,headers:cs([{...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",Xt({body:n,...t,headers:cs([{...null!=s?{"anthropic-workspace-id":s}:void 0},Ss(n.file),t?.headers])},this._client))}};function Ho(e){return e?.output_config?.format}function zo(e,t,s){const n=Ho(t);return t&&"parse"in(n??{})?Fo(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 Fo(e,t,s){let n=null;const r=e.content.map(e=>{if("text"===e.type){const s=function(e,t){const s=Ho(e);if("json_schema"!==s?.type)return null;try{return"parse"in s?s.parse(t):JSON.parse(t)}catch(n){throw new U(`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 Bo(e){return"tool_use"===e.type||"server_tool_use"===e.type}var Ko,Jo,Vo,Xo,Go=/* @__PURE__ */(()=>{class e{constructor(e,t){ji.add(this),this.messages=[],this.receivedMessages=[],Ui.set(this,void 0),Di.set(this,null),this.controller=new AbortController,Hi.set(this,void 0),zi.set(this,()=>{}),Fi.set(this,()=>{}),Bi.set(this,void 0),Ki.set(this,()=>{}),Ji.set(this,()=>{}),Vi.set(this,{}),Xi.set(this,!1),Gi.set(this,!1),Yi.set(this,!1),Qi.set(this,!1),Zi.set(this,void 0),eo.set(this,void 0),to.set(this,void 0),so.set(this,void 0),io.set(this,e=>{if(te(this,Gi,!0,"f"),W(e)&&(e=new H),e instanceof H)return te(this,Yi,!0,"f"),this._emit("abort",e);if(e instanceof U)return this._emit("error",e);if(e instanceof Error){const t=new U(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new U(String(e)))}),te(this,Hi,new Promise((e,t)=>{te(this,zi,e,"f"),te(this,Fi,t,"f")}),"f"),te(this,Bi,new Promise((e,t)=>{te(this,Ki,e,"f"),te(this,Ji,t,"f")}),"f"),se(this,Hi,"f").catch(()=>{}),se(this,Bi,"f").catch(()=>{}),te(this,Di,e,"f"),te(this,so,t?.logger??console,"f")}get response(){return se(this,Zi,"f")}get request_id(){return se(this,eo,"f")}get workspace_id(){return se(this,to,"f")}async withResponse(){te(this,Qi,!0,"f");const e=await se(this,Hi,"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 te(i,Di,{...s,stream:!0},"f"),i._run(()=>i._createMessage(t,{...s,stream:!0},{...n,headers:{...n?.headers,[_s]:"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},se(this,io,"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{se(this,ji,"m",oo).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)se(this,ji,"m",ao).call(this,e);if(r.controller.signal?.aborted)throw new H;se(this,ji,"m",co).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}_connected(e){this.ended||(te(this,Zi,e,"f"),te(this,eo,e?.headers.get("request-id"),"f"),te(this,to,e?.headers.get("anthropic-workspace-id"),"f"),se(this,zi,"f").call(this,e),this._emit("connect"))}get ended(){return se(this,Xi,"f")}get errored(){return se(this,Gi,"f")}get aborted(){return se(this,Yi,"f")}abort(){this.controller.abort()}on(e,t){return(se(this,Vi,"f")[e]||(se(this,Vi,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=se(this,Vi,"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(se(this,Vi,"f")[e]||(se(this,Vi,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{te(this,Qi,!0,"f"),"error"!==e&&this.once("error",s),this.once(e,t)})}async done(){te(this,Qi,!0,"f"),await se(this,Bi,"f")}get currentMessage(){return se(this,Ui,"f")}async finalMessage(){return await this.done(),se(this,ji,"m",no).call(this)}async finalText(){return await this.done(),se(this,ji,"m",ro).call(this)}_emit(e,...t){if(se(this,Xi,"f"))return;"end"===e&&(te(this,Xi,!0,"f"),se(this,Ki,"f").call(this));const s=se(this,Vi,"f")[e];if(s&&(se(this,Vi,"f")[e]=s.filter(e=>!e.once),s.forEach(({listener:e})=>e(...t))),"abort"===e){const e=t[0];return se(this,Qi,"f")||s?.length||Promise.reject(e),se(this,Fi,"f").call(this,e),se(this,Ji,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];se(this,Qi,"f")||s?.length||Promise.reject(e),se(this,Fi,"f").call(this,e),se(this,Ji,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",se(this,ji,"m",no).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{se(this,ji,"m",oo).call(this),this._connected(null);const t=$t.fromReadableStream(e,this.controller);for await(const e of t)se(this,ji,"m",ao).call(this,e);if(t.controller.signal?.aborted)throw new H;se(this,ji,"m",co).call(this)}finally{s&&n&&s.removeEventListener("abort",n)}}[(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,Yi=/* @__PURE__ */new WeakMap,Qi=/* @__PURE__ */new WeakMap,Zi=/* @__PURE__ */new WeakMap,eo=/* @__PURE__ */new WeakMap,to=/* @__PURE__ */new WeakMap,so=/* @__PURE__ */new WeakMap,io=/* @__PURE__ */new WeakMap,ji=/* @__PURE__ */new WeakSet,no=function(){if(0===this.receivedMessages.length)throw new U("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},ro=function(){if(0===this.receivedMessages.length)throw new U("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 U("stream ended without producing a content block with type=text");return e.join(" ")},oo=function(){this.ended||te(this,Ui,void 0,"f")},ao=function(e){if(this.ended)return;const t=se(this,ji,"m",lo).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":Bo(s)&&se(this,Vi,"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(zo(t,se(this,Di,"f"),se(this,so,"f")),!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":te(this,Ui,t,"f")}},co=function(){if(this.ended)throw new U("stream has ended, this shouldn't happen");const e=se(this,Ui,"f");if(!e)throw new U("request ended without sending any chunks");return te(this,Ui,void 0,"f"),zo(e,se(this,Di,"f"),se(this,so,"f"))},lo=function(e){let t=se(this,Ui,"f");if("message_start"===e.type){if(t)throw new U(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new U(`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&&Bo(s)){const n=(s.__json_buf||"")+e.delta.partial_json;t.content[e.index]=Ur(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&&Bo(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 $t(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}return e})(),Yo=class extends ss{create(e,t){const{user_profile_id:s,workspace_id:n,...r}=e;return this._client.post("/v1/messages/batches",{body:r,...t,headers:cs([{...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(us`/v1/messages/batches/${e}`,{...s,headers:cs([{...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",Ht,{query:n,...t,headers:cs([{...null!=s?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(e,t={},s){const{workspace_id:n}=t??{};return this._client.delete(us`/v1/messages/batches/${e}`,{...s,headers:cs([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}cancel(e,t={},s){const{workspace_id:n}=t??{};return this._client.post(us`/v1/messages/batches/${e}/cancel`,{...s,headers:cs([{...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 U(`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:cs([{Accept:"application/binary",...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>ar.fromResponse(t.response,t.controller))}},Qo=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.batches=new Yo(this._client)}create(e,t){const{user_profile_id:s,workspace_id:n,...r}=e;r.model,Zo.includes(r.model)&&r.thinking&&r.thinking.type;let i=t?.timeout??this._client._options.timeout;if(!r.stream&&null==i){const e=lr[r.model]??void 0;i=this._client.calculateNonstreamingTimeout(r.max_tokens,e)}const o=ks(r.tools,r.messages);return this._client.post("/v1/messages",{body:r,timeout:i??6e5,...t,headers:cs([{...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=>Fo(t,e,this._client.logger??console))}stream(e,t){return Go.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:cs([{...null!=s?{"anthropic-user-profile-id":s}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}}return e.Batches=Yo,e})(),Zo=["claude-mythos-preview","claude-opus-4-6"],ea=class extends ss{retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(us`/v1/models/${e}`,{...s,headers:cs([{...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",Ht,{query:r,...t,headers:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}},ta=class extends ss{create(e,t,s){const{workspace_id:n,...r}=t;return this._client.post(us`/v1/skills/${e}/versions`,Xt({body:r,...s,headers:cs([{...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(us`/v1/skills/${n}/versions/${e}`,{...s,headers:cs([{...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e,t={},s){const{workspace_id:n,...r}=t??{};return this._client.getAPIList(us`/v1/skills/${e}/versions`,zt,{query:r,...s,headers:cs([{...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(us`/v1/skills/${n}/versions/${e}`,{...s,headers:cs([{...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},sa=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.versions=new ta(this._client)}create(e,t){const{workspace_id:s,...n}=e;return this._client.post("/v1/skills",Xt({body:n,...t,headers:cs([{...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(us`/v1/skills/${e}`,{...s,headers:cs([{...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",zt,{query:n,...t,headers:cs([{...null!=s?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(e,t={},s){const{workspace_id:n}=t??{};return this._client.delete(us`/v1/skills/${e}`,{...s,headers:cs([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}}return e.Versions=ta,e})(),na=/* @__PURE__ */(()=>{class e{get credentials(){return this._authState.provider}constructor({baseURL:e=Qe("ANTHROPIC_BASE_URL"),apiKey:t,authToken:s,webhookKey:n=Qe("ANTHROPIC_WEBHOOK_SIGNING_KEY")??null,...r}={}){if(Ko.add(this),this._requestAuthFlags=/* @__PURE__ */new WeakMap,Vo.set(this,void 0),void 0===t&&(t=null!=r.profile?null:Qe("ANTHROPIC_API_KEY")??null),void 0===s&&(s=null!=r.profile?null:Qe("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 U("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??Jo.DEFAULT_TIMEOUT,this.logger=i.logger??console,this.logLevel="warn",this.logLevel=st(i.logLevel,"ClientOptions.logLevel",ht(this))??st(Qe("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",ht(this))??"warn",this.fetchOptions=i.fetchOptions,this.maxRetries=he("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`")}(),te(this,Vo,Se,"f"),this.middleware=[...i.middleware??[]];const o=Qe("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=xt(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=>{ht(this).debug("credential cache write failed (best-effort)",e)},onSafetyWarning:e=>{ht(this).warn(e)}}}_credentialsFetch(){return Nt(this.fetch,this.middleware,void 0,this)}_makeTokenCache(e){return new Ye(e,e=>{ht(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 bt();if(null===n)return null;const r=e??await kt();if(null===r)return null;mt(r);const{fs:i,path:o}=await(import("./node.browser-Aw6ESngp.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=Qe("ANTHROPIC_ORGANIZATION_ID"),t=Qe("ANTHROPIC_IDENTITY_TOKEN_FILE"),s=Qe("ANTHROPIC_FEDERATION_RULE_ID");return s&&e?{fromFile:!1,config:{organization_id:e,workspace_id:Qe("ANTHROPIC_WORKSPACE_ID"),base_url:Qe("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:s,service_account_id:Qe("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:t?{source:"file",path:t}:void 0,scope:Qe("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=Qe("ANTHROPIC_ORGANIZATION_ID")),l.workspace_id??(l.workspace_id=Qe("ANTHROPIC_WORKSPACE_ID")),l.base_url??(l.base_url=Qe("ANTHROPIC_BASE_URL")),(t=l.authentication).scope??(t.scope=Qe("ANTHROPIC_SCOPE")),"oidc_federation"===l.authentication.type){if(!l.authentication.identity_token){const e=Qe("ANTHROPIC_IDENTITY_TOKEN_FILE");e&&(l.authentication.identity_token={source:"file",path:e})}l.authentication.federation_rule_id||(l.authentication.federation_rule_id=Qe("ANTHROPIC_FEDERATION_RULE_ID")??""),(s=l.authentication).service_account_id??(s.service_account_id=Qe("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:l,fromFile:!0}})(t);if(!s)return null;const{config:n,fromFile:r}=s;return xt(n.authentication.credentials_path||!r?n:{...n,authentication:{...n.authentication,credentials_path:await yt(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 U(`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,cs([{Authorization:`Bearer ${t}`}])}return cs([await this.apiKeyAuth(e),await this.bearerAuth(e)])}}async apiKeyAuth(e){if(null!=this.apiKey)return cs([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(null!=this.authToken)return cs([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return function(e){return function(e,t={}){let s=e;const n=function(e=Ce){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||Ce.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=xe;if(void 0!==e.format){if(!Ae(Re,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const n=Re[s];let r,i=Ce.filter;if(("function"==typeof e.filter||re(e.filter))&&(i=e.filter),r=e.arrayFormat&&e.arrayFormat in Oe?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":Ce.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||Ce.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:Ce.addQueryPrefix,allowDots:o,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:Ce.allowEmptyArrays,arrayFormat:r,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Ce.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?Ce.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:Ce.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:Ce.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:Ce.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:Ce.encodeValuesOnly,filter:i,format:s,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:Ce.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:Ce.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Ce.strictNullHandling}}(t);let r,i;"function"==typeof n.filter?(i=n.filter,s=i("",s)):re(n.filter)&&(i=n.filter,r=i);const o=[];if("object"!=typeof s||null===s)return"";const a=Oe[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]||Pe(o,Ne(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 ${pe}`}makeStatusError(e,t,s,n){return D.generate(e,t,s,n)}buildURL(e,t,s){const n=!se(this,Ko,"m",Xo).call(this)&&s||this.baseURL,r=(e=>ne.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 ae(i)&&ae(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 U("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??[],We].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 jt(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){const n=await e;let r=he("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 H;const d=new AbortController,u=await this.fetchWithTimeout(o,i,a,d,n,{requestLogID:c,retryOfRequestLogID:s}).catch(j),p=Date.now();if(u instanceof globalThis.Error){ye(d);const e=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new H;const r=W(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),Lt(e)||W(e)||e instanceof z||e instanceof B)return!0;e=e.cause}return!1}(u))throw ht(this).info(`[${c}] middleware error (not retryable)`),ut(ht(this),`[${c}] middleware error (not retryable)`,{retryOfRequestLogID:s,url:o,durationMs:p-h,message:u.message}),u;if(t)return ht(this).info(`[${c}] connection ${r?"timed out":"failed"} - ${e}`),ut(ht(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(ht(this).info(`[${c}] connection ${r?"timed out":"failed"} - error; no more retries left`),ut(ht(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 F;if(i&&!Lt(u))throw u;throw new z({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),ye(d),ht(this).info(`${f} - ${e}`),ut(ht(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";ht(this).info(`${f} - ${r}`);const i=await u.text().catch(e=>j(e).message),o=de(i),a=o?void 0:i;throw ut(ht(this),`[${c}] response error (${r})`,{retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,message:a,durationMs:Date.now()-h}),ye(d),this.makeStatusError(u.status,o,a,u.headers)}return ht(this).info(f),ut(ht(this),`[${c}] response start`,{retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,durationMs:p-h}),function(e,t){_e.has(t)&&we?.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 Dt(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){_e.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&&ut(ht(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 Nt(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 ue(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 U("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&&he("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=cs([{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),"X-Stainless-Timeout":String(Math.trunc(r/1e3)),...me(),...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=cs([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:ve(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)}:se(this,Vo,"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 Jo=e,Vo=/* @__PURE__ */new WeakMap,Ko=/* @__PURE__ */new WeakSet,Xo=function(){return"https://api.anthropic.com"!==this.baseURL},e.Anthropic=Jo,e.DEFAULT_TIMEOUT=6e5,e.AnthropicError=U,e.APIError=D,e.APIConnectionError=z,e.APIConnectionTimeoutError=F,e.APIUserAbortError=H,e.NotFoundError=X,e.ConflictError=G,e.RateLimitError=Q,e.BadRequestError=K,e.AuthenticationError=J,e.InternalServerError=Z,e.PermissionDeniedError=V,e.UnprocessableEntityError=Y,e.toFile=es,e.HUMAN_PROMPT="\\n\\nHuman:",e.AI_PROMPT="\\n\\nAssistant:",e})(),ra=/* @__PURE__ */(()=>{class e extends na{constructor(){super(...arguments),this.completions=new Uo(this),this.messages=new Qo(this),this.models=new ea(this),this.files=new Do(this),this.skills=new sa(this),this.beta=new jo(this)}}return e.Completions=Uo,e.Messages=Qo,e.Models=ea,e.Files=Do,e.Skills=sa,e.Beta=jo,e})(),ia=["The compiled grammar is too large","Too many strict tools (","Schemas contains too many parameters with union types ("];function oa(e){return ia.some(t=>e.includes(t))}var aa=/* @__PURE__ */new Set;function ca(e){if(void 0!==e&&(aa.add(e),aa.size>1e4)){const e=aa.values().next().value;void 0!==e&&aa.delete(e)}}q(e=>{e?aa.delete(e):aa.clear()});var la=/* @__PURE__ */e({stream:()=>Na,streamSimple:()=>qa});function ha(e,t){return e||("long"===y("PI_CACHE_RETENTION",t)?"long":"short")}var da=new Map(["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"].map(e=>[e.toLowerCase(),e])),ua=e=>da.get(e.toLowerCase())??e,pa=(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 fa(e){return{type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}}}function ga(e){if(!e.some(e=>"image"===e.type))return A(e.map(e=>e.text).join("\n"));const t=e.map(e=>"text"===e.type?{type:"text",text:A(e.text)}:fa(e));return t.some(e=>"text"===e.type)||t.unshift({type:"text",text:"(see attached image)"}),t}var ma={name:"__pi_deferred_placeholder__",description:"Reserved placeholder. Never available. Never call this.",input_schema:{type:"object",properties:{},required:[]},defer_loading:!0};function _a(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,supportsMessageThreads:e.compat?.supportsMessageThreads??("anthropic"===e.provider&&e.baseUrl.includes("api.anthropic.com"))}}var wa=/* @__PURE__ */new Map,ya=/* @__PURE__ */new Set(["thread_not_found","thread_already_continued","thread_continue_in_flight","thread_fingerprint_mismatch"]);function ba(e,t){if(wa.delete(e),wa.set(e,t),wa.size>1e4){const e=wa.keys().next().value;void 0!==e&&wa.delete(e)}}function va(e,t,s){const{system:n,tools:r,thinking:i,output_config:o,tool_choice:a,betas:c,fallbacks:l}=t,h=JSON.stringify([e.provider,e.baseUrl,t.model,n,r,i,o,a,c,l]),d=JSON.stringify(s,(e,t)=>{if("cache_control"!==e)return"content"===e&&"string"==typeof t?[{type:"text",text:t}]:t});return b(h+d)}function ka(e,t){return{sessionId:e,body:{...t,thread:{type:"create"}}}}function Sa(e,t,s){const n=wa.get(t);if("off"!==n){if(void 0!==n&&s.messages.length>n.prefixCount&&va(e,s,s.messages.slice(0,n.prefixCount))===n.prefixHash){wa.delete(t);const{system:e,tools:r,...i}=s;return{body:{...i,messages:s.messages.slice(n.prefixCount),thread:{type:"continue",previous_message_id:n.replyId}},sessionId:t}}return ka(t,s)}}async function xa(e,t,s,n,i){try{return{response:await s(e.body),thread:e}}catch(o){if(i?.aborted||!(o instanceof ra.APIError))throw o;const a=function(e){const t=e.error?.error?.details?.error_code;return"string"==typeof t?t:void 0}(o),c=void 0!==a&&ya.has(a),l="thread_unsupported_request"===a||void 0===a&&400===o.status&&o.message.includes("thread");if(!c&&!l)throw o;if(r(n,{type:"anthropic_thread_fallback",timestamp:Date.now(),error:{message:o.message},details:{reason:a??String(o.status)}}),c){const n=ka(e.sessionId,t);return{response:await s(n.body),thread:n}}const h=await s(t);return ba(e.sessionId,"off"),{response:h,thread:void 0}}}function Ia(...e){const t={};for(const s of e)s&&Object.assign(t,s);return t}function Ra(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 Aa(e,t){return!!e||Ra(t,"authorization")||Ra(t,"x-api-key")||Ra(t,"cf-aig-authorization")}function $a(e,t,s){if(!Aa(t,s))throw new Error(`No API key for provider: ${e}`)}q(e=>{e?wa.delete(e):wa.clear()});var Ta,Ea=class extends ra{_shouldResolveDefaultCredentials(){return!1}};function Ma(e,t,s,n){if("anthropic"!==e.provider||Aa(t,s))return;const r=y(h,n),i=y(l,n),a=y(u,n);return r&&i&&a?{organization_id:i,workspace_id:y(d,n),authentication:{type:"oidc_federation",federation_rule_id:r,service_account_id:y(o,n),identity_token:{source:"file",path:a}}}:void 0}var Oa=/* @__PURE__ */new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);function Pa(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 Ca(e,t){if(""===e)return Pa(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 La(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 Na=(e,t,n)=>{const i=new s,o=_a(e),l=p(t,o.supportsMidConvoSystemMessages),h=c(l.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 d,u,p,f=e;const y="none"===ha(n?.cacheRetention,n?.env)?void 0:n?.sessionId,b=o.supportsMessageThreads?y:void 0;if(n?.client)d=n.client,u=!1;else{const t=n?.apiKey,s=Ma(e,t,n?.headers,n?.env);let r;if(s||$a(e.provider,t,n?.headers),"github-copilot"===e.provider){const e=w(l.messages);r=v({messages:l.messages,hasImages:e})}const i=function(e,t,s,n,r,i,o,a){if("github-copilot"===e.provider)return{client:new Ea({apiKey:null,authToken:t??null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:n,defaultHeaders:Ia(g(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 Ea({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:n,defaultHeaders:Ia({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","user-agent":"claude-cli/2.1.322","x-app":"cli"},e.headers,s)}),isOAuthToken:!0};const c=_a(e),l={};i&&c.sendSessionAffinityHeaders&&(l["openrouter"===c.sessionAffinityFormat?"x-session-id":"x-session-affinity"]=i);const h=Ia(g(e,a),{accept:"application/json","anthropic-dangerous-direct-browser-access":"true"},l,e.headers,s);if(o){const t=JSON.stringify([e.baseUrl,o]);return Ta?.key===t&&Ta.fetch===n||(Ta={key:t,fetch:n,client:new Ea({apiKey:null,authToken:null,config:o,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:n})}),{client:Ta.client.withOptions({defaultHeaders:h}),isOAuthToken:!1}}return{client:new Ea({apiKey:t??null,authToken:null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:n,defaultHeaders:h}),isOAuthToken:!1}}(e,t,n?.headers,n?.fetch,r,y,s,n?.identity);d=i.client,u=i.isOAuthToken}const S={...n?.signal?{signal:n.signal}:{},...void 0!==n?.timeoutMs?{timeout:n.timeoutMs}:{},maxRetries:0},A=e=>x(()=>d.beta.messages.create(e,S).asResponse(),{maxRetries:n?.maxRetries,maxRetryDelayMs:n?.maxRetryDelayMs,signal:n?.signal});let $,T,E,M=(s=n?.sessionId,void 0!==s&&aa.has(s));for(;;){n?.signal?.throwIfAborted();const s=Wa(e,l,u,n,{disablePreferredStrictTools:M,messageThreads:void 0!==b});s.providerThinkingLevel&&(t.providerThinkingLevel=s.providerThinkingLevel),T=s.params;const i=await(n?.onPayload?.(T,e));void 0!==i&&(T={...i,stream:!0});const o=void 0!==b&&!0!==n?.disableContinuation?Sa(e,b,T):void 0;try{const e=o?await xa(o,T,A,t,n?.signal):{response:await A(T),thread:void 0};$=e.response,E=e.thread;break}catch(c){if(n?.signal?.aborted||M||!s.hasPreferredStrictTools||!(c instanceof ra.APIError)||400!==c.status||"invalid_request_error"!==c.type||!oa(c.message))throw c;M=!0,ca(n?.sessionId),r(t,{type:"anthropic_strict_tools_fallback",timestamp:Date.now(),error:{message:c.message},details:{reason:"strict_tool_limits_exceeded"}})}}await(n?.onResponse?.({status:$.status,headers:k($.headers)},e)),i.push({type:"start",partial:t});const P=/* @__PURE__ */new Map,C=e=>{const s=P.get(e);return void 0===s?void 0:{...s,block:t.content[s.contentIndex]}};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=La(i);for(;a;){i=a.rest;const e=Ca(a.line,r);e&&(yield e),a=La(i)}}i+=n.decode();let e=La(i);for(;e;){i=e.rest;const t=Ca(e.line,r);t&&(yield t),e=La(i)}if(i.length>0){const e=Ca(i,r);e&&(yield e)}const o=Pa(r);o&&(yield o)}finally{s.releaseLock()}}(e.body,t)){if("error"===r.event)throw new Error(r.data);if(Oa.has(r.event??""))try{const e=m(r.data);"message_start"===e.type?s=!0:"message_stop"===e.type&&(n=!0),yield e}catch(c){const t=c instanceof Error?c.message:String(c);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")}($,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)&&(p=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;f=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(f,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}"text"===s.content_block.type?(t.content.push({type:"text",text:s.content_block.text??""}),P.set(s.index,{contentIndex:t.content.length-1}),i.push({type:"text_start",contentIndex:t.content.length-1,partial:t})):"thinking"===s.content_block.type?(t.content.push({type:"thinking",thinking:s.content_block.thinking??"",thinkingSignature:s.content_block.signature??""}),P.set(s.index,{contentIndex:t.content.length-1}),i.push({type:"thinking_start",contentIndex:t.content.length-1,partial:t})):"redacted_thinking"===s.content_block.type?(t.content.push({type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:s.content_block.data,redacted:!0}),P.set(s.index,{contentIndex:t.content.length-1}),i.push({type:"thinking_start",contentIndex:t.content.length-1,partial:t})):"tool_use"===s.content_block.type&&(t.content.push({type:"toolCall",id:s.content_block.id,name:u?pa(s.content_block.name,h):s.content_block.name,arguments:s.content_block.input??{}}),P.set(s.index,{contentIndex:t.content.length-1,arguments:new _}),i.push({type:"toolcall_start",contentIndex:t.content.length-1,partial:t}))}else if("content_block_delta"===s.type){const e=C(s.index);"text_delta"===s.delta.type?"text"===e?.block.type&&(e.block.text+=s.delta.text,i.push({type:"text_delta",contentIndex:e.contentIndex,delta:s.delta.text,partial:t})):"thinking_delta"===s.delta.type?"thinking"===e?.block.type&&(e.block.thinking+=s.delta.thinking,i.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:s.delta.thinking,partial:t})):"input_json_delta"===s.delta.type?"toolCall"===e?.block.type&&void 0!==e.arguments&&(e.block.arguments=e.arguments.append(s.delta.partial_json),i.push({type:"toolcall_delta",contentIndex:e.contentIndex,delta:s.delta.partial_json,partial:t})):"signature_delta"===s.delta.type&&"thinking"===e?.block.type&&(e.block.thinkingSignature=e.block.thinkingSignature||"",e.block.thinkingSignature+=s.delta.signature)}else if("content_block_stop"===s.type){const e=C(s.index);if(P.delete(s.index),e){const{block:s,contentIndex:n}=e;"text"===s.type?i.push({type:"text_end",contentIndex:n,content:s.text,partial:t}):"thinking"===s.type?i.push({type:"thinking_end",contentIndex:n,content:s.thinking,partial:t}):"toolCall"===s.type&&void 0!==e.arguments&&(Object.assign(s,e.arguments.finish()),i.push({type:"toolcall_end",contentIndex:n,toolCall:s,partial:t}))}}else if("message_delta"===s.type){const n=s.input_transformations;if(Array.isArray(n)&&(p=n),s.delta.stop_reason){t.rawStopReason=s.delta.stop_reason;const e=Ja(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(f,t.usage),I(e)&&s.usage&&R(t.usage,s.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");E&&function(e,t,s,n,r,i){if(void 0===n.responseId||void 0!==n.responseModel)return;const o=Da(O([n],e,ja),r,void 0,i).messages.filter(e=>"assistant"===e.role),a=[...s.messages,...o];ba(t.sessionId,{prefixCount:a.length,prefixHash:va(e,s,a),replyId:n.responseId})}(e,E,T,t,u,o.allowEmptySignature),p&&p.length>0&&r(t,{type:"anthropic_input_transformations",timestamp:Date.now(),details:{transformations:p.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(c){t.stopReason=n?.signal?.aborted?"aborted":"error",t.errorMessage=c instanceof Error?S(c):JSON.stringify(c),i.push({type:"error",reason:t.stopReason,error:t}),i.end()}var s})(),i},qa=(e,t,s)=>{Ma(e,s?.apiKey,s?.headers,s?.env)||$a(e.provider,s?.apiKey,s?.headers);const n={...E(e,t,s,s?.apiKey),toolChoice:s?.toolChoice};if(!s?.reasoning)return Na(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 Na(e,t,{...n,thinkingEnabled:!0,effort:r})}const r=C(n.maxTokens,e.maxTokens,s.reasoning,s.thinkingBudgets),i=$(e,t,r.maxTokens);return Na(e,t,{...n,maxTokens:i,thinkingEnabled:!0,thinkingBudgetTokens:Math.min(r.thinkingBudget,Math.max(0,i-1024))})};function Wa(e,t,s,r,o){const{cacheControl:a}=function(e,t,s){const n=ha(t,s);if("none"===n)return{retention:n};const r="long"===n&&_a(e).supportsLongCacheRetention?"1h":void 0;return{retention:n,cacheControl:{type:"ephemeral",...r&&{ttl:r}}}}(e,r?.cacheRetention,r?.env),l=_a(e),h=i(t.messages),d=h?n(h):"",u=O(t.messages,e,ja),p=h?u.slice(1):u;let f=!1;const g=(e,t)=>{const n=function(e,t,s,n,r,i=!1){return e?e.map((o,a)=>{const c=i&&M(o)?void 0:T(o,n,Ka),l=P(o,c),h=l,d={type:"object",properties:h.properties??{},required:h.required??[],...void 0===h.$defs?{}:{$defs:h.$defs},...void 0===h.definitions?{}:{definitions:h.definitions}},u=!0===c?{...l,...d}:d;return{name:t?ua(o.name):o.name,description:o.description,...s?{eager_input_streaming:!0}:{},...!0===c?{strict:!0}:{},input_schema:u,...r&&a===e.length-1?{cache_control:r}:{}}}):[]}(e,s,l.supportsEagerToolInputStreaming,l.supportsStrictTools,t,o.disablePreferredStrictTools);return n.some((t,s)=>!0===t.strict&&M(e[s]))&&(f=!0),n},m=h?.toolsAdded??[],_=l.supportsMidConvoSystemMessages&&l.supportsMidConvoToolChanges&&m.length>0,w=e.reasoning&&!1===r?.thinkingEnabled&&null!==e.thinkingLevelMap?.off,y=!0===e.compat?.supportsMidConvoEffort&&!w,b=Da(p,s,a,l.allowEmptySignature,y?e.provider:void 0,_?g:void 0),v=r?.effort??"high",k=function(e,t,s,{isOAuthToken:n,nativeToolChanges:r,messageThreads:i}){let o;for(const c of[e.headers,s?.headers])for(const[e,t]of Object.entries(c??{}))"anthropic-beta"===e.toLowerCase()&&(o=t);if(null===o)return[];if(void 0!==o)return[...new Set(o.split(",").map(e=>e.trim()).filter(e=>e.length>0))];const a=[];return n&&a.push("claude-code-20250219","oauth-2025-04-20"),function(e,t){return c(t.messages).length>0&&!_a(e).supportsEagerToolInputStreaming}(e,t)&&a.push("fine-grained-tool-streaming-2025-05-14"),e.reasoning&&!0===s?.thinkingEnabled&&(s.interleavedThinking??!0)&&!0!==e.compat?.forceAdaptiveThinking&&a.push("interleaved-thinking-2025-05-14"),function(e){return(e.compat?.allowedFallbackModels?.length??0)>0}(e)&&a.push("server-side-fallback-2026-07-01"),!0===e.compat?.supportsMidConvoEffort&&a.push("mid-conversation-output-config-2026-07-01","thinking-binding-controls-2026-08-01"),r&&a.push("inline-tools-2026-09-15"),i&&a.push("message-threads-2026-08-12"),[...new Set(a)]}(e,t,r,{isOAuthToken:s,nativeToolChanges:_,messageThreads:o.messageThreads}),S={model:e.id,messages:y?za(b,v):b.messages,max_tokens:r?.maxTokens??e.maxTokens,stream:!0,...k.length>0?{betas:k}:{}};s?(S.system=[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude.",...a?{cache_control:a}:{}}],d&&S.system.push({type:"text",text:A(d),...a?{cache_control:a}:{}})):d&&(S.system=[{type:"text",text:A(d),...a?{cache_control:a}:{}}]),void 0!==r?.temperature&&!r?.thinkingEnabled&&!0!==e.compat?.supportsMidConvoEffort&&l.supportsTemperature&&(S.temperature=r.temperature);const x=l.supportsCacheControlOnTools?a:void 0;if(_)S.tools=[...g(m,x),ma];else{const e=c(t.messages);e.length>0&&(S.tools=g(e,x))}if(w)S.thinking={type:"disabled"};else if(y)S.thinking={type:"adaptive",display:r?.thinkingDisplay??"summarized",block_binding:{prefix_mismatch_behavior:"drop_block"}},S.output_config={effort:"low"};else if(e.reasoning&&r?.thinkingEnabled){const t=r.thinkingDisplay??"summarized";!0===e.compat?.forceAdaptiveThinking?(S.thinking={type:"adaptive",display:t},r.effort&&(S.output_config={effort:r.effort})):S.thinking={type:"enabled",budget_tokens:r.thinkingBudgetTokens||1024,display:t}}if(r?.metadata){const e=r.metadata.user_id;"string"==typeof e&&(S.metadata={user_id:e})}r?.toolChoice&&("string"==typeof r.toolChoice?S.tool_choice={type:r.toolChoice}:S.tool_choice=r.toolChoice);const I=e.compat?.allowedFallbackModels;return I&&I.length>0&&(S.fallbacks=I.map(e=>({model:e.model}))),{params:S,hasPreferredStrictTools:f,providerThinkingLevel:y?v:void 0}}function ja(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function Ua(e,t=e.content){return{type:"tool_result",tool_use_id:e.toolCallId,content:ga(t),is_error:e.isError}}function Da(e,t,s,n=!1,r,i){const o=[],a=/* @__PURE__ */new Map,c=[],l=()=>{o.push(...c),c.length=0};for(let h=0;h<e.length;h++){const s=e[h];if("system"===s.role){const e=f(s),n=[];if(e.length>0&&n.push({type:"text",text:A(e)}),i){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?ua(i.name):i.name}});for(const t of i(e))n.push({type:"tool_addition",tool:{type:"tool_definition",definition:t}})}n.length>0&&c.push({role:"system",content:n})}else if("user"===s.role)if("string"==typeof s.content)s.content.trim().length>0&&o.push({role:"user",content:A(s.content)});else{const e=s.content.map(e=>"text"===e.type?{type:"text",text:A(e.text)}:fa(e)).filter(e=>"text"!==e.type||e.text.trim().length>0);if(0===e.length)continue;o.push({role:"user",content:e})}else if("assistant"===s.role){const e=[];for(const r of s.content)if("text"===r.type){if(0===r.text.trim().length)continue;e.push({type:"text",text:A(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:A(r.thinking),signature:t}):e.push(n?{type:"thinking",thinking:A(r.thinking),signature:""}:{type:"text",text:A(r.thinking)})}else"toolCall"===r.type&&e.push({type:"tool_use",id:r.id,name:t?ua(r.name):r.name,input:r.arguments??{}});if(0===e.length)continue;l();const i=o.length;o.push({role:"assistant",content:e}),void 0!==r&&"anthropic-messages"===s.api&&s.provider===r&&Ha(s.providerThinkingLevel)&&a.set(i,s.providerThinkingLevel)}else if("toolResult"===s.role){const t=[],s=[];let n=h;for(;n<e.length&&"toolResult"===e[n].role;){const r=e[n],i=L(r);t.push(Ua(r,i?.content)),i&&s.push({type:"text",text:i.caption},...i.images.map(fa)),n++}h=n-1,o.push({role:"user",content:[...t,...s]})}}if(l(),s&&o.length>0){const e=o[o.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:o,assistantLevels:a}}function Ha(e){return"low"===e||"medium"===e||"high"===e||"xhigh"===e||"max"===e}function za(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 Fa=/* @__PURE__ */new Set(["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","maxItems","uniqueItems","minContains","maxContains","minProperties","maxProperties"]),Ba=/* @__PURE__ */new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),Ka=(e,t)=>!(!Fa.has(e)&&("minItems"===e?0===t||1===t:"format"!==e||"string"==typeof t&&Ba.has(t)));function Ja(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{ee as n,U as r,Na as stream,qa as streamSimple,la 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-WNHmnFyz.js";import{E 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-DImbnOQx.js";import{a as m,i as _,n as w,o as y,r as b,t as v}from"./github-copilot-headers-CdUV5uSi.js";import{n as k,o as S,t as x}from"./provider-retry-jOpF7gmO.js";import{n as I,t as R}from"./openrouter-cost-BcsrXcCZ.js";import{_ as A,a as $,g as T,i as E,m as M,n as O,p as P,r as C,t as L}from"./transform-messages-sc733Lgj.js";var N=/* @__PURE__ */new Set;function q(e){return N.add(e),()=>{N.delete(e)}}function W(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var j=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)},U=/* @__PURE__ */(()=>{class e extends Error{}return e})(),D=class e extends U{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 z({message:n,cause:j(s)});const i=s,o=i?.error?.type;return 400===t?new K(t,i,n,r,o):401===t?new J(t,i,n,r,o):403===t?new V(t,i,n,r,o):404===t?new X(t,i,n,r,o):409===t?new G(t,i,n,r,o):422===t?new Y(t,i,n,r,o):429===t?new Q(t,i,n,r,o):t>=500?new Z(t,i,n,r,o):new e(t,i,n,r,o)}},H=class extends D{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},z=class extends D{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},F=class extends z{constructor({message:e}={}){super({message:e??"Request timed out."})}},B=class extends U{constructor(e,{cause:t}={}){super(e??"Retryable error."),void 0!==t&&(this.cause=t)}},K=class extends D{},J=class extends D{},V=class extends D{},X=class extends D{},G=class extends D{},Y=class extends D{},Q=class extends D{},Z=class extends D{},ee=5e3;function te(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 se(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 ne=/^[a-z][a-z0-9+.-]*:/i,re=e=>(re=Array.isArray)(e),ie=re;function oe(e){return"object"!=typeof e?{}:e??{}}function ae(e){if(!e)return!0;for(const t in e)return!1;return!0}function ce(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}var le,he=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new U(`${e} must be an integer`);if(t<0)throw new U(`${e} must be a positive integer`);return t},de=e=>{try{return JSON.parse(e)}catch(t){return}},ue=(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})}),pe="0.129.0",fe=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",ge=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",me=()=>le??(le=(()=>{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":pe,"X-Stainless-OS":ge(Deno.build.os),"X-Stainless-Arch":fe(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":pe,"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":pe,"X-Stainless-OS":ge(globalThis.process.platform??"unknown"),"X-Stainless-Arch":fe(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":pe,"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":pe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}})()),_e=/* @__PURE__ */new WeakMap,we="function"==typeof globalThis.FinalizationRegistry?new globalThis.FinalizationRegistry(e=>ye(e)):null;function ye(e){const t=_e.get(e);t&&(_e.delete(e),we?.unregister(e),t())}function be(...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 ve(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return be({start(){},async pull(e){const{done:s,value:n}=await t.next();s?e.close():e.enqueue(n)},async cancel(){await(t.return?.())}})}function ke(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 Se=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),xe="RFC3986",Ie=e=>String(e),Re={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:Ie},Ae=(e,t)=>(Ae=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty))(e,t),$e=/* @__PURE__ */(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),Te=1024;function Ee(e,t){if(re(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}var Me,Oe={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},Pe=function(e,t){Array.prototype.push.apply(e,re(t)?t:[t])},Ce={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+=Te){const e=i.length>=Te?i.slice(a,a+Te):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]=$e[n]:n<2048?t[t.length]=$e[192|n>>6]+$e[128|63&n]:n<55296||n>=57344?t[t.length]=$e[224|n>>12]+$e[128|n>>6&63]+$e[128|63&n]:(s+=1,n=65536+((1023&n)<<10|1023&e.charCodeAt(s)),t[t.length]=$e[240|n>>18]+$e[128|n>>12&63]+$e[128|n>>6&63]+$e[128|63&n])}o+=t.join("")}return o},encodeValuesOnly:!1,format:xe,formatter:Ie,indices:!1,serializeDate:e=>(Me??(Me=Function.prototype.call.bind(Date.prototype.toISOString)))(e),skipNulls:!1,strictNullHandling:!1},Le={};function Ne(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(Le))&&!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(Le)&&(b=0)}if("function"==typeof l?w=l(t,w):w instanceof Date?w=u?.(w):"comma"===s&&re(w)&&(w=Ee(w,function(e){return e instanceof Date?u?.(e):e})),null===w){if(i)return c&&!g?c(t,Ce.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,Ce.encoder,m,"key",p);return[f?.(e)+"="+f?.(c(w,Ce.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&&re(w))g&&c&&(w=Ee(w,c)),x=[{value:w.length>0?w.join(",")||null:void 0}];else if(re(l))x=l;else{const e=Object.keys(w);x=h?e.sort(h):e}const I=a?String(t).replace(/\./g,"%2E"):String(t),R=n&&re(w)&&1===w.length?I+"[]":I;if(r&&re(w)&&0===w.length)return R+"[]";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=re(w)?"function"==typeof s?s(R,v):R:R+(d?"."+v:"["+v+"]");_.set(e,b);const I=/* @__PURE__ */new WeakMap;I.set(Le,_),Pe(S,Ne(y,k,s,n,r,i,o,a,"comma"===s&&g&&re(w)?null:c,l,h,d,u,p,f,g,m,I))}return S}var qe="/v1/oauth/token",We="oauth-2025-04-20",je=1<<20;function Ue(e){if(!e)return;let t;try{t=new URL(e)}catch(n){throw new Je(`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 Je(`Refusing to send credential over non-https token endpoint "${e}"`)}async function De(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>je){const e=je-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 Je(`Token endpoint returned non-JSON response (status ${e.status})`,e.status,Fe(s),t)}if(!n.access_token)throw new Je(`Token endpoint response missing access_token: ${JSON.stringify(Fe(n))}`,e.status,Fe(n),t);if(n.token_type&&"bearer"!==n.token_type.toLowerCase())throw new Je(`Token endpoint response: unsupported token_type "${n.token_type}" (want Bearer)`,e.status,Fe(n),t);return n}var He=2e3,ze=/* @__PURE__ */new Set(["error","error_description","error_uri"]);function Fe(e){if(null==e)return e;if("string"==typeof e){let t;try{t=JSON.parse(e)}catch{return e.length<=He?e:e.slice(0,He)+`... <${e.length-He} more chars>`}return JSON.stringify(Fe(t))}if("object"==typeof e&&!Array.isArray(e)){const t={};for(const[s,n]of Object.entries(e))ze.has(s)&&(t[s]=n);return t}return null}async function Be(e,t=e=>{}){if("undefined"==typeof process)return;const{fs:s}=await(import("./node.browser-BDF4XvCU.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 Je(`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 Je(`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 Ke(e,t){const{fs:s,path:n}=await(import("./node.browser-BDF4XvCU.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 Je=class extends U{constructor(e,t=null,s=null,n=null){super(e),this.statusCode=t,this.body=s,this.requestId=n}};function Ve(){return Math.floor(Date.now()/1e3)}var Xe,Ge,Ye=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-Ve();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||Ve()-this.lastAdvisoryError<5||this.doRefresh().catch(e=>{this.lastAdvisoryError=Ve(),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}},Qe=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 Ze(e){let t;return(Xe??(t=new globalThis.TextEncoder,Xe=t.encode.bind(t)))(e)}function et(e){let t;return(Ge??(t=new globalThis.TextDecoder,Ge=t.decode.bind(t)))(e)}var tt={off:0,error:200,warn:300,info:400,debug:500},st=(e,t,s)=>{var n,r;if(e)return n=tt,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(tt))}`)};function nt(){}function rt(e,t,s){return!t||tt[e]>tt[s]?nt:t[e].bind(t)}var it,ot,at={error:nt,warn:nt,info:nt,debug:nt},ct=/* @__PURE__ */new WeakMap;function lt(e,t){const s=ct.get(e);if(s&&s[0]===t)return s[1];const n={error:rt("error",e,t),warn:rt("warn",e,t),info:rt("info",e,t),debug:rt("debug",e,t)};return ct.set(e,[t,n]),n}function ht(e){const t=e.logger,s=e.logLevel??"off";return t?lt(t,s):at}function dt(){const e=Qe("ANTHROPIC_LOG");return ot&&e===it||(it=e,ot=lt(console,st(e,"process.env['ANTHROPIC_LOG']",lt(console,"warn"))??"warn")),ot}function ut(e,t,s){e.debug!==nt&&e.debug(t,pt(s))}var pt=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),ft=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return ft=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))},gt=/^[A-Za-z0-9_.-]+$/;function mt(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(!gt.test(e))throw new Error(`profile name "${e}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var _t,wt,yt=async(e,t)=>{if(e?.authentication.credentials_path)return e.authentication.credentials_path;const s=await bt();if(!s)return null;const n=t??await kt();if(!n)return null;mt(n);const{path:r}=await(import("./node.browser-BDF4XvCU.js"));return r.join(s,"credentials",`${n}.json`)},bt=async()=>{if(!vt())return null;const{path:e}=await(import("./node.browser-BDF4XvCU.js")),t=Qe("ANTHROPIC_CONFIG_DIR");if(t)return t;if("Windows"===me()["X-Stainless-OS"]){const t=Qe("APPDATA");if(t)return e.join(t,"Anthropic");const s=Qe("USERPROFILE");return s?e.join(s,"AppData","Roaming","Anthropic"):null}const s=Qe("XDG_CONFIG_HOME");if(s)return e.join(s,"anthropic");const n=Qe("HOME");return n?e.join(n,".config","anthropic"):null},vt=()=>{const e=me()["X-Stainless-Runtime"];return"node"===e||"deno"===e},kt=async()=>{const e=await bt();if(!e)return null;const t=Qe("ANTHROPIC_PROFILE");if(t)return t;const{fs:s,path:n}=await(import("./node.browser-BDF4XvCU.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 St(e){if(!e)throw new U("Identity token file path is empty");return async()=>{const{fs:t}=await(import("./node.browser-BDF4XvCU.js"));let s;try{s=await t.promises.readFile(e,"utf-8")}catch(r){throw new U(`Failed to read identity token file at ${e}: ${r}`)}const n=s.trim();if(!n)throw new U(`Identity token file at ${e} is empty`);return n}}function xt(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 Je(`identity_token.source "${t}" is not supported by this SDK version (only "file")`);if(!e.identity_token.path)throw new Je('identity_token.source "file" requires a non-empty path');return St(e.identity_token.path)}const t=Qe("ANTHROPIC_IDENTITY_TOKEN_FILE");if(t)return St(t);const s=Qe("ANTHROPIC_IDENTITY_TOKEN");return s?function(e){if(!e)throw new U("Identity token value is empty");return()=>e}(s):null}(r);if(!i)throw new Je("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 Je("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 Je("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");const o=function(e){return async()=>{Ue(e.baseURL);const t=await e.identityTokenProvider();if(t.length>16384)throw new Je(`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}${qe}`;let r;try{r=await e.fetch(n,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${We},oidc-federation-2026-04-01`,"User-Agent":e.userAgent||"anthropic-sdk-typescript/0.129.0 oidcFederationProvider"},body:JSON.stringify(s)})}catch(c){throw new Je(`Failed to reach token endpoint ${n}: ${c}`)}const i=r.headers.get("Request-Id");if(!r.ok){const t=Fe(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 Je(`Token exchange failed with status ${r.status}${i?` (request-id ${i})`:""}: ${t}${s}`,r.status,t,i)}const o=await De(r,i),a=Number(o.expires_in);if(!Number.isFinite(a))throw new Je(`Token endpoint response missing required fields: ${JSON.stringify(Fe(o))}`,r.status,Fe(o),i);return{token:o.access_token,expiresAt:Ve()+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-BDF4XvCU.js"));let o;await Be(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||Ve()<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 Ke(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 Je("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-BDF4XvCU.js"));let n,r;await Be(e.credentialsPath,e.onSafetyWarning);try{n=await s.promises.readFile(e.credentialsPath,"utf-8")}catch(m){throw new Je(`Credentials file not found at ${e.credentialsPath}: ${m}`)}try{r=JSON.parse(n)}catch(m){throw new Je(`Credentials file at ${e.credentialsPath} is not valid JSON: ${m}`)}const i=r.access_token;if(!i)throw new Je(`Credentials file at ${e.credentialsPath} must include 'access_token'`);const o=r.expires_at;if(!t?.forceRefresh&&(null==o||Ve()<o-30))return{token:i,expiresAt:o??null};const a=r.refresh_token;if(!e.clientId||!a)throw new Je(`Access token at ${e.credentialsPath} has expired and no refresh is available (client_id ${e.clientId?"set":"empty"}, refresh_token ${a?"set":"empty"})`);Ue(e.baseURL);const c={grant_type:"refresh_token",refresh_token:a,client_id:e.clientId},l=`${e.baseURL}${qe}`;let h;try{h=await e.fetch(l,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":We,"User-Agent":e.userAgent||"anthropic-sdk-typescript/0.129.0 userOAuthProvider"},body:JSON.stringify(c)})}catch(m){throw new Je(`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 Je(`User OAuth refresh failed (HTTP ${h.status}): ${Fe(e)}`,h.status,Fe(e),d)}const u=await De(h,d),p=Number(u.expires_in);if(!Number.isFinite(p))throw new Je(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(Fe(u))}`,h.status,Fe(u),d);const f=Ve()+p,g=u.refresh_token||a;return await Ke(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 Je(`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 It,Rt=/* @__PURE__ */(()=>{class e{constructor(){_t.set(this,void 0),wt.set(this,void 0),te(this,_t,/* @__PURE__ */new Uint8Array,"f"),te(this,wt,null,"f")}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?Ze(e):e;te(this,_t,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}([se(this,_t,"f"),t]),"f");const s=[];let n;for(;null!=(n=At(se(this,_t,"f"),se(this,wt,"f")));){if(n.carriage&&null==se(this,wt,"f")){te(this,wt,n.index,"f");continue}if(null!=se(this,wt,"f")&&(n.index!==se(this,wt,"f")+1||n.carriage)){s.push(et(se(this,_t,"f").subarray(0,se(this,wt,"f")-1))),te(this,_t,se(this,_t,"f").subarray(se(this,wt,"f")),"f"),te(this,wt,null,"f");continue}const e=null!==se(this,wt,"f")?n.preceding-1:n.preceding,t=et(se(this,_t,"f").subarray(0,e));s.push(t),te(this,_t,se(this,_t,"f").subarray(n.index),"f"),te(this,wt,null,"f")}return s}flush(){return se(this,_t,"f").length?this.decode("\n"):[]}}return _t=/* @__PURE__ */new WeakMap,wt=/* @__PURE__ */new WeakMap,e.NEWLINE_CHARS=/* @__PURE__ */new Set(["\n","\r"]),e.NEWLINE_REGEXP=/\r\n|[\n\r]/g,e})();function At(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 $t=/* @__PURE__ */(()=>{class e{constructor(e,t,s){this.iterator=e,It.set(this,void 0),this.controller=t,te(this,It,s,"f")}static rawEvents(e,t=new AbortController){return Tt(e,t)}static fromSSEResponse(t,s,n){let r=!1;const i=n?ht(n):console;return new e(async function*(){if(r)throw new U("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let e=!1;try{for await(const e of Tt(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=de(e.data)??e.data,n=s?.error?.type;throw new D(void 0,s,void 0,t.headers,n)}}e=!0}catch(n){if(W(n))return;throw n}finally{e||s.abort(),ye(s)}},s,n)}static fromReadableStream(t,s,n){let r=!1;return new e(async function*(){if(r)throw new U("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 Rt,s=ke(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(W(n))return;throw n}finally{e||s.abort(),ye(s)}},s,n)}[(It=/* @__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,se(this,It,"f")),new e(()=>r(s),this.controller,se(this,It,"f"))]}toReadableStream(){const e=this;let t;return be({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=Ze(JSON.stringify(s)+"\n");e.enqueue(r)}catch(s){e.error(s)}},async cancel(){await(t.return?.())}})}}return e})();async function*Tt(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new U("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 U("Attempted to iterate over a response with no body")}const s=new Et,n=new Rt,r=ke(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 Et=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 Mt(e,t){const{response:s,requestLogID:n,retryOfRequestLogID:r,startTime:i}=t,o=await(async()=>{if(t.options.stream)return ht(e).debug("response",s.status,s.url,s.headers,s.body),$t.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 Ot(await s.json(),s)}return await s.text()})().finally(()=>{t.options.stream||t.options.__binaryResponse||ye(t.controller)});return ut(ht(e),`[${n}] response parsed`,{retryOfRequestLogID:r,url:s.url,status:s.status,body:o,durationMs:Date.now()-i}),o}function Ot(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 Pt,Ct=/* @__PURE__ */new WeakSet;function Lt(e){return"object"==typeof e&&null!==e&&Ct.has(e)}function Nt(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=j(n);throw Ct.add(e),e}};const i=function(e,t){const s=/* @__PURE__ */new WeakMap;return{options:e,logger:t?ht(t):dt(),parse(n){if(e?.stream&&n.ok)return qt(n,e,t);let r=s.get(n);return r||(r=qt(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 U("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 qt(e,t,s){if(e.bodyUsed||e.body?.locked)throw new U("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 $t.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 Ot(await e.clone().json(),e)}return await e.clone().text()}var Wt,jt=/* @__PURE__ */(()=>{class e extends Promise{constructor(e,t,s=Mt){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=s,Pt.set(this,void 0),te(this,Pt,e,"f")}_thenUnwrap(t){return new e(se(this,Pt,"f"),this.responsePromise,async(e,s)=>Ot(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(se(this,Pt,"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 Pt=/* @__PURE__ */new WeakMap,e})(),Ut=/* @__PURE__ */(()=>{class e{constructor(e,t,s,n){Wt.set(this,void 0),te(this,Wt,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 U("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await se(this,Wt,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Wt=/* @__PURE__ */new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}return e})(),Dt=/* @__PURE__ */(()=>{class e extends jt{constructor(e,t,s){super(e,t,async(e,t)=>new s(e,t.response,await Mt(e,t),t.options))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}return e})(),Ht=class extends Ut{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:{...oe(this.options.query),before_id:e}}:null}const e=this.last_id;return e?{...this.options,query:{...oe(this.options.query),after_id:e}}:null}},zt=class extends Ut{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:{...oe(this.options.query),page:e}}:null}},Ft=class extends Ut{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:{...oe(this.options.query),page:e}}:null}},Bt=()=>{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 Kt(e,t,s){return Bt(),new File(e,t??"",s)}function Jt(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 Vt=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],Xt=async(e,t,s=!0)=>({...e,body:await Yt(e.body,t,s)}),Gt=/* @__PURE__ */new WeakMap,Yt=async(e,t,s=!0)=>{if(!(await function(e){const t="function"==typeof e?e:e.fetch,s=Gt.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 Gt.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])=>Qt(n,e,t,s))),n},Qt=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,Kt([await s.blob()],Jt(s,n),r))}else if(Vt(s))e.append(t,Kt([await new Response(ve(s)).blob()],Jt(s,n)));else if(s instanceof Blob){const r="undefined"!=typeof File&&s instanceof File?s.name:Jt(s,n);e.append(t,Kt([s],r,{type:s.type}))}else if(Array.isArray(s))await Promise.all(s.map(s=>Qt(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])=>Qt(e,`${t}[${s}]`,r,n)))}}},Zt=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 es(e,t,s){if(Bt(),e=await e,t||(t=e instanceof File?e.name:Jt(e,!0)),(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&Zt(e))(e))return e instanceof File&&null==t&&null==s?e:Kt([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()),Kt(await ts(n),t,s)}const n=await ts(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 Kt(n,t,s)}async function ts(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Zt(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else{if(!Vt(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 ts(s))}return t}var ss=class{constructor(e){this._client=e}},ns=Symbol.for("brand.privateNullableHeaders");function*rs(e){if(!e)return;if(ns 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():ie(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=ie(n[1])?n[1]:[n[1]];let r=!1;for(const n of t)void 0!==n&&(s&&!r&&(r=!0,yield[e,is]),yield[e,n])}}var is=Symbol("clear"),os=/* @__PURE__ */new Set(["x-stainless-helper"]),as=(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(", ")},cs=e=>{const t=new Headers,s=/* @__PURE__ */new Set;for(const n of e){const e=/* @__PURE__ */new Set;for(const[r,i]of rs(n)){const n=r.toLowerCase();if(os.has(n)){if(i===is)continue;null===i?(t.delete(r),s.add(n)):(t.set(r,as(t.get(r),i)),s.delete(n))}else(i!==is&&e.has(n)||(t.delete(r),e.add(n),i!==is))&&(null===i?(t.delete(r),s.add(n)):(t.append(r,i),s.delete(n)))}}return{[ns]:!0,values:t,nulls:s}};function ls(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var hs=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.create(null)),ds=(e=ls)=>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??hs)??hs)?.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 U(`Path parameters result in path with invalid segments:\n${r.map(e=>e.error).join("\n")}\n${i}\n${t}`)}return i},us=/* @__PURE__ */ds(ls),ps=class extends ss{retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(us`/v1/deployment_runs/${e}?beta=true`,{...s,headers:cs([{"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",zt,{query:r,...t,headers:cs([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}},fs=class extends ss{create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/deployments?beta=true",{body:r,...t,headers:cs([{"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(us`/v1/deployments/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/deployments/${e}?beta=true`,{body:i,...s,headers:cs([{"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",zt,{query:r,...t,headers:cs([{"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(us`/v1/deployments/${e}/archive?beta=true`,{...s,headers:cs([{"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(us`/v1/deployments/${e}/pause?beta=true`,{...s,headers:cs([{"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(us`/v1/deployments/${e}/run?beta=true`,{...s,headers:cs([{"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(us`/v1/deployments/${e}/unpause?beta=true`,{...s,headers:cs([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},gs=class extends ss{create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/dreams?beta=true",{body:r,...t,headers:cs([{"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(us`/v1/dreams/${e}?beta=true`,{...s,headers:cs([{"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",zt,{query:r,...t,headers:cs([{"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(us`/v1/dreams/${e}/archive?beta=true`,{...s,headers:cs([{"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(us`/v1/dreams/${e}/cancel?beta=true`,{...s,headers:cs([{"anthropic-beta":[...n??[],"dreaming-2026-04-21"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},ms="x-stainless-helper",_s="x-stainless-helper-method";function ws(e){return{[ms]:e}}var ys=Symbol("anthropic.sdk.stainlessHelper");function bs(e){return"object"==typeof e&&null!==e&&ys in e}function vs(e,t){const s=/* @__PURE__ */new Set;if(e)for(const n of e)bs(n)&&s.add(n[ys]);if(t)for(const n of t){bs(n)&&s.add(n[ys]);const e=n.content;if(Array.isArray(e))for(const t of e){bs(t)&&s.add(t[ys]);const e=t?.tool?.definition;bs(e)&&s.add(e[ys])}}return Array.from(s)}function ks(e,t){const s=vs(e,t);return 0===s.length?{}:{[ms]:s.join(", ")}}function Ss(e){return bs(e)?{[ms]:e[ys]}:{}}var xs,Is,Rs,As,$s,Ts,Es,Ms,Os,Ps,Cs,Ls,Ns,qs=class extends ss{list(e={},t){const{betas:s,workspace_id:n,...r}=e??{};return this._client.getAPIList("/v1/files?beta=true",zt,{query:r,...t,headers:cs([{...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(us`/v1/files/${e}?beta=true`,{...s,headers:cs([{...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(us`/v1/files/${e}/content?beta=true`,{...s,headers:cs([{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(us`/v1/files/${e}?beta=true`,{...s,headers:cs([{...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",Xt({body:r,...t,headers:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},Ss(r.file),t?.headers])},this._client))}},Ws=class extends ss{retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(us`/v1/models/${e}?beta=true`,{...s,headers:cs([{...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",Ht,{query:r,...t,headers:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}},js=class extends ss{create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/user_profiles?beta=true",{body:r,...t,headers:cs([{"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(us`/v1/user_profiles/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/user_profiles/${e}?beta=true`,{body:i,...s,headers:cs([{"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",zt,{query:r,...t,headers:cs([{"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(us`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...s,headers:cs([{"anthropic-beta":[...n??[],"user-profiles-2026-08-18"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},Us=/* @__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)}}),Ds=/* @__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)}),Hs=/* @__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}}),zs=/* @__PURE__ */t(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Webhook=e.WebhookVerificationError=void 0;var t=Us(),s=Ds(),n=Hs(),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_"}),Fs=zs(),Bs=class extends ss{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 Fs.Webhook(n).verify(e,s),JSON.parse(e)}},Ks=class extends ss{list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(us`/v1/agents/${e}/versions?beta=true`,zt,{query:i,...s,headers:cs([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},Js=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.versions=new Ks(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:cs([{"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(us`/v1/agents/${e}?beta=true`,{query:i,...s,headers:cs([{"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(us`/v1/agents/${e}?beta=true`,{body:i,...s,headers:cs([{"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",zt,{query:r,...t,headers:cs([{"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(us`/v1/agents/${e}/archive?beta=true`,{...s,headers:cs([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Versions=Ks,e})();function Vs(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 Xs(e,t){return e instanceof D&&e.status===t}function Gs(e){return function(e){return e instanceof D&&"number"==typeof e.status&&e.status>=400&&e.status<500}(e)&&!Xs(e,408)&&!Xs(e,409)&&!Xs(e,429)}function Ys(e,t,s){return Math.min(t*2**e,s)}function Qs(e,t){return e+Math.random()*(t-e)}function Zs(e){return e*(1-.25*Math.random())}function en(e,{authToken:t,helper:s}){if(!t)throw new U(`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=cs([o,r,{[ms]:s}]);return e.withOptions({apiKey:null,authToken:t,baseURL:e.baseURL,credentials:void 0,defaultHeaders:a})}var tn=/* @__PURE__ */(()=>{class e{constructor(e){xs.set(this,void 0),Is.set(this,!1),Rs.set(this,void 0),As.set(this,void 0),$s.set(this,void 0),Ts.set(this,void 0),Es.set(this,void 0),Ms.set(this,void 0),Os.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}-${ft()}`:ft()}(),te(this,xs,en(e.client,{authToken:e.environmentKey,helper:"environments-work-poller"}),"f"),te(this,$s,e.autoStop??!0,"f"),te(this,Ts,e.drain??!1,"f"),te(this,Es,void 0===e.blockMs?999:e.blockMs,"f"),te(this,Ms,e.reclaimOlderThanMs??null,"f"),te(this,Os,e.requestOptions,"f"),te(this,Rs,new AbortController,"f"),te(this,As,Vs(e.signal,se(this,Rs,"f")),"f")}get signal(){return se(this,Rs,"f").signal}abort(){se(this,Rs,"f").abort()}async*[(xs=/* @__PURE__ */new WeakMap,Is=/* @__PURE__ */new WeakMap,Rs=/* @__PURE__ */new WeakMap,As=/* @__PURE__ */new WeakMap,$s=/* @__PURE__ */new WeakMap,Ts=/* @__PURE__ */new WeakMap,Es=/* @__PURE__ */new WeakMap,Ms=/* @__PURE__ */new WeakMap,Os=/* @__PURE__ */new WeakMap,Symbol.asyncIterator)](){if(se(this,Is,"f"))throw new U("Cannot iterate over a consumed WorkPoller");te(this,Is,!0,"f");const e=ht(this.client);e.info("poller starting",{component:"work-poller",environment_id:this.environmentId});const t=new Un(e,this.environmentId);try{let n=0;for(;!se(this,Rs,"f").signal.aborted;){let r;try{r=await se(this,xs,"f").beta.environments.work.poll(this.environmentId,{"Anthropic-Worker-ID":this.workerId,...null!==se(this,Es,"f")?{block_ms:se(this,Es,"f")}:{},...null!==se(this,Ms,"f")?{reclaim_older_than_ms:se(this,Ms,"f")}:{}},{headers:cs([se(this,Os,"f")?.headers]),signal:se(this,Rs,"f").signal})}catch(s){if(se(this,Rs,"f").signal.aborted)return;if(Gs(s))throw e.error("poll failed permanently, stopping poller",{error:String(s)}),s;const t=Zs(sn(n));e.warn("poll failed, backing off",{error:String(s),backoff_ms:t}),n++,await ue(t,se(this,Rs,"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 se(this,xs,"f").beta.environments.work.ack(r.id,{environment_id:r.environment_id},{headers:cs([se(this,Os,"f")?.headers]),signal:se(this,Rs,"f").signal})}catch(s){e.error("ack failed",{work_id:r.id,error:String(s)});continue}try{yield r}finally{if(se(this,$s,"f"))try{await se(this,xs,"f").beta.environments.work.stop(r.id,{environment_id:r.environment_id},{headers:cs([se(this,Os,"f")?.headers])})}catch(s){Xs(s,409)||e.warn("stop failed",{work_id:r.id,error:String(s)})}}}else{if(se(this,Ts,"f"))return;t.onEmptyPoll(),await ue(Qs(1e3,3e3),se(this,Rs,"f").signal)}}}finally{se(this,As,"f").call(this)}}}return e})();function sn(e){return Ys(e,1e3,6e4)}var nn,rn,on,an,cn,ln,hn,dn,un,pn,fn,gn,mn,_n,wn,yn,bn,vn,kn,Sn,xn,In,Rn,An,$n,Tn,En,Mn,On,Pn,Cn,Ln,Nn,qn,Wn,jn,Un=/* @__PURE__ */(()=>(Ps=/* @__PURE__ */new WeakMap,Cs=/* @__PURE__ */new WeakMap,Ls=/* @__PURE__ */new WeakMap,Ns=/* @__PURE__ */new WeakMap,class{constructor(e,t){Ps.set(this,void 0),Cs.set(this,void 0),Ls.set(this,void 0),Ns.set(this,0),te(this,Ps,e,"f"),te(this,Cs,t,"f")}onEmptyPoll(){const e=Date.now(),t={component:"work-poller",environment_id:se(this,Cs,"f")};void 0===se(this,Ls,"f")?(te(this,Ls,te(this,Ns,e,"f"),"f"),se(this,Ps,"f").info("idle; polling for work",t)):e-se(this,Ns,"f")>=3e5?(te(this,Ns,e,"f"),se(this,Ps,"f").info(`still polling; idle for ${Math.round((e-se(this,Ls,"f"))/1e3)}s`,t)):se(this,Ps,"f").debug("poll returned no work",t)}onClaim(){te(this,Ls,void 0,"f")}}))(),Dn=/* @__PURE__ */(()=>(nn=/* @__PURE__ */new WeakMap,rn=/* @__PURE__ */new WeakMap,on=/* @__PURE__ */new WeakMap,class{constructor(){nn.set(this,[]),rn.set(this,[]),on.set(this,!1)}push(e){if(se(this,on,"f"))return!1;const t=se(this,rn,"f").shift();return t?t({done:!1,value:e}):se(this,nn,"f").push(e),!0}close(){if(!se(this,on,"f"))for(te(this,on,!0,"f");se(this,rn,"f").length>0;)se(this,rn,"f").shift()({done:!0,value:void 0})}next(e){return se(this,nn,"f").length>0?Promise.resolve({done:!1,value:se(this,nn,"f").shift()}):se(this,on,"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=se(this,rn,"f").indexOf(s);e>=0&&se(this,rn,"f").splice(e,1),t({done:!0,value:void 0})};se(this,rn,"f").push(s),e?.addEventListener("abort",n,{once:!0})})}tryShift(){return se(this,nn,"f").shift()}}))(),Hn=/* @__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 zn(e){return"name"in e?e.name:"mcp_server_name"in e?e.mcp_server_name:e.type}function Fn(e){return e instanceof Hn?e.content:`Error: ${e instanceof Error?e.message:String(e)}`}function Bn(e){return"session.status_idle"===e.type&&"end_turn"===e.stop_reason?.type}var Kn,Jn,Vn,Xn,Gn,Yn=/* @__PURE__ */(()=>(an=/* @__PURE__ */new WeakMap,cn=/* @__PURE__ */new WeakMap,ln=/* @__PURE__ */new WeakMap,hn=/* @__PURE__ */new WeakMap,dn=/* @__PURE__ */new WeakMap,class{constructor(e,t){an.set(this,void 0),cn.set(this,void 0),ln.set(this,/* @__PURE__ */new Set),hn.set(this,!1),dn.set(this,void 0),te(this,an,e,"f"),te(this,cn,t,"f")}noteEvent(e){"user.tool_confirmation"!==e.type&&(Bn(e)?this.arm():this.disarm())}block(e){se(this,ln,"f").add(e),void 0!==se(this,dn,"f")&&(te(this,hn,!0,"f"),clearTimeout(se(this,dn,"f")),te(this,dn,void 0,"f"))}unblock(e){se(this,ln,"f").delete(e),0===se(this,ln,"f").size&&se(this,hn,"f")&&this.arm()}arm(){se(this,an,"f")<=0||(se(this,ln,"f").size>0?te(this,hn,!0,"f"):(te(this,hn,!1,"f"),void 0!==se(this,dn,"f")&&clearTimeout(se(this,dn,"f")),te(this,dn,setTimeout(se(this,cn,"f"),se(this,an,"f")),"f")))}disarm(){te(this,hn,!1,"f"),void 0!==se(this,dn,"f")&&(clearTimeout(se(this,dn,"f")),te(this,dn,void 0,"f"))}}))(),Qn=/* @__PURE__ */(()=>{class e{constructor(e,t){un.add(this),pn.set(this,!1),fn.set(this,void 0),gn.set(this,void 0),mn.set(this,void 0),_n.set(this,void 0),wn.set(this,void 0),yn.set(this,/* @__PURE__ */new Set),bn.set(this,/* @__PURE__ */new Set),vn.set(this,/* @__PURE__ */new Map),kn.set(this,/* @__PURE__ */new Map),Sn.set(this,new Dn),xn.set(this,0),In.set(this,3e5),Rn.set(this,null),An.set(this,void 0),this.client=t.client,this.sessionId=e,this.tools=t.tools,this.maxIdleMs=t.maxIdleMs??6e4,te(this,wn,ht(t.client),"f"),te(this,_n,new Map(t.tools.map(e=>[zn(e),e])),"f"),te(this,fn,new AbortController,"f"),te(this,gn,Vs(t.signal,se(this,fn,"f")),"f"),te(this,mn,t.requestOptions,"f"),te(this,An,new Yn(this.maxIdleMs,()=>{se(this,wn,"f").info("session idle after end_turn; stopping",{component:"session-tool-runner",session_id:this.sessionId,max_idle_ms:this.maxIdleMs}),se(this,fn,"f").abort()}),"f")}get signal(){return se(this,fn,"f").signal}abort(){se(this,fn,"f").abort()}_setSendRetryWindow(e){te(this,In,e,"f")}async*[(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,kn=/* @__PURE__ */new WeakMap,Sn=/* @__PURE__ */new WeakMap,xn=/* @__PURE__ */new WeakMap,In=/* @__PURE__ */new WeakMap,Rn=/* @__PURE__ */new WeakMap,An=/* @__PURE__ */new WeakMap,un=/* @__PURE__ */new WeakSet,Symbol.asyncIterator)](){if(se(this,pn,"f"))throw new U("Cannot iterate over a consumed SessionToolRunner");te(this,pn,!0,"f"),se(this,wn,"f").info("session tool runner starting",{component:"session-tool-runner",session_id:this.sessionId});const e=se(this,un,"m",Tn).call(this).catch(e=>{se(this,fn,"f").signal.aborted||se(this,wn,"f").error("stream loop failed",{error:String(e)}),se(this,fn,"f").abort()});try{for(;;){const e=await se(this,Sn,"f").next(se(this,fn,"f").signal);if(e.done)break;yield e.value}let t;for(await e;void 0!==(t=se(this,Sn,"f").tryShift());)yield t}finally{se(this,fn,"f").abort(),se(this,An,"f").disarm(),await e;try{await se(this,un,"m",jn).call(this)}catch(t){se(this,wn,"f").warn("drain failed",{error:String(t)})}se(this,Sn,"f").close();for(const e of this.tools)try{await(e.close?.())}catch(t){se(this,wn,"f").warn("tool.close failed",{tool:zn(e),error:String(t)})}se(this,gn,"f").call(this)}}}return $n=function(){return{...se(this,mn,"f"),headers:cs([ws("session-tool-runner"),se(this,mn,"f")?.headers]),signal:se(this,fn,"f").signal}},Tn=async function(){const e=se(this,fn,"f");let t=500;for(;!e.signal.aborted;){try{const e=await this.client.beta.sessions.events.stream(this.sessionId,{},se(this,un,"m",$n).call(this));await se(this,un,"m",En).call(this);for await(const s of e)if(t=500,await se(this,un,"m",On).call(this,s))return}catch(s){if(e.signal.throwIfAborted(),Gs(s))throw se(this,wn,"f").error("permanent stream failure, shutting down",{error:String(s)}),e.abort(),s;se(this,wn,"f").warn("stream disconnected, reconnecting",{error:String(s),backoff_ms:t})}e.signal.throwIfAborted(),await ue(t,e.signal),t=Math.min(2*t,1e4)}},En=async function(){const e=se(this,fn,"f"),t=[];let s=!1;try{for await(const e of this.client.beta.sessions.events.list(this.sessionId,{limit:1e3},se(this,un,"m",$n).call(this)))se(this,un,"m",Mn).call(this,e,t),s=Bn(e)}catch(i){e.signal.throwIfAborted(),se(this,wn,"f").warn("reconcile list failed",{error:String(i)});for(const e of t)se(this,yn,"f").delete(e.id);return}const n=t.filter(e=>!se(this,bn,"f").has(e.id));se(this,An,"f").disarm();for(const o of n)await se(this,un,"m",Pn).call(this,o);for(const o of[...se(this,kn,"f").values()]){const e=se(this,vn,"f").get(o.id);void 0!==e&&await se(this,un,"m",Ln).call(this,o,e)}const r=n.filter(e=>!se(this,bn,"f").has(e.id)&&!se(this,kn,"f").has(e.id));s&&0===r.length?se(this,An,"f").arm():se(this,An,"f").disarm()},Mn=function(e,t){"agent.tool_use"===e.type||"agent.custom_tool_use"===e.type?(se(this,yn,"f").add(e.id),se(this,bn,"f").has(e.id)||t.push(e)):"user.tool_result"===e.type?se(this,bn,"f").add(e.tool_use_id):"user.custom_tool_result"===e.type?se(this,bn,"f").add(e.custom_tool_use_id):"user.tool_confirmation"===e.type&&(se(this,bn,"f").has(e.tool_use_id)||se(this,vn,"f").set(e.tool_use_id,e.result))},On=async function(e){switch(se(this,An,"f").noteEvent(e),e.type){case"agent.tool_use":case"agent.custom_tool_use":return se(this,yn,"f").has(e.id)||(se(this,yn,"f").add(e.id),await se(this,un,"m",Pn).call(this,e)),!1;case"user.tool_confirmation":return await se(this,un,"m",Cn).call(this,e),!1;case"user.tool_result":return se(this,bn,"f").add(e.tool_use_id),!1;case"user.custom_tool_result":return se(this,bn,"f").add(e.custom_tool_use_id),!1;case"session.status_terminated":case"session.deleted":return se(this,wn,"f").info("session terminated",{component:"session-tool-runner",session_id:this.sessionId}),se(this,fn,"f").abort(),!0;default:return!1}},Pn=async function(e){const t=e.evaluated_permission,s="deny"===t?"deny":se(this,vn,"f").get(e.id);void 0!==s?await se(this,un,"m",Ln).call(this,e,s):void 0===t||"allow"===t?await se(this,un,"m",qn).call(this,e,void 0):se(this,kn,"f").has(e.id)||(se(this,wn,"f").info("tool call awaiting confirmation; holding",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),se(this,kn,"f").set(e.id,e),se(this,An,"f").block(e.id))},Cn=async function(e){se(this,vn,"f").set(e.tool_use_id,e.result);const t=se(this,kn,"f").get(e.tool_use_id);void 0!==t&&await se(this,un,"m",Ln).call(this,t,e.result)},Ln=async function(e,t){const s=se(this,kn,"f").delete(e.id);if("allow"!==t)s&&se(this,An,"f").unblock(e.id),se(this,bn,"f").add(e.id),se(this,wn,"f").info("tool call denied; not executing",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),se(this,un,"m",Nn).call(this,{event:e,toolUseId:e.id,name:e.name,isError:!1,posted:!1,confirmation:"deny"});else{se(this,wn,"f").info("tool call confirmed",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),s||se(this,An,"f").block(e.id);try{await se(this,un,"m",qn).call(this,e,"allow")}finally{se(this,An,"f").unblock(e.id)}}},Nn=function(e){se(this,Sn,"f").push(e)},qn=async function(e,t){var s,n;if(!se(this,bn,"f").has(e.id)){se(this,wn,"f").info("executing tool",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),te(this,xn,(s=se(this,xn,"f"),++s),"f");try{const s=se(this,_n,"f").get(e.name);if(!s)return se(this,wn,"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 se(this,un,"m",Nn).call(this,{event:e,toolUseId:e.id,name:e.name,isError:!1,posted:!1,confirmation:t});let n,r;const i=new AbortController,o=Vs(se(this,fn,"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:Fn(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 se(this,un,"m",Wn).call(this,c,e.id);se(this,un,"m",Nn).call(this,{event:e,result:c,toolUseId:e.id,name:e.name,isError:r,posted:l,confirmation:t})}finally{te(this,xn,(n=se(this,xn,"f"),--n),"f"),0===se(this,xn,"f")&&se(this,Rn,"f")?.call(this)}}},Wn=async function(e,t){const s=se(this,fn,"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]},se(this,un,"m",$n).call(this)),se(this,bn,"f").add(t),!0}catch(o){if(r=o,Gs(o))break;const e=se(this,In,"f")-(Date.now()-n);if(e<=0)break;const a=Math.min(Zs(Ys(i-1,1e3,3e4)),e);se(this,wn,"f").warn("tool result send failed; retrying",{tool_use_id:t,attempt:i,backoff_ms:a,error:String(o)}),await ue(a,s.signal)}}return se(this,wn,"f").error("failed to send tool result",{tool_use_id:t,attempts:i,error:String(r)}),!1},jn=async function(){0!==se(this,xn,"f")&&(await Promise.race([new Promise(e=>te(this,Rn,e,"f")),ue(3e4)]),te(this,Rn,null,"f"),se(this,xn,"f")>0&&se(this,wn,"f").warn("drain timeout exceeded"))},e})();var Zn=/* @__PURE__ */(()=>(Jn=/* @__PURE__ */new WeakMap,Kn=/* @__PURE__ */new WeakSet,Vn=async function(e,t,s){const n=ht(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(et((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 U("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 U("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=en(this.client,{authToken:i,helper:"environments-worker"}),a=e.data.id,c=new AbortController,l=Vs(s,c),h=new tr(c),d=await(import("./node.browser-5xUv_7Bz.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=Vs(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:cs([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(),Xs(f,412)){const e=function(e){let t=e instanceof D?e.error:void 0;for(const s of["error","details","current_state"]){if(!ce(t))return{};t=t[s]}return ce(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(Gs(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 ue(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 Qn(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 er(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 er(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:cs([n?.headers])})}catch(w){Xs(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(Kn.add(this),Jn.set(this,void 0),void 0!==e.unrestrictedPaths)throw new U("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 U(`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,te(this,Jn,e.signal,"f")}async run(e){const{environmentId:t,environmentKey:s}=this;if(void 0===t||void 0===s)throw new U("EnvironmentWorker.run: environmentId and environmentKey are required to poll for work");const n=e??se(this,Jn,"f"),r=new tn({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 se(this,Kn,"m",Vn).call(this,o,s,r.signal)}catch(i){if(r.signal?.aborted)throw i;ht(this.client).error("work item failed",{work_id:o.id,error:String(i)})}}async handleItem(e){const t=e?.workId??Qe("ANTHROPIC_WORK_ID"),s=e?.environmentId??Qe("ANTHROPIC_ENVIRONMENT_ID"),n=e?.sessionId??Qe("ANTHROPIC_SESSION_ID"),r=(e?.environmentKey??this.environmentKey??Qe("ANTHROPIC_ENVIRONMENT_KEY"))||void 0,i=e?.workSecret||Qe("ANTHROPIC_WORK_SECRET")||null;if(!t)throw new U("handleItem: workId is required — pass it or set ANTHROPIC_WORK_ID");if(!s)throw new U("handleItem: environmentId is required — pass it or set ANTHROPIC_ENVIRONMENT_ID");if(!n)throw new U("handleItem: sessionId is required — pass it or set ANTHROPIC_SESSION_ID");if(!r&&!i)throw new U("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 se(this,Kn,"m",Vn).call(this,o,r,e?.signal??se(this,Jn,"f"))}}))();async function er(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 tr=/* @__PURE__ */(()=>(Xn=/* @__PURE__ */new WeakMap,Gn=/* @__PURE__ */new WeakMap,class{constructor(e){Xn.set(this,void 0),Gn.set(this,void 0),te(this,Xn,e,"f")}get signal(){return se(this,Xn,"f").signal}finish(e){te(this,Gn,se(this,Gn,"f")??e,"f"),se(this,Xn,"f").abort()}get lost(){return"lease_lost"===se(this,Gn,"f")||"assumed_lost"===se(this,Gn,"f")}}))(),sr=/* @__PURE__ */(()=>{class e extends ss{retrieve(e,t,s){const{environment_id:n,betas:r,workspace_id:i}=t;return this._client.get(us`/v1/environments/${n}/work/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/environments/${n}/work/${e}?beta=true`,{body:o,...s,headers:cs([{"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(us`/v1/environments/${e}/work?beta=true`,zt,{query:r,...s,headers:cs([{"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(us`/v1/environments/${n}/work/${e}/ack?beta=true`,{...s,headers:cs([{"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(us`/v1/environments/${n}/work/${e}/heartbeat?beta=true`,{query:{desired_ttl_seconds:r,expected_last_heartbeat:i},...s,headers:cs([{"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(us`/v1/environments/${e}/work/poll?beta=true`,{query:i,...s,headers:cs([{"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(us`/v1/environments/${e}/work/stats?beta=true`,{...s,headers:cs([{"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(us`/v1/environments/${n}/work/${e}/stop?beta=true`,{body:o,...s,headers:cs([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}poller(e){return new tn({...e,client:this._client})}worker(e){return new Zn({...e,client:this._client})}}return e.WorkPoller=tn,e.EnvironmentWorker=Zn,e})(),nr=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.work=new sr(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:cs([{"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(us`/v1/environments/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/environments/${e}?beta=true`,{body:i,...s,headers:cs([{"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",zt,{query:r,...t,headers:cs([{"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(us`/v1/environments/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/environments/${e}/archive?beta=true`,{...s,headers:cs([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Work=sr,e})(),rr=class extends ss{create(e,t,s){const{view:n,betas:r,workspace_id:i,...o}=t;return this._client.post(us`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:n},body:o,...s,headers:cs([{"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(us`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:o,...s,headers:cs([{"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(us`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:{view:r},body:a,...s,headers:cs([{"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(us`/v1/memory_stores/${e}/memories?beta=true`,zt,{query:i,...s,headers:cs([{"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(us`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:{expected_content_sha256:r},...s,headers:cs([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...null!=o?{"anthropic-workspace-id":o}:void 0},s?.headers])})}},ir=class extends ss{retrieve(e,t,s){const{memory_store_id:n,betas:r,workspace_id:i,...o}=t;return this._client.get(us`/v1/memory_stores/${n}/memory_versions/${e}?beta=true`,{query:o,...s,headers:cs([{"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(us`/v1/memory_stores/${e}/memory_versions?beta=true`,zt,{query:i,...s,headers:cs([{"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(us`/v1/memory_stores/${n}/memory_versions/${e}/redact?beta=true`,{...s,headers:cs([{"anthropic-beta":[...r??[],"agent-memory-2026-07-22"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}},or=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.memories=new rr(this._client),this.memoryVersions=new ir(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:cs([{"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(us`/v1/memory_stores/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/memory_stores/${e}?beta=true`,{body:i,...s,headers:cs([{"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",zt,{query:r,...t,headers:cs([{"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(us`/v1/memory_stores/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/memory_stores/${e}/archive?beta=true`,{...s,headers:cs([{"anthropic-beta":[...n??[],"agent-memory-2026-07-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Memories=rr,e.MemoryVersions=ir,e})(),ar=/* @__PURE__ */(()=>{class e{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new Rt;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 U("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 U("Attempted to iterate over a response with no body")}return new e(ke(t.body),s)}}return e})(),cr=class extends ss{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:cs([{"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(us`/v1/messages/batches/${e}?beta=true`,{...s,headers:cs([{"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",Ht,{query:r,...t,headers:cs([{"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(us`/v1/messages/batches/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/messages/batches/${e}/cancel?beta=true`,{...s,headers:cs([{"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 U(`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:cs([{"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)=>ar.fromResponse(t.response,t.controller))}},lr={"claude-opus-4@20250514":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function hr(e){return e?.output_format??e?.output_config?.format}function dr(e,t,s){const n=hr(t);return t&&"parse"in(n??{})?ur(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 ur(e,t,s){let n=null;const r=e.content.map(e=>{if("text"===e.type){const r=function(e,t){const s=hr(e);if("json_schema"!==s?.type)return null;try{return"parse"in s?s.parse(t):JSON.parse(t)}catch(n){throw new U(`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 pr,fr,gr,mr,_r,wr,yr,br,vr,kr,Sr,xr,Ir,Rr,Ar,$r,Tr,Er,Mr,Or,Pr,Cr,Lr,Nr,qr,Wr,jr="__json_buf";function Ur(e,t){const s={};for(const i of Object.keys(e))"input"!==i&&(s[i]=e[i]);let n;Object.defineProperty(s,jr,{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 Dr(e){return"tool_use"===e.type||"server_tool_use"===e.type||"mcp_tool_use"===e.type}var 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,bi,vi,ki,Si,xi,Ii=/* @__PURE__ */(()=>{class e{constructor(e,t){pr.add(this),this.messages=[],this.receivedMessages=[],fr.set(this,void 0),gr.set(this,null),this.controller=new AbortController,mr.set(this,void 0),_r.set(this,()=>{}),wr.set(this,()=>{}),yr.set(this,void 0),br.set(this,()=>{}),vr.set(this,()=>{}),kr.set(this,{}),Sr.set(this,!1),xr.set(this,!1),Ir.set(this,!1),Rr.set(this,!1),Ar.set(this,void 0),$r.set(this,void 0),Tr.set(this,void 0),Er.set(this,void 0),Pr.set(this,e=>{if(te(this,xr,!0,"f"),W(e)&&(e=new H),e instanceof H)return te(this,Ir,!0,"f"),this._emit("abort",e);if(e instanceof U)return this._emit("error",e);if(e instanceof Error){const t=new U(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new U(String(e)))}),te(this,mr,new Promise((e,t)=>{te(this,_r,e,"f"),te(this,wr,t,"f")}),"f"),te(this,yr,new Promise((e,t)=>{te(this,br,e,"f"),te(this,vr,t,"f")}),"f"),se(this,mr,"f").catch(()=>{}),se(this,yr,"f").catch(()=>{}),te(this,gr,e,"f"),te(this,Er,t?.logger??console,"f")}get response(){return se(this,Ar,"f")}get request_id(){return se(this,$r,"f")}get workspace_id(){return se(this,Tr,"f")}async withResponse(){te(this,Rr,!0,"f");const e=await se(this,mr,"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 te(i,gr,{...s,stream:!0},"f"),i._run(()=>i._createMessage(t,{...s,stream:!0},{...n,headers:{...n?.headers,[_s]:"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},se(this,Pr,"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{se(this,pr,"m",Cr).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)se(this,pr,"m",Lr).call(this,e);if(r.controller.signal?.aborted)throw new H;se(this,pr,"m",Nr).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}_connected(e){this.ended||(te(this,Ar,e,"f"),te(this,$r,e?.headers.get("request-id"),"f"),te(this,Tr,e?.headers.get("anthropic-workspace-id"),"f"),se(this,_r,"f").call(this,e),this._emit("connect"))}get ended(){return se(this,Sr,"f")}get errored(){return se(this,xr,"f")}get aborted(){return se(this,Ir,"f")}abort(){this.controller.abort()}on(e,t){return(se(this,kr,"f")[e]||(se(this,kr,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=se(this,kr,"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(se(this,kr,"f")[e]||(se(this,kr,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{te(this,Rr,!0,"f"),"error"!==e&&this.once("error",s),this.once(e,t)})}async done(){te(this,Rr,!0,"f"),await se(this,yr,"f")}get currentMessage(){return se(this,fr,"f")}async finalMessage(){return await this.done(),se(this,pr,"m",Mr).call(this)}async finalText(){return await this.done(),se(this,pr,"m",Or).call(this)}_emit(e,...t){if(se(this,Sr,"f"))return;"end"===e&&(te(this,Sr,!0,"f"),se(this,br,"f").call(this));const s=se(this,kr,"f")[e];if(s&&(se(this,kr,"f")[e]=s.filter(e=>!e.once),s.forEach(({listener:e})=>e(...t))),"abort"===e){const e=t[0];return se(this,Rr,"f")||s?.length||Promise.reject(e),se(this,wr,"f").call(this,e),se(this,vr,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];se(this,Rr,"f")||s?.length||Promise.reject(e),se(this,wr,"f").call(this,e),se(this,vr,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",se(this,pr,"m",Mr).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{se(this,pr,"m",Cr).call(this),this._connected(null);const t=$t.fromReadableStream(e,this.controller);for await(const e of t)se(this,pr,"m",Lr).call(this,e);if(t.controller.signal?.aborted)throw new H;se(this,pr,"m",Nr).call(this)}finally{s&&n&&s.removeEventListener("abort",n)}}[(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,Ir=/* @__PURE__ */new WeakMap,Rr=/* @__PURE__ */new WeakMap,Ar=/* @__PURE__ */new WeakMap,$r=/* @__PURE__ */new WeakMap,Tr=/* @__PURE__ */new WeakMap,Er=/* @__PURE__ */new WeakMap,Pr=/* @__PURE__ */new WeakMap,pr=/* @__PURE__ */new WeakSet,Mr=function(){if(0===this.receivedMessages.length)throw new U("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Or=function(){if(0===this.receivedMessages.length)throw new U("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 U("stream ended without producing a content block with type=text");return e.join(" ")},Cr=function(){this.ended||te(this,fr,void 0,"f")},Lr=function(e){if(this.ended)return;const t=se(this,pr,"m",qr).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(Dr(n)&&se(this,kr,"f").inputJson?.length){let t;try{t=n.input}catch(s){se(this,Pr,"f").call(this,se(this,pr,"m",Wr).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(dr(t,se(this,gr,"f"),{logger:se(this,Er,"f")}),!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":te(this,fr,t,"f")}},Nr=function(){if(this.ended)throw new U("stream has ended, this shouldn't happen");const e=se(this,fr,"f");if(!e)throw new U("request ended without sending any chunks");return te(this,fr,void 0,"f"),dr(e,se(this,gr,"f"),{logger:se(this,Er,"f")})},qr=function(e){let t=se(this,fr,"f");if("message_start"===e.type){if(t)throw new U(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new U(`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&&Dr(s)){const n=(s.__json_buf||"")+e.delta.partial_json;t.content[e.index]=Ur(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&&Dr(n)&&"__json_buf"in n){let e;try{e=n.input}catch(s){e={},se(this,Pr,"f").call(this,se(this,pr,"m",Wr).call(this,n,s))}Object.defineProperty(n,"input",{value:e,enumerable:!0,configurable:!0,writable:!0})}return t}}},Wr=function(e,t){const s=e[jr];return new U(`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 $t(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}return e})(),Ri=/* @__PURE__ */(()=>{class e extends Ii{constructor(e,t){super(e),Hr.add(this),zr.set(this,void 0),Fr.set(this,0),Br.set(this,[]),Kr.set(this,[]),Jr.set(this,void 0),Vr.set(this,[]),Xr.set(this,!1),te(this,zr,t,"f")}get toolCalls(){return se(this,Kr,"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,[_s]:"stream"}})),i}_emit(e,...t){var s;if("streamEvent"!==e||this.ended)return void super._emit(e,...t);te(this,Fr,(s=se(this,Fr,"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&&se(this,Kr,"f").push(o),super._emit(e,...t),se(this,Hr,"m",Gr).call(this,n,o),se(this,Hr,"m",Yr).call(this)}[(zr=/* @__PURE__ */new WeakMap,Fr=/* @__PURE__ */new WeakMap,Br=/* @__PURE__ */new WeakMap,Kr=/* @__PURE__ */new WeakMap,Jr=/* @__PURE__ */new WeakMap,Vr=/* @__PURE__ */new WeakMap,Xr=/* @__PURE__ */new WeakMap,Hr=/* @__PURE__ */new WeakSet,Symbol.asyncIterator)](){const e=super[Symbol.asyncIterator](),t={handled:se(this,Fr,"f")};se(this,Br,"f").push(t);let s=!1;return{next:async()=>{s&&(s=!1,t.handled++,se(this,Hr,"m",Yr).call(this));try{const n=await e.next();return s=!n.done,n.done&&se(this,Hr,"m",Qr).call(this,t),n}catch(n){throw se(this,Hr,"m",Qr).call(this,t),n}},return:async()=>{const s=e.return?.();return se(this,Hr,"m",Qr).call(this,t),await s??{value:void 0,done:!0}}}}}return Gr=function(e,t){if(se(this,Xr,"f"))return;if("content_block_start"===e.type&&"fallback"===e.content_block.type)return te(this,Xr,!0,"f"),void te(this,Jr,void 0,"f");const s="content_block_start"===e.type||"message_delta"===e.type&&"tool_use"===e.delta.stop_reason;se(this,Jr,"f")&&s&&(se(this,Vr,"f").push({toolUse:se(this,Jr,"f"),event:se(this,Fr,"f")}),te(this,Jr,void 0,"f")),t&&te(this,Jr,t,"f")},Yr=function(){if(this.errored||this.controller.signal.aborted)return;const e=Math.min(se(this,Fr,"f"),...se(this,Br,"f").map(e=>e.handled));for(;se(this,Vr,"f")[0]&&se(this,Vr,"f")[0].event<=e;)se(this,zr,"f").call(this,se(this,Vr,"f").shift().toolUse)},Qr=function(e){const t=se(this,Br,"f").indexOf(e);t>=0&&(se(this,Br,"f").splice(t,1),se(this,Hr,"m",Yr).call(this))},e})();function Ai(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}var $i=/* @__PURE__ */(()=>{class e{constructor(e,t,s){Zr.add(this),this.client=e,ei.set(this,!1),ti.set(this,!1),si.set(this,void 0),ni.set(this,void 0),ri.set(this,void 0),ii.set(this,void 0),oi.set(this,void 0),ai.set(this,void 0),ci.set(this,0),li.set(this,{status:"idle"}),hi.set(this,void 0),di.set(this,null),ui.set(this,/* @__PURE__ */new Map),pi.set(this,[]),Ti(t),function(e){if("compactionControl"in e&&null!=e.compactionControl)throw new U("`compactionControl` has been removed from the tool runner. Use server-side compaction instead: call `runner.compactBeforeNextTurn()` when the conversation should be compacted.")}(t),Ei(t),te(this,si,{params:{...t,messages:JSON.parse(JSON.stringify(t.messages))}},"f");const n=vs(t.tools,t.messages);te(this,ni,{...s,headers:cs([ws("BetaToolRunner"),n.length?{[ms]:n.join(", ")}:void 0,s?.headers])},"f"),te(this,ai,Ai(),"f")}async*[(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,ci=/* @__PURE__ */new WeakMap,li=/* @__PURE__ */new WeakMap,hi=/* @__PURE__ */new WeakMap,di=/* @__PURE__ */new WeakMap,ui=/* @__PURE__ */new WeakMap,pi=/* @__PURE__ */new WeakMap,Zr=/* @__PURE__ */new WeakSet,Symbol.asyncIterator)](){var e;if(se(this,ei,"f"))throw new U("Cannot iterate over a consumed stream");te(this,ei,!0,"f"),te(this,ti,!0,"f"),te(this,oi,void 0,"f");try{for(;;)try{if(se(this,si,"f").params.max_iterations&&se(this,ci,"f")>=se(this,si,"f").params.max_iterations)break;if(se(this,Zr,"m",Si).call(this),"scheduled"===se(this,li,"f").status&&"resume"!==Li(se(this,di,"f"))){yield*se(this,Zr,"m",_i).call(this,se(this,li,"f").config);continue}te(this,ti,!1,"f"),te(this,oi,void 0,"f"),te(this,ci,(e=se(this,ci,"f"),++e),"f"),te(this,ri,void 0,"f");const{max_iterations:t,runToolsEagerly:s,...n}=se(this,si,"f").params;if(yield*se(this,Zr,"m",fi).call(this,n),se(this,ti,"f"))te(this,di,null,"f");else{const e=await se(this,ri,"f"),t=Li(e.stop_reason);te(this,di,e.stop_reason,"f"),se(this,si,"f").params.messages.push({role:e.role,content:Pi(e.content)});const{container:s}=se(this,si,"f").params;if(e.container&&(null==s?se(this,si,"f").params.container=e.container.id:"object"==typeof s&&null==s.id&&(se(this,si,"f").params.container={...s,id:e.container.id})),"stop"===t){yield*se(this,Zr,"m",vi).call(this);break}if("resume"===t)continue}const r=await se(this,Zr,"m",ki).call(this,se(this,si,"f").params.messages.at(-1));if(r)se(this,si,"f").params.messages.push(r);else if(!se(this,ti,"f")){yield*se(this,Zr,"m",vi).call(this);break}}finally{se(this,ii,"f")?.abort(),te(this,ii,void 0,"f")}if(await se(this,Zr,"m",mi).call(this),!se(this,ri,"f"))throw new U("ToolRunner concluded without a message from the server");se(this,ai,"f").resolve(await se(this,ri,"f"))}catch(t){throw te(this,ei,!1,"f"),se(this,ai,"f").promise.catch(()=>{}),se(this,ai,"f").reject(t),te(this,ai,Ai(),"f"),t}}setMessagesParams(e){const t="function"==typeof e?e(se(this,si,"f").params):e;if(Ti(t),Ei(t),"idle"!==se(this,li,"f").status&&Mi(t),"in_flight"===se(this,li,"f").status&&t.messages!==se(this,si,"f").params.messages)throw new U("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.");se(this,si,"f").params=t,te(this,ti,!0,"f"),te(this,oi,void 0,"f")}setRequestOptions(e){te(this,ni,"function"==typeof e?e(se(this,ni,"f")):{...se(this,ni,"f"),...e},"f")}async generateToolResponse(e=se(this,ni,"f").signal){const t=await se(this,ri,"f")??this.params.messages.at(-1);return t?se(this,Zr,"m",ki).call(this,t,e):null}deferToolCall(e){const t="string"==typeof e?e:e.id;se(this,hi,"f")&&!se(this,hi,"f").has(t)&&se(this,hi,"f").set(t,{status:"held"})}get deferredToolCalls(){const e=se(this,ii,"f"),t=se(this,hi,"f");return e instanceof Ri&&t?e.toolCalls.filter(e=>"held"===t.get(e.id)?.status):[]}done(){return se(this,ai,"f").promise}async runUntilDone(){if(!se(this,ei,"f"))for await(const e of this);return this.done()}get params(){return se(this,si,"f").params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}compactBeforeNextTurn(e){"in_flight"!==se(this,li,"f").status&&(Mi(se(this,si,"f").params),te(this,li,{status:"scheduled",config:e??{type:"summarize"}},"f"))}addTools(...e){for(const t of e)"name"in t&&se(this,ui,"f").set(t.name,"run"in t?t:null),se(this,pi,"f").push({type:"addition",tool:t})}removeTools(...e){for(const t of e){const e="string"==typeof t?t:t.name;se(this,ui,"f").set(e,null),se(this,pi,"f").push({type:"removal",name:e})}}then(e,t){return this.runUntilDone().then(e,t)}}return fi=async function*(e){await se(this,Zr,"m",mi).call(this),te(this,hi,void 0,"f"),e.stream?(te(this,ii,se(this,si,"f").params.runToolsEagerly?se(this,Zr,"m",gi).call(this,e):this.client.beta.messages.stream({...e},se(this,ni,"f")),"f"),te(this,ri,se(this,ii,"f").finalMessage(),"f"),se(this,ri,"f").catch(()=>{}),yield se(this,ii,"f")):(te(this,ri,this.client.beta.messages.create({...e,stream:!1},se(this,ni,"f")),"f"),yield se(this,ri,"f"))},gi=function(e){const t=/* @__PURE__ */new Map;return te(this,hi,t,"f"),Ri.start(this.client.beta.messages,e,se(this,ni,"f"),e=>{if(t.has(e.id))return;const s=Oi(se(this,Zr,"m",wi).call(this),se(this,Zr,"m",yi).call(this),e,se(this,ni,"f"));s.catch(()=>{}),t.set(e.id,{status:"started",result:s})})},mi=async function(){const e=[...se(this,hi,"f")?.values()??[]].filter(e=>"started"===e.status);await Promise.allSettled(e.map(e=>e.result))},_i=async function*(e){Mi(se(this,si,"f").params);const{max_iterations:t,runToolsEagerly:s,...n}=se(this,si,"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);te(this,li,{status:"in_flight"},"f"),te(this,oi,void 0,"f");const i=se(this,ri,"f");try{yield*se(this,Zr,"m",fi).call(this,{...r,compaction:e});const t=await se(this,ri,"f");t.content.some(e=>"compaction"===e.type&&e.content)?(se(this,Zr,"m",bi).call(this),se(this,si,"f").params.messages=[{role:t.role,content:t.content}]):(ht(this.client).warn("Compaction produced no summary; keeping the conversation as it is."),te(this,ri,i,"f"))}finally{te(this,li,{status:"idle"},"f")}},wi=function(){const e=/* @__PURE__ */new Map;for(const t of se(this,si,"f").params.tools)"run"in t&&e.set(t.name,t);for(const[t,s]of se(this,ui,"f"))s?e.set(t,s):e.delete(t);return e},yi=function(){const e=new Set(se(this,Zr,"m",wi).call(this).keys());for(const t of[...se(this,si,"f").params.messages,se(this,Zr,"m",xi).call(this)])if("string"!=typeof t.content)for(const s of t.content)if("system"===t.role)Ci(s,e);else if("assistant"===t.role&&"compaction"===s.type)for(const t of s.tool_changes??[])Ci(t,e);return e},bi=function(){const e=se(this,Zr,"m",yi).call(this);for(const t of se(this,Zr,"m",wi).call(this).keys())e.has(t)||se(this,ui,"f").set(t,null)},vi=async function*(){if("scheduled"!==se(this,li,"f").status)return;const e=se(this,si,"f").params.messages.at(-1)?.content;if(Array.isArray(e)&&e.some(e=>"tool_use"===e.type))return ht(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 te(this,li,{status:"idle"},"f");yield*se(this,Zr,"m",_i).call(this,se(this,li,"f").config)},ki=async function(e,t=se(this,ni,"f").signal){return void 0!==se(this,oi,"f")||te(this,oi,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=Oi(e,t,s,n);return r?.set(s.id,{status:"started",result:o}),o}))}}(se(this,Zr,"m",wi).call(this),se(this,Zr,"m",yi).call(this),e,{...se(this,ni,"f"),signal:t},se(this,hi,"f")),"f"),se(this,oi,"f")},Si=function(){"pause_turn"!==se(this,di,"f")&&0!==se(this,pi,"f").length&&(se(this,si,"f").params.messages.push(se(this,Zr,"m",xi).call(this)),te(this,pi,[],"f"))},xi=function(){const e=[];for(const t of se(this,pi,"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 Ti(e){if("compaction"in e&&null!=e.compaction)throw new U("`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 Ei(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 Mi(e){if(e.context_management?.edits?.some(e=>e.type.startsWith("compact_")))throw new U("`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 Oi(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 Hn?i.content:`Error: ${i instanceof Error?i.message:String(i)}`,is_error:!0}}}function Pi(e){return e}function Ci(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 Li(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 Ni=["claude-mythos-preview","claude-opus-4-6"],qi=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.batches=new cr(this._client)}create(e,t){const s=Wi(e),{betas:n,user_profile_id:r,workspace_id:i,...o}=s;o.model,Ni.includes(o.model)&&o.thinking&&o.thinking.type;let a=t?.timeout??this._client._options.timeout;if(!o.stream&&null==a){const e=lr[o.model]??void 0;a=this._client.calculateNonstreamingTimeout(o.max_tokens,e)}const c=ks(o.tools,o.messages);return this._client.post("/v1/messages?beta=true",{body:o,timeout:a??6e5,...t,headers:cs([{...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:cs([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},t?.headers])},this.create(e,t).then(t=>ur(t,e,{logger:this._client.logger??console}))}stream(e,t){return Ii.createMessage(this,e,t)}countTokens(e,t){const{betas:s,user_profile_id:n,workspace_id:r,...i}=Wi(e);return this._client.post("/v1/messages/count_tokens?beta=true",{body:i,...t,headers:cs([{"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 $i(this._client,e,t)}}return e.Batches=cr,e.BetaToolRunner=$i,e.ToolError=Hn,e})();function Wi(e){if(!e.output_format)return e;if(e.output_config?.format)throw new U("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 ji,Ui,Di,Hi,zi,Fi,Bi,Ki,Ji,Vi,Xi,Gi,Yi,Qi,Zi,eo,to,so,no,ro,io,oo,ao,co,lo,ho=class extends ss{retrieve(e,t){return this._client.get(us`/v1/organizations/api_keys/${e}?beta=true`,t)}update(e,t,s){return this._client.post(us`/v1/organizations/api_keys/${e}?beta=true`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/api_keys?beta=true",Ht,{query:e,...t})}},uo=class extends ss{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})}},po=class extends ss{create(e,t){return this._client.post("/v1/organizations/external_keys?beta=true",{body:e,...t})}retrieve(e,t){return this._client.get(us`/v1/organizations/external_keys/${e}?beta=true`,t)}update(e,t,s){return this._client.post(us`/v1/organizations/external_keys/${e}?beta=true`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/external_keys?beta=true",zt,{query:e,...t})}delete(e,t){return this._client.delete(us`/v1/organizations/external_keys/${e}?beta=true`,t)}validate(e,t){return this._client.post(us`/v1/organizations/external_keys/${e}/validate?beta=true`,t)}},fo=class extends ss{create(e,t){return this._client.post("/v1/organizations/invites?beta=true",{body:e,...t})}retrieve(e,t){return this._client.get(us`/v1/organizations/invites/${e}?beta=true`,t)}list(e={},t){return this._client.getAPIList("/v1/organizations/invites?beta=true",Ht,{query:e,...t})}delete(e,t){return this._client.delete(us`/v1/organizations/invites/${e}?beta=true`,t)}},go=class extends ss{list(e={},t){return this._client.getAPIList("/v1/organizations/rate_limits?beta=true",zt,{query:e,...t})}},mo=class extends ss{retrieve(e,t){return this._client.get(us`/v1/organizations/users/${e}?beta=true`,t)}update(e,t,s){return this._client.post(us`/v1/organizations/users/${e}?beta=true`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/users?beta=true",Ht,{query:e,...t})}remove(e,t){return this._client.delete(us`/v1/organizations/users/${e}?beta=true`,t)}},_o=class extends ss{create(e,t){const{betas:s,...n}=e;return this._client.post("/v1/organizations/federation_issuers?beta=true",{body:n,...t,headers:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n}=t??{};return this._client.get(us`/v1/organizations/federation_issuers/${e}?beta=true`,{...s,headers:cs([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}update(e,t,s){const{betas:n,...r}=t;return this._client.post(us`/v1/organizations/federation_issuers/${e}?beta=true`,{body:r,...s,headers:cs([{...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",zt,{query:n,...t,headers:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}archive(e,t={},s){const{betas:n}=t??{};return this._client.post(us`/v1/organizations/federation_issuers/${e}/archive?beta=true`,{...s,headers:cs([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}},wo=class extends ss{list(e,t={},s){const{betas:n,...r}=t??{};return this._client.getAPIList(us`/v1/organizations/federation_rules/${e}/workspaces?beta=true`,zt,{query:r,...s,headers:cs([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}add(e,t,s){const{betas:n,...r}=t;return this._client.post(us`/v1/organizations/federation_rules/${e}/workspaces?beta=true`,{body:r,...s,headers:cs([{...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(us`/v1/organizations/federation_rules/${n}/workspaces/${e}?beta=true`,{...s,headers:cs([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}},yo=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.workspaces=new wo(this._client)}create(e,t){const{betas:s,...n}=e;return this._client.post("/v1/organizations/federation_rules?beta=true",{body:n,...t,headers:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n}=t??{};return this._client.get(us`/v1/organizations/federation_rules/${e}?beta=true`,{...s,headers:cs([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}update(e,t,s){const{betas:n,...r}=t;return this._client.post(us`/v1/organizations/federation_rules/${e}?beta=true`,{body:r,...s,headers:cs([{...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",zt,{query:n,...t,headers:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}archive(e,t={},s){const{betas:n}=t??{};return this._client.post(us`/v1/organizations/federation_rules/${e}/archive?beta=true`,{...s,headers:cs([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}}return e.Workspaces=wo,e})(),bo=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.issuers=new _o(this._client),this.rules=new yo(this._client)}}return e.Issuers=_o,e.Rules=yo,e})(),vo=class extends ss{list(e,t={},s){const{betas:n,...r}=t??{};return this._client.getAPIList(us`/v1/organizations/service_accounts/${e}/workspaces?beta=true`,zt,{query:r,...s,headers:cs([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}add(e,t,s){const{betas:n,...r}=t;return this._client.post(us`/v1/organizations/service_accounts/${e}/workspaces?beta=true`,{body:r,...s,headers:cs([{...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(us`/v1/organizations/service_accounts/${n}/workspaces/${e}?beta=true`,{...s,headers:cs([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}},ko=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.workspaces=new vo(this._client)}create(e,t){const{betas:s,...n}=e;return this._client.post("/v1/organizations/service_accounts?beta=true",{body:n,...t,headers:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}retrieve(e,t={},s){const{betas:n}=t??{};return this._client.get(us`/v1/organizations/service_accounts/${e}?beta=true`,{...s,headers:cs([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}update(e,t,s){const{betas:n,...r}=t;return this._client.post(us`/v1/organizations/service_accounts/${e}?beta=true`,{body:r,...s,headers:cs([{...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",zt,{query:n,...t,headers:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}archive(e,t={},s){const{betas:n}=t??{};return this._client.post(us`/v1/organizations/service_accounts/${e}/archive?beta=true`,{...s,headers:cs([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}}return e.Workspaces=vo,e})(),So=class extends ss{retrieve(e,t,s){const{workspace_id:n}=t;return this._client.get(us`/v1/organizations/workspaces/${n}/members/${e}?beta=true`,s)}update(e,t,s){const{workspace_id:n,...r}=t;return this._client.post(us`/v1/organizations/workspaces/${n}/members/${e}?beta=true`,{body:r,...s})}list(e,t={},s){return this._client.getAPIList(us`/v1/organizations/workspaces/${e}/members?beta=true`,Ht,{query:t,...s})}add(e,t,s){return this._client.post(us`/v1/organizations/workspaces/${e}/members?beta=true`,{body:t,...s})}remove(e,t,s){const{workspace_id:n}=t;return this._client.delete(us`/v1/organizations/workspaces/${n}/members/${e}?beta=true`,s)}},xo=class extends ss{list(e,t={},s){return this._client.getAPIList(us`/v1/organizations/workspaces/${e}/rate_limits?beta=true`,zt,{query:t,...s})}},Io=class extends ss{retrieve(e,t,s){const{workspace_id:n,betas:r}=t;return this._client.get(us`/v1/organizations/workspaces/${n}/service_accounts/${e}?beta=true`,{...s,headers:cs([{...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(us`/v1/organizations/workspaces/${n}/service_accounts/${e}?beta=true`,{body:i,...s,headers:cs([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}list(e,t={},s){const{betas:n,...r}=t??{};return this._client.getAPIList(us`/v1/organizations/workspaces/${e}/service_accounts?beta=true`,zt,{query:r,...s,headers:cs([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}add(e,t,s){const{betas:n,...r}=t;return this._client.post(us`/v1/organizations/workspaces/${e}/service_accounts?beta=true`,{body:r,...s,headers:cs([{...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(us`/v1/organizations/workspaces/${n}/service_accounts/${e}?beta=true`,{...s,headers:cs([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}},Ro=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.rateLimits=new xo(this._client),this.members=new So(this._client),this.serviceAccounts=new Io(this._client)}create(e,t){const{betas:s,...n}=e;return this._client.post("/v1/organizations/workspaces?beta=true",{body:n,...t,headers:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}retrieve(e,t){return this._client.get(us`/v1/organizations/workspaces/${e}?beta=true`,t)}update(e,t,s){return this._client.post(us`/v1/organizations/workspaces/${e}?beta=true`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/v1/organizations/workspaces?beta=true",Ht,{query:e,...t})}archive(e,t){return this._client.post(us`/v1/organizations/workspaces/${e}/archive?beta=true`,t)}}return e.RateLimits=xo,e.Members=So,e.ServiceAccounts=Io,e})(),Ao=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.apiKeys=new ho(this._client),this.externalKeys=new po(this._client),this.federation=new bo(this._client),this.invites=new fo(this._client),this.serviceAccounts=new ko(this._client),this.users=new mo(this._client),this.workspaces=new Ro(this._client),this.rateLimits=new go(this._client),this.complianceSettings=new uo(this._client)}retrieve(e){return this._client.get("/v1/organizations/me?beta=true",e)}}return e.APIKeys=ho,e.ExternalKeys=po,e.Federation=bo,e.Invites=fo,e.ServiceAccounts=ko,e.Users=mo,e.Workspaces=Ro,e.RateLimits=go,e.ComplianceSettings=uo,e})(),$o=/* @__PURE__ */(()=>{class e extends ss{list(e,t={},s){const{betas:n,workspace_id:r,...i}=t??{};return this._client.getAPIList(us`/v1/sessions/${e}/events?beta=true`,zt,{query:i,...s,headers:cs([{"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(us`/v1/sessions/${e}/events?beta=true`,{body:i,...s,headers:cs([{"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(us`/v1/sessions/${e}/events/stream?beta=true`,{query:i,...s,headers:cs([{"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 Qn(e,{...t,client:this._client})}}return e.SessionToolRunner=Qn,e})(),To=class extends ss{retrieve(e,t,s){const{session_id:n,betas:r,workspace_id:i}=t;return this._client.get(us`/v1/sessions/${n}/resources/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/sessions/${n}/resources/${e}?beta=true`,{body:o,...s,headers:cs([{"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(us`/v1/sessions/${e}/resources?beta=true`,zt,{query:i,...s,headers:cs([{"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(us`/v1/sessions/${n}/resources/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/sessions/${e}/resources?beta=true`,{body:i,...s,headers:cs([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},Eo=class extends ss{list(e,t,s){const{session_id:n,betas:r,workspace_id:i,...o}=t;return this._client.getAPIList(us`/v1/sessions/${n}/threads/${e}/events?beta=true`,zt,{query:o,...s,headers:cs([{"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(us`/v1/sessions/${n}/threads/${e}/stream?beta=true`,{query:o,...s,headers:cs([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers]),stream:!0})}},Mo=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.events=new Eo(this._client)}retrieve(e,t,s){const{session_id:n,betas:r,workspace_id:i}=t;return this._client.get(us`/v1/sessions/${n}/threads/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/sessions/${e}/threads?beta=true`,zt,{query:i,...s,headers:cs([{"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(us`/v1/sessions/${n}/threads/${e}/archive?beta=true`,{...s,headers:cs([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}}return e.Events=Eo,e})(),Oo=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.events=new $o(this._client),this.resources=new To(this._client),this.threads=new Mo(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:cs([{"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(us`/v1/sessions/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/sessions/${e}?beta=true`,{body:i,...s,headers:cs([{"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",Ft,{query:r,...t,headers:cs([{"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(us`/v1/sessions/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/sessions/${e}/archive?beta=true`,{...s,headers:cs([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Events=$o,e.Resources=To,e.Threads=Mo,e})(),Po=class extends ss{create(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(us`/v1/skills/${e}/versions?beta=true`,Xt({body:i,...s,headers:cs([{...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(us`/v1/skills/${n}/versions/${e}?beta=true`,{...s,headers:cs([{...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(us`/v1/skills/${e}/versions?beta=true`,zt,{query:i,...s,headers:cs([{...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(us`/v1/skills/${n}/versions/${e}?beta=true`,{...s,headers:cs([{...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(us`/v1/skills/${n}/versions/${e}/content?beta=true`,{...s,headers:cs([{Accept:"application/binary",...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0,...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers]),__binaryResponse:!0})}},Co=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.versions=new Po(this._client)}create(e,t){const{betas:s,workspace_id:n,...r}=e;return this._client.post("/v1/skills?beta=true",Xt({body:r,...t,headers:cs([{...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(us`/v1/skills/${e}?beta=true`,{...s,headers:cs([{...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",zt,{query:r,...t,headers:cs([{...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(us`/v1/skills/${e}?beta=true`,{...s,headers:cs([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0,...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Versions=Po,e})(),Lo=class extends ss{create(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(us`/v1/tunnels/${e}/certificates?beta=true`,{body:i,...s,headers:cs([{"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(us`/v1/tunnels/${n}/certificates/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/tunnels/${e}/certificates?beta=true`,zt,{query:i,...s,headers:cs([{"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(us`/v1/tunnels/${n}/certificates/${e}/archive?beta=true`,{...s,headers:cs([{"anthropic-beta":[...r??[],"mcp-tunnels-2026-06-22"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}},No=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.certificates=new Lo(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:cs([{"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(us`/v1/tunnels/${e}?beta=true`,{...s,headers:cs([{"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",zt,{query:r,...t,headers:cs([{"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(us`/v1/tunnels/${e}/archive?beta=true`,{...s,headers:cs([{"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(us`/v1/tunnels/${e}/reveal_token?beta=true`,{...s,headers:cs([{"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(us`/v1/tunnels/${e}/rotate_token?beta=true`,{body:i,...s,headers:cs([{"anthropic-beta":[...n??[],"mcp-tunnels-2026-06-22"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Certificates=Lo,e})(),qo=class extends ss{create(e,t,s){const{betas:n,workspace_id:r,...i}=t;return this._client.post(us`/v1/vaults/${e}/credentials?beta=true`,{body:i,...s,headers:cs([{"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(us`/v1/vaults/${n}/credentials/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/vaults/${n}/credentials/${e}?beta=true`,{body:o,...s,headers:cs([{"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(us`/v1/vaults/${e}/credentials?beta=true`,zt,{query:i,...s,headers:cs([{"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(us`/v1/vaults/${n}/credentials/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/vaults/${n}/credentials/${e}/archive?beta=true`,{...s,headers:cs([{"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(us`/v1/vaults/${n}/credentials/${e}/mcp_oauth_validate?beta=true`,{...s,headers:cs([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString(),...null!=i?{"anthropic-workspace-id":i}:void 0},s?.headers])})}},Wo=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.credentials=new qo(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:cs([{"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(us`/v1/vaults/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/vaults/${e}?beta=true`,{body:i,...s,headers:cs([{"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",zt,{query:r,...t,headers:cs([{"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(us`/v1/vaults/${e}?beta=true`,{...s,headers:cs([{"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(us`/v1/vaults/${e}/archive?beta=true`,{...s,headers:cs([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}}return e.Credentials=qo,e})(),jo=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.models=new Ws(this._client),this.messages=new qi(this._client),this.agents=new Js(this._client),this.environments=new nr(this._client),this.sessions=new Oo(this._client),this.deployments=new fs(this._client),this.deploymentRuns=new ps(this._client),this.vaults=new Wo(this._client),this.memoryStores=new or(this._client),this.files=new qs(this._client),this.skills=new Co(this._client),this.webhooks=new Bs(this._client),this.userProfiles=new js(this._client),this.dreams=new gs(this._client),this.tunnels=new No(this._client),this.organization=new Ao(this._client)}}return e.Models=Ws,e.Messages=qi,e.Agents=Js,e.Environments=nr,e.Sessions=Oo,e.Deployments=fs,e.DeploymentRuns=ps,e.Vaults=Wo,e.MemoryStores=or,e.Files=qs,e.Skills=Co,e.Webhooks=Bs,e.UserProfiles=js,e.Dreams=gs,e.Tunnels=No,e.Organization=Ao,e})(),Uo=class extends ss{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:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers]),stream:e.stream??!1})}},Do=class extends ss{list(e={},t){const{workspace_id:s,...n}=e??{};return this._client.getAPIList("/v1/files",zt,{query:n,...t,headers:cs([{...null!=s?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(e,t={},s){const{workspace_id:n}=t??{};return this._client.delete(us`/v1/files/${e}`,{...s,headers:cs([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}download(e,t={},s){const{workspace_id:n}=t??{};return this._client.get(us`/v1/files/${e}/content`,{...s,headers:cs([{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(us`/v1/files/${e}`,{...s,headers:cs([{...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",Xt({body:n,...t,headers:cs([{...null!=s?{"anthropic-workspace-id":s}:void 0},Ss(n.file),t?.headers])},this._client))}};function Ho(e){return e?.output_config?.format}function zo(e,t,s){const n=Ho(t);return t&&"parse"in(n??{})?Fo(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 Fo(e,t,s){let n=null;const r=e.content.map(e=>{if("text"===e.type){const s=function(e,t){const s=Ho(e);if("json_schema"!==s?.type)return null;try{return"parse"in s?s.parse(t):JSON.parse(t)}catch(n){throw new U(`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 Bo(e){return"tool_use"===e.type||"server_tool_use"===e.type}var Ko,Jo,Vo,Xo,Go=/* @__PURE__ */(()=>{class e{constructor(e,t){ji.add(this),this.messages=[],this.receivedMessages=[],Ui.set(this,void 0),Di.set(this,null),this.controller=new AbortController,Hi.set(this,void 0),zi.set(this,()=>{}),Fi.set(this,()=>{}),Bi.set(this,void 0),Ki.set(this,()=>{}),Ji.set(this,()=>{}),Vi.set(this,{}),Xi.set(this,!1),Gi.set(this,!1),Yi.set(this,!1),Qi.set(this,!1),Zi.set(this,void 0),eo.set(this,void 0),to.set(this,void 0),so.set(this,void 0),io.set(this,e=>{if(te(this,Gi,!0,"f"),W(e)&&(e=new H),e instanceof H)return te(this,Yi,!0,"f"),this._emit("abort",e);if(e instanceof U)return this._emit("error",e);if(e instanceof Error){const t=new U(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new U(String(e)))}),te(this,Hi,new Promise((e,t)=>{te(this,zi,e,"f"),te(this,Fi,t,"f")}),"f"),te(this,Bi,new Promise((e,t)=>{te(this,Ki,e,"f"),te(this,Ji,t,"f")}),"f"),se(this,Hi,"f").catch(()=>{}),se(this,Bi,"f").catch(()=>{}),te(this,Di,e,"f"),te(this,so,t?.logger??console,"f")}get response(){return se(this,Zi,"f")}get request_id(){return se(this,eo,"f")}get workspace_id(){return se(this,to,"f")}async withResponse(){te(this,Qi,!0,"f");const e=await se(this,Hi,"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 te(i,Di,{...s,stream:!0},"f"),i._run(()=>i._createMessage(t,{...s,stream:!0},{...n,headers:{...n?.headers,[_s]:"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},se(this,io,"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{se(this,ji,"m",oo).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)se(this,ji,"m",ao).call(this,e);if(r.controller.signal?.aborted)throw new H;se(this,ji,"m",co).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}_connected(e){this.ended||(te(this,Zi,e,"f"),te(this,eo,e?.headers.get("request-id"),"f"),te(this,to,e?.headers.get("anthropic-workspace-id"),"f"),se(this,zi,"f").call(this,e),this._emit("connect"))}get ended(){return se(this,Xi,"f")}get errored(){return se(this,Gi,"f")}get aborted(){return se(this,Yi,"f")}abort(){this.controller.abort()}on(e,t){return(se(this,Vi,"f")[e]||(se(this,Vi,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=se(this,Vi,"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(se(this,Vi,"f")[e]||(se(this,Vi,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{te(this,Qi,!0,"f"),"error"!==e&&this.once("error",s),this.once(e,t)})}async done(){te(this,Qi,!0,"f"),await se(this,Bi,"f")}get currentMessage(){return se(this,Ui,"f")}async finalMessage(){return await this.done(),se(this,ji,"m",no).call(this)}async finalText(){return await this.done(),se(this,ji,"m",ro).call(this)}_emit(e,...t){if(se(this,Xi,"f"))return;"end"===e&&(te(this,Xi,!0,"f"),se(this,Ki,"f").call(this));const s=se(this,Vi,"f")[e];if(s&&(se(this,Vi,"f")[e]=s.filter(e=>!e.once),s.forEach(({listener:e})=>e(...t))),"abort"===e){const e=t[0];return se(this,Qi,"f")||s?.length||Promise.reject(e),se(this,Fi,"f").call(this,e),se(this,Ji,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];se(this,Qi,"f")||s?.length||Promise.reject(e),se(this,Fi,"f").call(this,e),se(this,Ji,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",se(this,ji,"m",no).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{se(this,ji,"m",oo).call(this),this._connected(null);const t=$t.fromReadableStream(e,this.controller);for await(const e of t)se(this,ji,"m",ao).call(this,e);if(t.controller.signal?.aborted)throw new H;se(this,ji,"m",co).call(this)}finally{s&&n&&s.removeEventListener("abort",n)}}[(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,Yi=/* @__PURE__ */new WeakMap,Qi=/* @__PURE__ */new WeakMap,Zi=/* @__PURE__ */new WeakMap,eo=/* @__PURE__ */new WeakMap,to=/* @__PURE__ */new WeakMap,so=/* @__PURE__ */new WeakMap,io=/* @__PURE__ */new WeakMap,ji=/* @__PURE__ */new WeakSet,no=function(){if(0===this.receivedMessages.length)throw new U("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},ro=function(){if(0===this.receivedMessages.length)throw new U("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 U("stream ended without producing a content block with type=text");return e.join(" ")},oo=function(){this.ended||te(this,Ui,void 0,"f")},ao=function(e){if(this.ended)return;const t=se(this,ji,"m",lo).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":Bo(s)&&se(this,Vi,"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(zo(t,se(this,Di,"f"),se(this,so,"f")),!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":te(this,Ui,t,"f")}},co=function(){if(this.ended)throw new U("stream has ended, this shouldn't happen");const e=se(this,Ui,"f");if(!e)throw new U("request ended without sending any chunks");return te(this,Ui,void 0,"f"),zo(e,se(this,Di,"f"),se(this,so,"f"))},lo=function(e){let t=se(this,Ui,"f");if("message_start"===e.type){if(t)throw new U(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new U(`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&&Bo(s)){const n=(s.__json_buf||"")+e.delta.partial_json;t.content[e.index]=Ur(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&&Bo(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 $t(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}return e})(),Yo=class extends ss{create(e,t){const{user_profile_id:s,workspace_id:n,...r}=e;return this._client.post("/v1/messages/batches",{body:r,...t,headers:cs([{...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(us`/v1/messages/batches/${e}`,{...s,headers:cs([{...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",Ht,{query:n,...t,headers:cs([{...null!=s?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(e,t={},s){const{workspace_id:n}=t??{};return this._client.delete(us`/v1/messages/batches/${e}`,{...s,headers:cs([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}cancel(e,t={},s){const{workspace_id:n}=t??{};return this._client.post(us`/v1/messages/batches/${e}/cancel`,{...s,headers:cs([{...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 U(`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:cs([{Accept:"application/binary",...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>ar.fromResponse(t.response,t.controller))}},Qo=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.batches=new Yo(this._client)}create(e,t){const{user_profile_id:s,workspace_id:n,...r}=e;r.model,Zo.includes(r.model)&&r.thinking&&r.thinking.type;let i=t?.timeout??this._client._options.timeout;if(!r.stream&&null==i){const e=lr[r.model]??void 0;i=this._client.calculateNonstreamingTimeout(r.max_tokens,e)}const o=ks(r.tools,r.messages);return this._client.post("/v1/messages",{body:r,timeout:i??6e5,...t,headers:cs([{...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=>Fo(t,e,this._client.logger??console))}stream(e,t){return Go.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:cs([{...null!=s?{"anthropic-user-profile-id":s}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}}return e.Batches=Yo,e})(),Zo=["claude-mythos-preview","claude-opus-4-6"],ea=class extends ss{retrieve(e,t={},s){const{betas:n,workspace_id:r}=t??{};return this._client.get(us`/v1/models/${e}`,{...s,headers:cs([{...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",Ht,{query:r,...t,headers:cs([{...null!=s?.toString()?{"anthropic-beta":s?.toString()}:void 0,...null!=n?{"anthropic-workspace-id":n}:void 0},t?.headers])})}},ta=class extends ss{create(e,t,s){const{workspace_id:n,...r}=t;return this._client.post(us`/v1/skills/${e}/versions`,Xt({body:r,...s,headers:cs([{...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(us`/v1/skills/${n}/versions/${e}`,{...s,headers:cs([{...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}list(e,t={},s){const{workspace_id:n,...r}=t??{};return this._client.getAPIList(us`/v1/skills/${e}/versions`,zt,{query:r,...s,headers:cs([{...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(us`/v1/skills/${n}/versions/${e}`,{...s,headers:cs([{...null!=r?{"anthropic-workspace-id":r}:void 0},s?.headers])})}},sa=/* @__PURE__ */(()=>{class e extends ss{constructor(){super(...arguments),this.versions=new ta(this._client)}create(e,t){const{workspace_id:s,...n}=e;return this._client.post("/v1/skills",Xt({body:n,...t,headers:cs([{...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(us`/v1/skills/${e}`,{...s,headers:cs([{...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",zt,{query:n,...t,headers:cs([{...null!=s?{"anthropic-workspace-id":s}:void 0},t?.headers])})}delete(e,t={},s){const{workspace_id:n}=t??{};return this._client.delete(us`/v1/skills/${e}`,{...s,headers:cs([{...null!=n?{"anthropic-workspace-id":n}:void 0},s?.headers])})}}return e.Versions=ta,e})(),na=/* @__PURE__ */(()=>{class e{get credentials(){return this._authState.provider}constructor({baseURL:e=Qe("ANTHROPIC_BASE_URL"),apiKey:t,authToken:s,webhookKey:n=Qe("ANTHROPIC_WEBHOOK_SIGNING_KEY")??null,...r}={}){if(Ko.add(this),this._requestAuthFlags=/* @__PURE__ */new WeakMap,Vo.set(this,void 0),void 0===t&&(t=null!=r.profile?null:Qe("ANTHROPIC_API_KEY")??null),void 0===s&&(s=null!=r.profile?null:Qe("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 U("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??Jo.DEFAULT_TIMEOUT,this.logger=i.logger??console,this.logLevel="warn",this.logLevel=st(i.logLevel,"ClientOptions.logLevel",ht(this))??st(Qe("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",ht(this))??"warn",this.fetchOptions=i.fetchOptions,this.maxRetries=he("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`")}(),te(this,Vo,Se,"f"),this.middleware=[...i.middleware??[]];const o=Qe("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=xt(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=>{ht(this).debug("credential cache write failed (best-effort)",e)},onSafetyWarning:e=>{ht(this).warn(e)}}}_credentialsFetch(){return Nt(this.fetch,this.middleware,void 0,this)}_makeTokenCache(e){return new Ye(e,e=>{ht(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 bt();if(null===n)return null;const r=e??await kt();if(null===r)return null;mt(r);const{fs:i,path:o}=await(import("./node.browser-BDF4XvCU.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=Qe("ANTHROPIC_ORGANIZATION_ID"),t=Qe("ANTHROPIC_IDENTITY_TOKEN_FILE"),s=Qe("ANTHROPIC_FEDERATION_RULE_ID");return s&&e?{fromFile:!1,config:{organization_id:e,workspace_id:Qe("ANTHROPIC_WORKSPACE_ID"),base_url:Qe("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:s,service_account_id:Qe("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:t?{source:"file",path:t}:void 0,scope:Qe("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=Qe("ANTHROPIC_ORGANIZATION_ID")),l.workspace_id??(l.workspace_id=Qe("ANTHROPIC_WORKSPACE_ID")),l.base_url??(l.base_url=Qe("ANTHROPIC_BASE_URL")),(t=l.authentication).scope??(t.scope=Qe("ANTHROPIC_SCOPE")),"oidc_federation"===l.authentication.type){if(!l.authentication.identity_token){const e=Qe("ANTHROPIC_IDENTITY_TOKEN_FILE");e&&(l.authentication.identity_token={source:"file",path:e})}l.authentication.federation_rule_id||(l.authentication.federation_rule_id=Qe("ANTHROPIC_FEDERATION_RULE_ID")??""),(s=l.authentication).service_account_id??(s.service_account_id=Qe("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:l,fromFile:!0}})(t);if(!s)return null;const{config:n,fromFile:r}=s;return xt(n.authentication.credentials_path||!r?n:{...n,authentication:{...n.authentication,credentials_path:await yt(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 U(`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,cs([{Authorization:`Bearer ${t}`}])}return cs([await this.apiKeyAuth(e),await this.bearerAuth(e)])}}async apiKeyAuth(e){if(null!=this.apiKey)return cs([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(null!=this.authToken)return cs([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return function(e){return function(e,t={}){let s=e;const n=function(e=Ce){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||Ce.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=xe;if(void 0!==e.format){if(!Ae(Re,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const n=Re[s];let r,i=Ce.filter;if(("function"==typeof e.filter||re(e.filter))&&(i=e.filter),r=e.arrayFormat&&e.arrayFormat in Oe?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":Ce.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||Ce.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:Ce.addQueryPrefix,allowDots:o,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:Ce.allowEmptyArrays,arrayFormat:r,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Ce.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?Ce.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:Ce.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:Ce.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:Ce.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:Ce.encodeValuesOnly,filter:i,format:s,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:Ce.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:Ce.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Ce.strictNullHandling}}(t);let r,i;"function"==typeof n.filter?(i=n.filter,s=i("",s)):re(n.filter)&&(i=n.filter,r=i);const o=[];if("object"!=typeof s||null===s)return"";const a=Oe[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]||Pe(o,Ne(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 ${pe}`}makeStatusError(e,t,s,n){return D.generate(e,t,s,n)}buildURL(e,t,s){const n=!se(this,Ko,"m",Xo).call(this)&&s||this.baseURL,r=(e=>ne.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 ae(i)&&ae(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 U("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??[],We].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 jt(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){const n=await e;let r=he("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 H;const d=new AbortController,u=await this.fetchWithTimeout(o,i,a,d,n,{requestLogID:c,retryOfRequestLogID:s}).catch(j),p=Date.now();if(u instanceof globalThis.Error){ye(d);const e=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new H;const r=W(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),Lt(e)||W(e)||e instanceof z||e instanceof B)return!0;e=e.cause}return!1}(u))throw ht(this).info(`[${c}] middleware error (not retryable)`),ut(ht(this),`[${c}] middleware error (not retryable)`,{retryOfRequestLogID:s,url:o,durationMs:p-h,message:u.message}),u;if(t)return ht(this).info(`[${c}] connection ${r?"timed out":"failed"} - ${e}`),ut(ht(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(ht(this).info(`[${c}] connection ${r?"timed out":"failed"} - error; no more retries left`),ut(ht(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 F;if(i&&!Lt(u))throw u;throw new z({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),ye(d),ht(this).info(`${f} - ${e}`),ut(ht(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";ht(this).info(`${f} - ${r}`);const i=await u.text().catch(e=>j(e).message),o=de(i),a=o?void 0:i;throw ut(ht(this),`[${c}] response error (${r})`,{retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,message:a,durationMs:Date.now()-h}),ye(d),this.makeStatusError(u.status,o,a,u.headers)}return ht(this).info(f),ut(ht(this),`[${c}] response start`,{retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,durationMs:p-h}),function(e,t){_e.has(t)&&we?.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 Dt(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){_e.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&&ut(ht(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 Nt(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 ue(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 U("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&&he("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=cs([{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),"X-Stainless-Timeout":String(Math.trunc(r/1e3)),...me(),...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=cs([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:ve(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)}:se(this,Vo,"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 Jo=e,Vo=/* @__PURE__ */new WeakMap,Ko=/* @__PURE__ */new WeakSet,Xo=function(){return"https://api.anthropic.com"!==this.baseURL},e.Anthropic=Jo,e.DEFAULT_TIMEOUT=6e5,e.AnthropicError=U,e.APIError=D,e.APIConnectionError=z,e.APIConnectionTimeoutError=F,e.APIUserAbortError=H,e.NotFoundError=X,e.ConflictError=G,e.RateLimitError=Q,e.BadRequestError=K,e.AuthenticationError=J,e.InternalServerError=Z,e.PermissionDeniedError=V,e.UnprocessableEntityError=Y,e.toFile=es,e.HUMAN_PROMPT="\\n\\nHuman:",e.AI_PROMPT="\\n\\nAssistant:",e})(),ra=/* @__PURE__ */(()=>{class e extends na{constructor(){super(...arguments),this.completions=new Uo(this),this.messages=new Qo(this),this.models=new ea(this),this.files=new Do(this),this.skills=new sa(this),this.beta=new jo(this)}}return e.Completions=Uo,e.Messages=Qo,e.Models=ea,e.Files=Do,e.Skills=sa,e.Beta=jo,e})(),ia=["The compiled grammar is too large","Too many strict tools (","Schemas contains too many parameters with union types ("];function oa(e){return ia.some(t=>e.includes(t))}var aa=/* @__PURE__ */new Set;function ca(e){if(void 0!==e&&(aa.add(e),aa.size>1e4)){const e=aa.values().next().value;void 0!==e&&aa.delete(e)}}q(e=>{e?aa.delete(e):aa.clear()});var la=/* @__PURE__ */e({stream:()=>Na,streamSimple:()=>qa});function ha(e,t){return e||("long"===y("PI_CACHE_RETENTION",t)?"long":"short")}var da=new Map(["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"].map(e=>[e.toLowerCase(),e])),ua=e=>da.get(e.toLowerCase())??e,pa=(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 fa(e){return{type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}}}function ga(e){if(!e.some(e=>"image"===e.type))return A(e.map(e=>e.text).join("\n"));const t=e.map(e=>"text"===e.type?{type:"text",text:A(e.text)}:fa(e));return t.some(e=>"text"===e.type)||t.unshift({type:"text",text:"(see attached image)"}),t}var ma={name:"__pi_deferred_placeholder__",description:"Reserved placeholder. Never available. Never call this.",input_schema:{type:"object",properties:{},required:[]},defer_loading:!0};function _a(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,supportsMessageThreads:e.compat?.supportsMessageThreads??("anthropic"===e.provider&&e.baseUrl.includes("api.anthropic.com"))}}var wa=/* @__PURE__ */new Map,ya=/* @__PURE__ */new Set(["thread_not_found","thread_already_continued","thread_continue_in_flight","thread_fingerprint_mismatch"]);function ba(e,t){if(wa.delete(e),wa.set(e,t),wa.size>1e4){const e=wa.keys().next().value;void 0!==e&&wa.delete(e)}}function va(e,t,s){const{system:n,tools:r,thinking:i,output_config:o,tool_choice:a,betas:c,fallbacks:l}=t,h=JSON.stringify([e.provider,e.baseUrl,t.model,n,r,i,o,a,c,l]),d=JSON.stringify(s,(e,t)=>{if("cache_control"!==e)return"content"===e&&"string"==typeof t?[{type:"text",text:t}]:t});return b(h+d)}function ka(e,t){return{sessionId:e,body:{...t,thread:{type:"create"}}}}function Sa(e,t,s){const n=wa.get(t);if("off"!==n){if(void 0!==n&&s.messages.length>n.prefixCount&&va(e,s,s.messages.slice(0,n.prefixCount))===n.prefixHash){wa.delete(t);const{system:e,tools:r,...i}=s;return{body:{...i,messages:s.messages.slice(n.prefixCount),thread:{type:"continue",previous_message_id:n.replyId}},sessionId:t}}return ka(t,s)}}async function xa(e,t,s,n,i){try{return{response:await s(e.body),thread:e}}catch(o){if(i?.aborted||!(o instanceof ra.APIError))throw o;const a=function(e){const t=e.error?.error?.details?.error_code;return"string"==typeof t?t:void 0}(o),c=void 0!==a&&ya.has(a),l="thread_unsupported_request"===a||void 0===a&&400===o.status&&o.message.includes("thread");if(!c&&!l)throw o;if(r(n,{type:"anthropic_thread_fallback",timestamp:Date.now(),error:{message:o.message},details:{reason:a??String(o.status)}}),c){const n=ka(e.sessionId,t);return{response:await s(n.body),thread:n}}const h=await s(t);return ba(e.sessionId,"off"),{response:h,thread:void 0}}}function Ia(...e){const t={};for(const s of e)s&&Object.assign(t,s);return t}function Ra(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 Aa(e,t){return!!e||Ra(t,"authorization")||Ra(t,"x-api-key")||Ra(t,"cf-aig-authorization")}function $a(e,t,s){if(!Aa(t,s))throw new Error(`No API key for provider: ${e}`)}q(e=>{e?wa.delete(e):wa.clear()});var Ta,Ea=class extends ra{_shouldResolveDefaultCredentials(){return!1}};function Ma(e,t,s,n){if("anthropic"!==e.provider||Aa(t,s))return;const r=y(h,n),i=y(l,n),a=y(u,n);return r&&i&&a?{organization_id:i,workspace_id:y(d,n),authentication:{type:"oidc_federation",federation_rule_id:r,service_account_id:y(o,n),identity_token:{source:"file",path:a}}}:void 0}var Oa=/* @__PURE__ */new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);function Pa(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 Ca(e,t){if(""===e)return Pa(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 La(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 Na=(e,t,n)=>{const i=new s,o=_a(e),l=p(t,o.supportsMidConvoSystemMessages),h=c(l.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 d,u,p,f=e;const y="none"===ha(n?.cacheRetention,n?.env)?void 0:n?.sessionId,b=o.supportsMessageThreads?y:void 0;if(n?.client)d=n.client,u=!1;else{const t=n?.apiKey,s=Ma(e,t,n?.headers,n?.env);let r;if(s||$a(e.provider,t,n?.headers),"github-copilot"===e.provider){const e=w(l.messages);r=v({messages:l.messages,hasImages:e})}const i=function(e,t,s,n,r,i,o,a){if("github-copilot"===e.provider)return{client:new Ea({apiKey:null,authToken:t??null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:n,defaultHeaders:Ia(g(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 Ea({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:n,defaultHeaders:Ia({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","user-agent":"claude-cli/2.1.322","x-app":"cli"},e.headers,s)}),isOAuthToken:!0};const c=_a(e),l={};i&&c.sendSessionAffinityHeaders&&(l["openrouter"===c.sessionAffinityFormat?"x-session-id":"x-session-affinity"]=i);const h=Ia(g(e,a),{accept:"application/json","anthropic-dangerous-direct-browser-access":"true"},l,e.headers,s);if(o){const t=JSON.stringify([e.baseUrl,o]);return Ta?.key===t&&Ta.fetch===n||(Ta={key:t,fetch:n,client:new Ea({apiKey:null,authToken:null,config:o,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:n})}),{client:Ta.client.withOptions({defaultHeaders:h}),isOAuthToken:!1}}return{client:new Ea({apiKey:t??null,authToken:null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:n,defaultHeaders:h}),isOAuthToken:!1}}(e,t,n?.headers,n?.fetch,r,y,s,n?.identity);d=i.client,u=i.isOAuthToken}const S={...n?.signal?{signal:n.signal}:{},...void 0!==n?.timeoutMs?{timeout:n.timeoutMs}:{},maxRetries:0},A=e=>x(()=>d.beta.messages.create(e,S).asResponse(),{maxRetries:n?.maxRetries,maxRetryDelayMs:n?.maxRetryDelayMs,signal:n?.signal});let $,T,E,M=(s=n?.sessionId,void 0!==s&&aa.has(s));for(;;){n?.signal?.throwIfAborted();const s=Wa(e,l,u,n,{disablePreferredStrictTools:M,messageThreads:void 0!==b});s.providerThinkingLevel&&(t.providerThinkingLevel=s.providerThinkingLevel),T=s.params;const i=await(n?.onPayload?.(T,e));void 0!==i&&(T={...i,stream:!0});const o=void 0!==b&&!0!==n?.disableContinuation?Sa(e,b,T):void 0;try{const e=o?await xa(o,T,A,t,n?.signal):{response:await A(T),thread:void 0};$=e.response,E=e.thread;break}catch(c){if(n?.signal?.aborted||M||!s.hasPreferredStrictTools||!(c instanceof ra.APIError)||400!==c.status||"invalid_request_error"!==c.type||!oa(c.message))throw c;M=!0,ca(n?.sessionId),r(t,{type:"anthropic_strict_tools_fallback",timestamp:Date.now(),error:{message:c.message},details:{reason:"strict_tool_limits_exceeded"}})}}await(n?.onResponse?.({status:$.status,headers:k($.headers)},e)),i.push({type:"start",partial:t});const P=/* @__PURE__ */new Map,C=e=>{const s=P.get(e);return void 0===s?void 0:{...s,block:t.content[s.contentIndex]}};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=La(i);for(;a;){i=a.rest;const e=Ca(a.line,r);e&&(yield e),a=La(i)}}i+=n.decode();let e=La(i);for(;e;){i=e.rest;const t=Ca(e.line,r);t&&(yield t),e=La(i)}if(i.length>0){const e=Ca(i,r);e&&(yield e)}const o=Pa(r);o&&(yield o)}finally{s.releaseLock()}}(e.body,t)){if("error"===r.event)throw new Error(r.data);if(Oa.has(r.event??""))try{const e=m(r.data);"message_start"===e.type?s=!0:"message_stop"===e.type&&(n=!0),yield e}catch(c){const t=c instanceof Error?c.message:String(c);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")}($,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)&&(p=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;f=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(f,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}"text"===s.content_block.type?(t.content.push({type:"text",text:s.content_block.text??""}),P.set(s.index,{contentIndex:t.content.length-1}),i.push({type:"text_start",contentIndex:t.content.length-1,partial:t})):"thinking"===s.content_block.type?(t.content.push({type:"thinking",thinking:s.content_block.thinking??"",thinkingSignature:s.content_block.signature??""}),P.set(s.index,{contentIndex:t.content.length-1}),i.push({type:"thinking_start",contentIndex:t.content.length-1,partial:t})):"redacted_thinking"===s.content_block.type?(t.content.push({type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:s.content_block.data,redacted:!0}),P.set(s.index,{contentIndex:t.content.length-1}),i.push({type:"thinking_start",contentIndex:t.content.length-1,partial:t})):"tool_use"===s.content_block.type&&(t.content.push({type:"toolCall",id:s.content_block.id,name:u?pa(s.content_block.name,h):s.content_block.name,arguments:s.content_block.input??{}}),P.set(s.index,{contentIndex:t.content.length-1,arguments:new _}),i.push({type:"toolcall_start",contentIndex:t.content.length-1,partial:t}))}else if("content_block_delta"===s.type){const e=C(s.index);"text_delta"===s.delta.type?"text"===e?.block.type&&(e.block.text+=s.delta.text,i.push({type:"text_delta",contentIndex:e.contentIndex,delta:s.delta.text,partial:t})):"thinking_delta"===s.delta.type?"thinking"===e?.block.type&&(e.block.thinking+=s.delta.thinking,i.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:s.delta.thinking,partial:t})):"input_json_delta"===s.delta.type?"toolCall"===e?.block.type&&void 0!==e.arguments&&(e.block.arguments=e.arguments.append(s.delta.partial_json),i.push({type:"toolcall_delta",contentIndex:e.contentIndex,delta:s.delta.partial_json,partial:t})):"signature_delta"===s.delta.type&&"thinking"===e?.block.type&&(e.block.thinkingSignature=e.block.thinkingSignature||"",e.block.thinkingSignature+=s.delta.signature)}else if("content_block_stop"===s.type){const e=C(s.index);if(P.delete(s.index),e){const{block:s,contentIndex:n}=e;"text"===s.type?i.push({type:"text_end",contentIndex:n,content:s.text,partial:t}):"thinking"===s.type?i.push({type:"thinking_end",contentIndex:n,content:s.thinking,partial:t}):"toolCall"===s.type&&void 0!==e.arguments&&(Object.assign(s,e.arguments.finish()),i.push({type:"toolcall_end",contentIndex:n,toolCall:s,partial:t}))}}else if("message_delta"===s.type){const n=s.input_transformations;if(Array.isArray(n)&&(p=n),s.delta.stop_reason){t.rawStopReason=s.delta.stop_reason;const e=Ja(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(f,t.usage),I(e)&&s.usage&&R(t.usage,s.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");E&&function(e,t,s,n,r,i){if(void 0===n.responseId||void 0!==n.responseModel)return;const o=Da(O([n],e,ja),r,void 0,i).messages.filter(e=>"assistant"===e.role),a=[...s.messages,...o];ba(t.sessionId,{prefixCount:a.length,prefixHash:va(e,s,a),replyId:n.responseId})}(e,E,T,t,u,o.allowEmptySignature),p&&p.length>0&&r(t,{type:"anthropic_input_transformations",timestamp:Date.now(),details:{transformations:p.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(c){t.stopReason=n?.signal?.aborted?"aborted":"error",t.errorMessage=c instanceof Error?S(c):JSON.stringify(c),i.push({type:"error",reason:t.stopReason,error:t}),i.end()}var s})(),i},qa=(e,t,s)=>{Ma(e,s?.apiKey,s?.headers,s?.env)||$a(e.provider,s?.apiKey,s?.headers);const n={...E(e,t,s,s?.apiKey),toolChoice:s?.toolChoice};if(!s?.reasoning)return Na(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 Na(e,t,{...n,thinkingEnabled:!0,effort:r})}const r=C(n.maxTokens,e.maxTokens,s.reasoning,s.thinkingBudgets),i=$(e,t,r.maxTokens);return Na(e,t,{...n,maxTokens:i,thinkingEnabled:!0,thinkingBudgetTokens:Math.min(r.thinkingBudget,Math.max(0,i-1024))})};function Wa(e,t,s,r,o){const{cacheControl:a}=function(e,t,s){const n=ha(t,s);if("none"===n)return{retention:n};const r="long"===n&&_a(e).supportsLongCacheRetention?"1h":void 0;return{retention:n,cacheControl:{type:"ephemeral",...r&&{ttl:r}}}}(e,r?.cacheRetention,r?.env),l=_a(e),h=i(t.messages),d=h?n(h):"",u=O(t.messages,e,ja),p=h?u.slice(1):u;let f=!1;const g=(e,t)=>{const n=function(e,t,s,n,r,i=!1){return e?e.map((o,a)=>{const c=i&&M(o)?void 0:T(o,n,Ka),l=P(o,c),h=l,d={type:"object",properties:h.properties??{},required:h.required??[],...void 0===h.$defs?{}:{$defs:h.$defs},...void 0===h.definitions?{}:{definitions:h.definitions}},u=!0===c?{...l,...d}:d;return{name:t?ua(o.name):o.name,description:o.description,...s?{eager_input_streaming:!0}:{},...!0===c?{strict:!0}:{},input_schema:u,...r&&a===e.length-1?{cache_control:r}:{}}}):[]}(e,s,l.supportsEagerToolInputStreaming,l.supportsStrictTools,t,o.disablePreferredStrictTools);return n.some((t,s)=>!0===t.strict&&M(e[s]))&&(f=!0),n},m=h?.toolsAdded??[],_=l.supportsMidConvoSystemMessages&&l.supportsMidConvoToolChanges&&m.length>0,w=e.reasoning&&!1===r?.thinkingEnabled&&null!==e.thinkingLevelMap?.off,y=!0===e.compat?.supportsMidConvoEffort&&!w,b=Da(p,s,a,l.allowEmptySignature,y?e.provider:void 0,_?g:void 0),v=r?.effort??"high",k=function(e,t,s,{isOAuthToken:n,nativeToolChanges:r,messageThreads:i}){let o;for(const c of[e.headers,s?.headers])for(const[e,t]of Object.entries(c??{}))"anthropic-beta"===e.toLowerCase()&&(o=t);if(null===o)return[];if(void 0!==o)return[...new Set(o.split(",").map(e=>e.trim()).filter(e=>e.length>0))];const a=[];return n&&a.push("claude-code-20250219","oauth-2025-04-20"),function(e,t){return c(t.messages).length>0&&!_a(e).supportsEagerToolInputStreaming}(e,t)&&a.push("fine-grained-tool-streaming-2025-05-14"),e.reasoning&&!0===s?.thinkingEnabled&&(s.interleavedThinking??!0)&&!0!==e.compat?.forceAdaptiveThinking&&a.push("interleaved-thinking-2025-05-14"),function(e){return(e.compat?.allowedFallbackModels?.length??0)>0}(e)&&a.push("server-side-fallback-2026-07-01"),!0===e.compat?.supportsMidConvoEffort&&a.push("mid-conversation-output-config-2026-07-01","thinking-binding-controls-2026-08-01"),r&&a.push("inline-tools-2026-09-15"),i&&a.push("message-threads-2026-08-12"),[...new Set(a)]}(e,t,r,{isOAuthToken:s,nativeToolChanges:_,messageThreads:o.messageThreads}),S={model:e.id,messages:y?za(b,v):b.messages,max_tokens:r?.maxTokens??e.maxTokens,stream:!0,...k.length>0?{betas:k}:{}};s?(S.system=[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude.",...a?{cache_control:a}:{}}],d&&S.system.push({type:"text",text:A(d),...a?{cache_control:a}:{}})):d&&(S.system=[{type:"text",text:A(d),...a?{cache_control:a}:{}}]),void 0!==r?.temperature&&!r?.thinkingEnabled&&!0!==e.compat?.supportsMidConvoEffort&&l.supportsTemperature&&(S.temperature=r.temperature);const x=l.supportsCacheControlOnTools?a:void 0;if(_)S.tools=[...g(m,x),ma];else{const e=c(t.messages);e.length>0&&(S.tools=g(e,x))}if(w)S.thinking={type:"disabled"};else if(y)S.thinking={type:"adaptive",display:r?.thinkingDisplay??"summarized",block_binding:{prefix_mismatch_behavior:"drop_block"}},S.output_config={effort:"low"};else if(e.reasoning&&r?.thinkingEnabled){const t=r.thinkingDisplay??"summarized";!0===e.compat?.forceAdaptiveThinking?(S.thinking={type:"adaptive",display:t},r.effort&&(S.output_config={effort:r.effort})):S.thinking={type:"enabled",budget_tokens:r.thinkingBudgetTokens||1024,display:t}}if(r?.metadata){const e=r.metadata.user_id;"string"==typeof e&&(S.metadata={user_id:e})}r?.toolChoice&&("string"==typeof r.toolChoice?S.tool_choice={type:r.toolChoice}:S.tool_choice=r.toolChoice);const I=e.compat?.allowedFallbackModels;return I&&I.length>0&&(S.fallbacks=I.map(e=>({model:e.model}))),{params:S,hasPreferredStrictTools:f,providerThinkingLevel:y?v:void 0}}function ja(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function Ua(e,t=e.content){return{type:"tool_result",tool_use_id:e.toolCallId,content:ga(t),is_error:e.isError}}function Da(e,t,s,n=!1,r,i){const o=[],a=/* @__PURE__ */new Map,c=[],l=()=>{o.push(...c),c.length=0};for(let h=0;h<e.length;h++){const s=e[h];if("system"===s.role){const e=f(s),n=[];if(e.length>0&&n.push({type:"text",text:A(e)}),i){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?ua(i.name):i.name}});for(const t of i(e))n.push({type:"tool_addition",tool:{type:"tool_definition",definition:t}})}n.length>0&&c.push({role:"system",content:n})}else if("user"===s.role)if("string"==typeof s.content)s.content.trim().length>0&&o.push({role:"user",content:A(s.content)});else{const e=s.content.map(e=>"text"===e.type?{type:"text",text:A(e.text)}:fa(e)).filter(e=>"text"!==e.type||e.text.trim().length>0);if(0===e.length)continue;o.push({role:"user",content:e})}else if("assistant"===s.role){const e=[];for(const r of s.content)if("text"===r.type){if(0===r.text.trim().length)continue;e.push({type:"text",text:A(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:A(r.thinking),signature:t}):e.push(n?{type:"thinking",thinking:A(r.thinking),signature:""}:{type:"text",text:A(r.thinking)})}else"toolCall"===r.type&&e.push({type:"tool_use",id:r.id,name:t?ua(r.name):r.name,input:r.arguments??{}});if(0===e.length)continue;l();const i=o.length;o.push({role:"assistant",content:e}),void 0!==r&&"anthropic-messages"===s.api&&s.provider===r&&Ha(s.providerThinkingLevel)&&a.set(i,s.providerThinkingLevel)}else if("toolResult"===s.role){const t=[],s=[];let n=h;for(;n<e.length&&"toolResult"===e[n].role;){const r=e[n],i=L(r);t.push(Ua(r,i?.content)),i&&s.push({type:"text",text:i.caption},...i.images.map(fa)),n++}h=n-1,o.push({role:"user",content:[...t,...s]})}}if(l(),s&&o.length>0){const e=o[o.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:o,assistantLevels:a}}function Ha(e){return"low"===e||"medium"===e||"high"===e||"xhigh"===e||"max"===e}function za(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 Fa=/* @__PURE__ */new Set(["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","maxItems","uniqueItems","minContains","maxContains","minProperties","maxProperties"]),Ba=/* @__PURE__ */new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),Ka=(e,t)=>!(!Fa.has(e)&&("minItems"===e?0===t||1===t:"format"!==e||"string"==typeof t&&Ba.has(t)));function Ja(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{ee as n,U as r,Na as stream,qa as streamSimple,la as t};