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