noskills 4.5.1 → 4.5.2
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/chunks/{ajan-bridge-T5M4DPDT.js → ajan-bridge-BNPC757J.js} +1 -1
- package/chunks/{anthropic-TS7EMQML.js → anthropic-ZKOMTKX2.js} +1 -1
- package/chunks/{approve-HEW3VFYH.js → approve-3TKOHYHH.js} +1 -1
- package/chunks/{ask-AXHTCVD6.js → ask-UB26SBWQ.js} +1 -1
- package/chunks/{block-VN76CXZW.js → block-Q4WAIX7X.js} +1 -1
- package/chunks/{cancel-7WRAST62.js → cancel-DY76ADX4.js} +1 -1
- package/chunks/{chunk-4PF2MT7S.js → chunk-34RPTI4K.js} +7 -7
- package/chunks/chunk-3JTDWOAJ.js +2 -0
- package/chunks/{chunk-GQTHILPL.js → chunk-5FX4EBFY.js} +1 -1
- package/chunks/chunk-5OTECUN7.js +1 -0
- package/chunks/{chunk-6YSS6PEL.js → chunk-7PBHRFOZ.js} +1 -1
- package/chunks/{chunk-7GC46XEU.js → chunk-AB3N327V.js} +1 -1
- package/chunks/{chunk-KMLNG3EC.js → chunk-BYPCI5VU.js} +1 -1
- package/chunks/{chunk-QKWJ72HI.js → chunk-CKIZYL4O.js} +1 -1
- package/chunks/{chunk-S4MUTKHT.js → chunk-DYCGJ4RY.js} +1 -1
- package/chunks/{chunk-UE56BMAW.js → chunk-EVJYA7S3.js} +1 -1
- package/chunks/{chunk-LN4NDYT6.js → chunk-FYFUEK4U.js} +1 -1
- package/chunks/chunk-GNMOE7H3.js +48 -0
- package/chunks/chunk-HB62UGZI.js +2 -0
- package/chunks/{chunk-EIMBEXUJ.js → chunk-IM73MYMS.js} +1 -1
- package/chunks/{chunk-KM64FL2X.js → chunk-J25XTDQQ.js} +1 -1
- package/chunks/{chunk-JL3MAFYQ.js → chunk-LGQEWL5X.js} +1 -1
- package/chunks/{chunk-5DZHAHXW.js → chunk-LKZZ4JN5.js} +1 -1
- package/chunks/{chunk-DBKXMYLF.js → chunk-NPWXEWRN.js} +1 -1
- package/chunks/{chunk-PKEQKXZW.js → chunk-ONJVI5AZ.js} +1 -1
- package/chunks/{chunk-EIGFDYGQ.js → chunk-OP4XAIGW.js} +1 -1
- package/chunks/{chunk-W4TQLLUK.js → chunk-T6NZVA6P.js} +1 -1
- package/chunks/{chunk-5PBNUBBY.js → chunk-TCSIXKUD.js} +1 -1
- package/chunks/{chunk-KRKOWSYW.js → chunk-WDKWHGJU.js} +5 -7
- package/chunks/{chunk-PRQ5CRIG.js → chunk-XDPATEP5.js} +1 -1
- package/chunks/{chunk-CML74SNT.js → chunk-Y45DQJSS.js} +1 -1
- package/chunks/{chunk-RAQY37P6.js → chunk-YUTDPPXX.js} +1 -1
- package/chunks/claude-code-OQJIUKZP.js +1 -0
- package/chunks/{concern-QSENGU6C.js → concern-UIGVWDFS.js} +1 -1
- package/chunks/{config-S3UXTJN2.js → config-72Z4PIJN.js} +1 -1
- package/chunks/{decision-ledger-GY2W6VWL.js → decision-ledger-5IPPTRT7.js} +1 -1
- package/chunks/{delegate-WKXIER7E.js → delegate-OV6NY434.js} +1 -1
- package/chunks/{diagrams-A7W2EBYV.js → diagrams-OX4FBDGP.js} +1 -1
- package/chunks/{done-WR3UFYJT.js → done-V54GSSTY.js} +1 -1
- package/chunks/{followup-5EGZEF5Q.js → followup-NL7EPIGF.js} +1 -1
- package/chunks/{free-KJQHRYZA.js → free-KD344KRL.js} +1 -1
- package/chunks/{gemini-IWP24T63.js → gemini-23EOEXSF.js} +1 -1
- package/chunks/{init-437SU6XH.js → init-WDRNFT57.js} +1 -1
- package/chunks/{invoke-hook-LMCWNF65.js → invoke-hook-I3NTD36Q.js} +1 -1
- package/chunks/kiro-TPAAIMY6.js +1 -0
- package/chunks/{learn-ZTYKBZER.js → learn-WBWNJEB2.js} +1 -1
- package/chunks/{ledger-FOOPJ2UO.js → ledger-QYK252DV.js} +1 -1
- package/chunks/{list-HNGIOVBK.js → list-WO6RS7JX.js} +1 -1
- package/chunks/{manager-2MOLEJ4Q.js → manager-ZSPRC5R4.js} +1 -1
- package/chunks/{mod-AJIRKRAH.js → mod-B6LBGYON.js} +1 -1
- package/chunks/{mod-6EZYRKWV.js → mod-MMHDQRNF.js} +1 -1
- package/chunks/{mod-7X5TKHKC.js → mod-RBGAMGZA.js} +1 -1
- package/chunks/{mod-TGOMO3CJ.js → mod-SV4VELMH.js} +1 -1
- package/chunks/{next-Y6FOPM4Z.js → next-QXCLZ7P3.js} +1 -1
- package/chunks/node-2XIHQ2M4.js +1 -0
- package/chunks/node-BXYZKSJY.js +15 -0
- package/chunks/node-DMUOWFGA.js +69 -0
- package/chunks/ollama-MXRDGQDF.js +1 -0
- package/chunks/openai-LE47IWMQ.js +30 -0
- package/chunks/{openai-YES2XJDU.js → openai-MSJF4B6H.js} +1 -1
- package/chunks/opencode-ZDHKR2P6.js +1 -0
- package/chunks/{pack-KUT53Z24.js → pack-NS64WU6M.js} +1 -1
- package/chunks/{plan-export-PG2BVRQZ.js → plan-export-HECAF7D4.js} +1 -1
- package/chunks/{purge-JGNJNEET.js → purge-PSQNN42H.js} +1 -1
- package/chunks/{reopen-RPDXN3CF.js → reopen-L37M5XUI.js} +1 -1
- package/chunks/{reset-RBCQO2RF.js → reset-OOTZXW6Q.js} +1 -1
- package/chunks/{review-VMS5MYOV.js → review-QLD6WSOB.js} +1 -1
- package/chunks/{rule-IB4VKSBC.js → rule-OOANQBHB.js} +1 -1
- package/chunks/{run-62PWXVII.js → run-YHCIRY7Z.js} +1 -1
- package/chunks/{sdk-FR7Z4YSC.js → sdk-OQIHH3OY.js} +1 -1
- package/chunks/{session-Q43KMFL2.js → session-OWWDH7KA.js} +1 -1
- package/chunks/{spec-4RKLPOEM.js → spec-O7F525UN.js} +1 -1
- package/chunks/{status-OGLFEFF7.js → status-SZZXY7V3.js} +1 -1
- package/chunks/{sync-H35O5DN5.js → sync-3RYRGTEA.js} +1 -1
- package/chunks/{validate-JX7UTAK5.js → validate-UZD6JBSG.js} +1 -1
- package/chunks/{vertexai-WF5CKMYI.js → vertexai-CVCRCO24.js} +1 -1
- package/chunks/{watch-SOZDHLSC.js → watch-5DNM646U.js} +1 -1
- package/chunks/{web-3VGRM3W4.js → web-662LNB3K.js} +1 -1
- package/chunks/{wontfix-RBOGLLWJ.js → wontfix-UDCTLHNB.js} +1 -1
- package/noskills.js +1 -1
- package/package.json +1 -1
- package/chunks/chunk-3ZJ3UGQL.js +0 -48
- package/chunks/chunk-575Y3OEG.js +0 -1
- package/chunks/chunk-IGDFEGCH.js +0 -2
- package/chunks/claude-code-DIWRQKZA.js +0 -1
- package/chunks/kiro-THWCXS5L.js +0 -1
- package/chunks/node-AZK2C657.js +0 -12
- package/chunks/node-GQQ42DT2.js +0 -68
- package/chunks/ollama-2KAMCXVL.js +0 -1
- package/chunks/openai-HHE35TAX.js +0 -31
- package/chunks/opencode-S4M7WJTO.js +0 -1
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import{c as Br,e as _a}from"./chunk-HISXAZ4Y.js";var bo=Br(ee=>{"use strict";var nc=ee&&ee.__extends||(function(){var r=function(s,e){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var i in n)n.hasOwnProperty(i)&&(t[i]=n[i])},r(s,e)};return function(s,e){r(s,e);function t(){this.constructor=s}s.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}})();Object.defineProperty(ee,"__esModule",{value:!0});var W=256,Ds=(function(){function r(s){s===void 0&&(s="="),this._paddingCharacter=s}return r.prototype.encodedLength=function(s){return this._paddingCharacter?(s+2)/3*4|0:(s*8+5)/6|0},r.prototype.encode=function(s){for(var e="",t=0;t<s.length-2;t+=3){var n=s[t]<<16|s[t+1]<<8|s[t+2];e+=this._encodeByte(n>>>18&63),e+=this._encodeByte(n>>>12&63),e+=this._encodeByte(n>>>6&63),e+=this._encodeByte(n>>>0&63)}var i=s.length-t;if(i>0){var n=s[t]<<16|(i===2?s[t+1]<<8:0);e+=this._encodeByte(n>>>18&63),e+=this._encodeByte(n>>>12&63),i===2?e+=this._encodeByte(n>>>6&63):e+=this._paddingCharacter||"",e+=this._paddingCharacter||""}return e},r.prototype.maxDecodedLength=function(s){return this._paddingCharacter?s/4*3|0:(s*6+7)/8|0},r.prototype.decodedLength=function(s){return this.maxDecodedLength(s.length-this._getPaddingLength(s))},r.prototype.decode=function(s){if(s.length===0)return new Uint8Array(0);for(var e=this._getPaddingLength(s),t=s.length-e,n=new Uint8Array(this.maxDecodedLength(t)),i=0,o=0,c=0,u=0,d=0,m=0,p=0;o<t-4;o+=4)u=this._decodeChar(s.charCodeAt(o+0)),d=this._decodeChar(s.charCodeAt(o+1)),m=this._decodeChar(s.charCodeAt(o+2)),p=this._decodeChar(s.charCodeAt(o+3)),n[i++]=u<<2|d>>>4,n[i++]=d<<4|m>>>2,n[i++]=m<<6|p,c|=u&W,c|=d&W,c|=m&W,c|=p&W;if(o<t-1&&(u=this._decodeChar(s.charCodeAt(o)),d=this._decodeChar(s.charCodeAt(o+1)),n[i++]=u<<2|d>>>4,c|=u&W,c|=d&W),o<t-2&&(m=this._decodeChar(s.charCodeAt(o+2)),n[i++]=d<<4|m>>>2,c|=m&W),o<t-3&&(p=this._decodeChar(s.charCodeAt(o+3)),n[i++]=m<<6|p,c|=p&W),c!==0)throw new Error("Base64Coder: incorrect characters for decoding");return n},r.prototype._encodeByte=function(s){var e=s;return e+=65,e+=25-s>>>8&6,e+=51-s>>>8&-75,e+=61-s>>>8&-15,e+=62-s>>>8&3,String.fromCharCode(e)},r.prototype._decodeChar=function(s){var e=W;return e+=(42-s&s-44)>>>8&-W+s-43+62,e+=(46-s&s-48)>>>8&-W+s-47+63,e+=(47-s&s-58)>>>8&-W+s-48+52,e+=(64-s&s-91)>>>8&-W+s-65+0,e+=(96-s&s-123)>>>8&-W+s-97+26,e},r.prototype._getPaddingLength=function(s){var e=0;if(this._paddingCharacter){for(var t=s.length-1;t>=0&&s[t]===this._paddingCharacter;t--)e++;if(s.length<4||e>2)throw new Error("Base64Coder: incorrect padding")}return e},r})();ee.Coder=Ds;var ur=new Ds;function sc(r){return ur.encode(r)}ee.encode=sc;function ic(r){return ur.decode(r)}ee.decode=ic;var go=(function(r){nc(s,r);function s(){return r!==null&&r.apply(this,arguments)||this}return 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&-13,t+=62-e>>>8&49,String.fromCharCode(t)},s.prototype._decodeChar=function(e){var t=W;return t+=(44-e&e-46)>>>8&-W+e-45+62,t+=(94-e&e-96)>>>8&-W+e-95+63,t+=(47-e&e-58)>>>8&-W+e-48+52,t+=(64-e&e-91)>>>8&-W+e-65+0,t+=(96-e&e-123)>>>8&-W+e-97+26,t},s})(Ds);ee.URLSafeCoder=go;var wo=new go;function oc(r){return wo.encode(r)}ee.encodeURLSafe=oc;function ac(r){return wo.decode(r)}ee.decodeURLSafe=ac;ee.encodedLength=function(r){return ur.encodedLength(r)};ee.maxDecodedLength=function(r){return ur.maxDecodedLength(r)};ee.decodedLength=function(r){return ur.decodedLength(r)}});var ko=Br((yo,fn)=>{(function(r,s){var e={};s(e);var t=e.default;for(var n in e)t[n]=e[n];typeof fn=="object"&&typeof fn.exports=="object"?fn.exports=t:typeof define=="function"&&define.amd?define(function(){return t}):r.sha256=t})(yo,function(r){"use strict";r.__esModule=!0,r.digestLength=32,r.blockSize=64;var s=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 e(p,f,w,_,v){for(var A,E,y,I,x,R,P,T,O,L,$,j,he;v>=64;){for(A=f[0],E=f[1],y=f[2],I=f[3],x=f[4],R=f[5],P=f[6],T=f[7],L=0;L<16;L++)$=_+L*4,p[L]=(w[$]&255)<<24|(w[$+1]&255)<<16|(w[$+2]&255)<<8|w[$+3]&255;for(L=16;L<64;L++)O=p[L-2],j=(O>>>17|O<<15)^(O>>>19|O<<13)^O>>>10,O=p[L-15],he=(O>>>7|O<<25)^(O>>>18|O<<14)^O>>>3,p[L]=(j+p[L-7]|0)+(he+p[L-16]|0);for(L=0;L<64;L++)j=(((x>>>6|x<<26)^(x>>>11|x<<21)^(x>>>25|x<<7))+(x&R^~x&P)|0)+(T+(s[L]+p[L]|0)|0)|0,he=((A>>>2|A<<30)^(A>>>13|A<<19)^(A>>>22|A<<10))+(A&E^A&y^E&y)|0,T=P,P=R,R=x,x=I+j|0,I=y,y=E,E=A,A=j+he|0;f[0]+=A,f[1]+=E,f[2]+=y,f[3]+=I,f[4]+=x,f[5]+=R,f[6]+=P,f[7]+=T,_+=64,v-=64}return _}var t=(function(){function p(){this.digestLength=r.digestLength,this.blockSize=r.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return p.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},p.prototype.clean=function(){for(var f=0;f<this.buffer.length;f++)this.buffer[f]=0;for(var f=0;f<this.temp.length;f++)this.temp[f]=0;this.reset()},p.prototype.update=function(f,w){if(w===void 0&&(w=f.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");var _=0;if(this.bytesHashed+=w,this.bufferLength>0){for(;this.bufferLength<64&&w>0;)this.buffer[this.bufferLength++]=f[_++],w--;this.bufferLength===64&&(e(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(w>=64&&(_=e(this.temp,this.state,f,_,w),w%=64);w>0;)this.buffer[this.bufferLength++]=f[_++],w--;return this},p.prototype.finish=function(f){if(!this.finished){var w=this.bytesHashed,_=this.bufferLength,v=w/536870912|0,A=w<<3,E=w%64<56?64:128;this.buffer[_]=128;for(var y=_+1;y<E-8;y++)this.buffer[y]=0;this.buffer[E-8]=v>>>24&255,this.buffer[E-7]=v>>>16&255,this.buffer[E-6]=v>>>8&255,this.buffer[E-5]=v>>>0&255,this.buffer[E-4]=A>>>24&255,this.buffer[E-3]=A>>>16&255,this.buffer[E-2]=A>>>8&255,this.buffer[E-1]=A>>>0&255,e(this.temp,this.state,this.buffer,0,E),this.finished=!0}for(var y=0;y<8;y++)f[y*4+0]=this.state[y]>>>24&255,f[y*4+1]=this.state[y]>>>16&255,f[y*4+2]=this.state[y]>>>8&255,f[y*4+3]=this.state[y]>>>0&255;return this},p.prototype.digest=function(){var f=new Uint8Array(this.digestLength);return this.finish(f),f},p.prototype._saveState=function(f){for(var w=0;w<this.state.length;w++)f[w]=this.state[w]},p.prototype._restoreState=function(f,w){for(var _=0;_<this.state.length;_++)this.state[_]=f[_];this.bytesHashed=w,this.finished=!1,this.bufferLength=0},p})();r.Hash=t;var n=(function(){function p(f){this.inner=new t,this.outer=new t,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var w=new Uint8Array(this.blockSize);if(f.length>this.blockSize)new t().update(f).finish(w).clean();else for(var _=0;_<f.length;_++)w[_]=f[_];for(var _=0;_<w.length;_++)w[_]^=54;this.inner.update(w);for(var _=0;_<w.length;_++)w[_]^=106;this.outer.update(w),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate);for(var _=0;_<w.length;_++)w[_]=0}return p.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},p.prototype.clean=function(){for(var f=0;f<this.istate.length;f++)this.ostate[f]=this.istate[f]=0;this.inner.clean(),this.outer.clean()},p.prototype.update=function(f){return this.inner.update(f),this},p.prototype.finish=function(f){return this.outer.finished?this.outer.finish(f):(this.inner.finish(f),this.outer.update(f,this.digestLength).finish(f)),this},p.prototype.digest=function(){var f=new Uint8Array(this.digestLength);return this.finish(f),f},p})();r.HMAC=n;function i(p){var f=new t().update(p),w=f.digest();return f.clean(),w}r.hash=i,r.default=i;function o(p,f){var w=new n(p).update(f),_=w.digest();return w.clean(),_}r.hmac=o;function c(p,f,w,_){var v=_[0];if(v===0)throw new Error("hkdf: cannot expand more");f.reset(),v>1&&f.update(p),w&&f.update(w),f.update(_),f.finish(p),_[0]++}var u=new Uint8Array(r.digestLength);function d(p,f,w,_){f===void 0&&(f=u),_===void 0&&(_=32);for(var v=new Uint8Array([1]),A=o(f,p),E=new n(A),y=new Uint8Array(E.digestLength),I=y.length,x=new Uint8Array(_),R=0;R<_;R++)I===y.length&&(c(y,E,w,v),I=0),x[R]=y[I++];return E.clean(),y.fill(0),v.fill(0),x}r.hkdf=d;function m(p,f,w,_){for(var v=new n(p),A=v.digestLength,E=new Uint8Array(4),y=new Uint8Array(A),I=new Uint8Array(A),x=new Uint8Array(_),R=0;R*A<_;R++){var P=R+1;E[0]=P>>>24&255,E[1]=P>>>16&255,E[2]=P>>>8&255,E[3]=P>>>0&255,v.reset(),v.update(f),v.update(E),v.finish(I);for(var T=0;T<A;T++)y[T]=I[T];for(var T=2;T<=w;T++){v.reset(),v.update(I).finish(I);for(var O=0;O<A;O++)y[O]^=I[O]}for(var T=0;T<A&&R*A+T<_;T++)x[R*A+T]=y[T]}for(var R=0;R<A;R++)y[R]=I[R]=0;for(var R=0;R<4;R++)E[R]=0;return v.clean(),x}r.pbkdf2=m})});var xo=Br(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});Bs.timingSafeEqual=cc;function So(r,s=""){if(!r)throw new Error(s)}function cc(r,s){if(r.byteLength!==s.byteLength)return!1;r instanceof DataView||(r=new DataView(ArrayBuffer.isView(r)?r.buffer:r)),s instanceof DataView||(s=new DataView(ArrayBuffer.isView(s)?s.buffer:s)),So(r instanceof DataView),So(s instanceof DataView);let e=r.byteLength,t=0,n=-1;for(;++n<e;)t|=r.getUint8(n)^s.getUint8(n);return t===0}});var Eo=Br(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.Webhook=ct.WebhookVerificationError=void 0;var vo=bo(),lc=ko(),dc=xo(),Ao=300,Ws=class r extends Error{constructor(s){super(s),Object.setPrototypeOf(this,r.prototype),this.name="ExtendableError",this.stack=new Error(s).stack}},xe=class r extends Ws{constructor(s){super(s),Object.setPrototypeOf(this,r.prototype),this.name="WebhookVerificationError"}};ct.WebhookVerificationError=xe;var pn=class r{constructor(s,e){if(e?.format==="raw")s instanceof Uint8Array?this.key=s:this.key=Uint8Array.from(s,t=>t.charCodeAt(0));else{if(typeof s!="string")throw new Error("Expected secret to be of type string");s.startsWith(r.prefix)&&(s=s.substring(r.prefix.length)),this.key=vo.decode(s)}if(this.key.length===0)throw new Error("Secret can't be empty.")}verify(s,e,t){var n;let i=(n=t?.jsonParse)!==null&&n!==void 0?n:!0,o={};for(let v of Object.keys(e))o[v.toLowerCase()]=e[v];let c=o["webhook-id"],u=o["webhook-signature"],d=o["webhook-timestamp"];if(!u||!c||!d)throw new xe("Missing required headers");let m=this.verifyTimestamp(d),f=this.sign(c,m,s).split(",")[1],w=u.split(" "),_=new globalThis.TextEncoder;for(let v of w){let[A,E]=v.split(",");if(A==="v1"&&(0,dc.timingSafeEqual)(_.encode(E),_.encode(f))){let y=s.toString();return y===""?void 0:i?JSON.parse(y):void 0}}throw new xe("No matching signature found")}sign(s,e,t){if(typeof t!="string")if(t.constructor.name==="Buffer")t=t.toString();else throw new Error("Expected payload to be of type string or Buffer.");let n=new TextEncoder,i=Math.floor(e.getTime()/1e3),o=n.encode(`${s}.${i}.${t}`);return`v1,${vo.encode(lc.hmac(this.key,o))}`}verifyTimestamp(s){let e=Math.floor(Date.now()/1e3),t=parseInt(s,10);if(Number.isNaN(t))throw new xe("Invalid Signature Headers");if(e-t>Ao)throw new xe("Message timestamp too old");if(t>e+Ao)throw new xe("Message timestamp too new");return new Date(t*1e3)}};ct.Webhook=pn;pn.prefix="whsec_"});function g(r,s,e,t,n){if(t==="m")throw new TypeError("Private method is not writable");if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof s=="function"?r!==s||!n:!s.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t==="a"?n.call(r,e):n?n.value=e:s.set(r,e),e}function a(r,s,e,t){if(e==="a"&&!t)throw new TypeError("Private accessor was defined without a getter");if(typeof s=="function"?r!==s||!t:!s.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?t:e==="a"?t.call(r):t?t.value:s.get(r)}function G(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var Ce=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{let s=Object.prototype.toString.call(r);if(s==="[object Error]"||s==="[object DOMException]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};var k=(()=>{class r extends Error{}return r})(),F=class r extends k{constructor(s,e,t,n,i){super(`${r.makeMessage(s,e,t)}`),this.status=s,this.headers=n,this.requestID=n?.get("request-id"),this.workspaceID=n?.get("anthropic-workspace-id"),this.error=e,this.type=i??null}static makeMessage(s,e,t){let n=e?.message?typeof e.message=="string"?e.message:JSON.stringify(e.message):e?JSON.stringify(e):t;return s&&n?`${s} ${n}`:s?`${s} status code (no body)`:n||"(no status code or body)"}static generate(s,e,t,n){if(!s||!n)return new fe({message:t,cause:Ce(e)});let i=e,o=i?.error?.type;return s===400?new Ve(s,i,t,n,o):s===401?new Je(s,i,t,n,o):s===403?new Ye(s,i,t,n,o):s===404?new Xe(s,i,t,n,o):s===409?new Ge(s,i,t,n,o):s===422?new Qe(s,i,t,n,o):s===429?new Ze(s,i,t,n,o):s>=500?new et(s,i,t,n,o):new r(s,i,t,n,o)}},z=class extends F{constructor({message:s}={}){super(void 0,void 0,s||"Request was aborted.",void 0)}},fe=class extends F{constructor({message:s,cause:e}){super(void 0,void 0,s||"Connection error.",void 0),e&&(this.cause=e)}},Ke=class extends fe{constructor({message:s}={}){super({message:s??"Request timed out."})}},Yt=class extends k{constructor(s,{cause:e}={}){super(s??"Retryable error."),e!==void 0&&(this.cause=e)}},Ve=class extends F{},Je=class extends F{},Ye=class extends F{},Xe=class extends F{},Ge=class extends F{},Qe=class extends F{},Ze=class extends F{},et=class extends F{};var wa=/^[a-z][a-z0-9+.-]*:/i,wi=r=>wa.test(r),V=r=>(V=Array.isArray,V(r)),hs=V;function Xt(r){return typeof r!="object"?{}:r??{}}function fs(r){if(!r)return!0;for(let s in r)return!1;return!0}function bi(r,s){return Object.prototype.hasOwnProperty.call(r,s)}function ps(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}var Wr=(r,s)=>{if(typeof s!="number"||!Number.isInteger(s))throw new k(`${r} must be an integer`);if(s<0)throw new k(`${r} must be a positive integer`);return s};var $e=r=>{try{return JSON.parse(r)}catch{return}};var le=(r,s)=>new Promise(e=>{if(s?.aborted)return e();let t=()=>{clearTimeout(n),e()},n=setTimeout(()=>{s?.removeEventListener("abort",t),e()},r);s?.addEventListener("abort",t,{once:!0})});var ne="0.126.0";var xi=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function ba(){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 ya=()=>{let r=ba();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ne,"X-Stainless-OS":ki(Deno.build.os),"X-Stainless-Arch":yi(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":ne,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process?.version??"unknown"};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ne,"X-Stainless-OS":ki(globalThis.process.platform??"unknown"),"X-Stainless-Arch":yi(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let s=ka();return s?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ne,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${s.browser}`,"X-Stainless-Runtime-Version":s.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ne,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ka(){if(typeof navigator>"u"||!navigator)return null;let r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:s,pattern:e}of r){let t=e.exec(navigator.userAgent);if(t){let n=t[1]||0,i=t[2]||0,o=t[3]||0;return{browser:s,version:`${n}.${i}.${o}`}}}return null}var yi=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",ki=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),Si,Gt=()=>Si??(Si=ya());var Ur=new WeakMap,vi=typeof globalThis.FinalizationRegistry=="function"?new globalThis.FinalizationRegistry(r=>pe(r)):null;function Sa(r,s){return()=>r.removeEventListener("abort",s)}function Ai(r,s,e){Ur.set(r,Sa(s,e))}function Ei(r,s){Ur.has(s)&&vi?.register(r,s,s)}function pe(r){let s=Ur.get(r);s&&(Ur.delete(r),vi?.unregister(r),s())}function Ri(){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 ms(...r){let s=globalThis.ReadableStream;if(typeof s>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new s(...r)}function qr(r){let s=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return ms({start(){},async pull(e){let{done:t,value:n}=await s.next();t?e.close():e.enqueue(n)},async cancel(){await s.return?.()}})}function Qt(r){if(r[Symbol.asyncIterator])return r;let s=r.getReader();return{async next(){try{let e=await s.read();return e?.done&&s.releaseLock(),e}catch(e){throw s.releaseLock(),e}},async return(){let e=s.cancel();return s.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Ii(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let s=r.getReader(),e=s.cancel();s.releaseLock(),await e}var jr=class{},Pi=({headers:r,body:s})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(s)});var _s="RFC3986",gs=r=>String(r),ws={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:gs},Ti="RFC1738";var zr=(r,s)=>(zr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),zr(r,s)),me=(()=>{let r=[];for(let s=0;s<256;++s)r.push("%"+((s<16?"0":"")+s.toString(16)).toUpperCase());return r})();var bs=1024,Mi=(r,s,e,t,n)=>{if(r.length===0)return r;let i=r;if(typeof r=="symbol"?i=Symbol.prototype.toString.call(r):typeof r!="string"&&(i=String(r)),e==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,function(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let o="";for(let c=0;c<i.length;c+=bs){let u=i.length>=bs?i.slice(c,c+bs):i,d=[];for(let m=0;m<u.length;++m){let p=u.charCodeAt(m);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||n===Ti&&(p===40||p===41)){d[d.length]=u.charAt(m);continue}if(p<128){d[d.length]=me[p];continue}if(p<2048){d[d.length]=me[192|p>>6]+me[128|p&63];continue}if(p<55296||p>=57344){d[d.length]=me[224|p>>12]+me[128|p>>6&63]+me[128|p&63];continue}m+=1,p=65536+((p&1023)<<10|u.charCodeAt(m)&1023),d[d.length]=me[240|p>>18]+me[128|p>>12&63]+me[128|p>>6&63]+me[128|p&63]}o+=d.join("")}return o};function Oi(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function ys(r,s){if(V(r)){let e=[];for(let t=0;t<r.length;t+=1)e.push(s(r[t]));return e}return s(r)}var $i={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,s){return String(r)+"["+s+"]"},repeat(r){return String(r)}},Ni=function(r,s){Array.prototype.push.apply(r,V(s)?s:[s])},Ci,q={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Mi,encodeValuesOnly:!1,format:_s,formatter:gs,indices:!1,serializeDate(r){return(Ci??(Ci=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function Aa(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var ks={};function Li(r,s,e,t,n,i,o,c,u,d,m,p,f,w,_,v,A,E){let y=r,I=E,x=0,R=!1;for(;(I=I.get(ks))!==void 0&&!R;){let $=I.get(r);if(x+=1,typeof $<"u"){if($===x)throw new RangeError("Cyclic object value");R=!0}typeof I.get(ks)>"u"&&(x=0)}if(typeof d=="function"?y=d(s,y):y instanceof Date?y=f?.(y):e==="comma"&&V(y)&&(y=ys(y,function($){return $ instanceof Date?f?.($):$})),y===null){if(i)return u&&!v?u(s,q.encoder,A,"key",w):s;y=""}if(Aa(y)||Oi(y)){if(u){let $=v?s:u(s,q.encoder,A,"key",w);return[_?.($)+"="+_?.(u(y,q.encoder,A,"value",w))]}return[_?.(s)+"="+_?.(String(y))]}let P=[];if(typeof y>"u")return P;let T;if(e==="comma"&&V(y))v&&u&&(y=ys(y,u)),T=[{value:y.length>0?y.join(",")||null:void 0}];else if(V(d))T=d;else{let $=Object.keys(y);T=m?$.sort(m):$}let O=c?String(s).replace(/\./g,"%2E"):String(s),L=t&&V(y)&&y.length===1?O+"[]":O;if(n&&V(y)&&y.length===0)return L+"[]";for(let $=0;$<T.length;++$){let j=T[$],he=typeof j=="object"&&typeof j.value<"u"?j.value:y[j];if(o&&he===null)continue;let Oe=p&&c?j.replace(/\./g,"%2E"):j,ze=V(y)?typeof e=="function"?e(L,Oe):L:L+(p?"."+Oe:"["+Oe+"]");E.set(r,x);let gi=new WeakMap;gi.set(ks,E),Ni(P,Li(he,ze,e,t,n,i,o,c,e==="comma"&&v&&V(y)?null:u,d,m,p,f,w,_,v,A,gi))}return P}function Ea(r=q){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let s=r.charset||q.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let e=_s;if(typeof r.format<"u"){if(!zr(ws,r.format))throw new TypeError("Unknown format option provided.");e=r.format}let t=ws[e],n=q.filter;(typeof r.filter=="function"||V(r.filter))&&(n=r.filter);let i;if(r.arrayFormat&&r.arrayFormat in $i?i=r.arrayFormat:"indices"in r?i=r.indices?"indices":"repeat":i=q.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let o=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:q.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:q.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:q.allowEmptyArrays,arrayFormat:i,charset:s,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:q.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?q.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:q.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:q.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:q.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:q.encodeValuesOnly,filter:n,format:e,formatter:t,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:q.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:q.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:q.strictNullHandling}}function Fi(r,s={}){let e=r,t=Ea(s),n,i;typeof t.filter=="function"?(i=t.filter,e=i("",e)):V(t.filter)&&(i=t.filter,n=i);let o=[];if(typeof e!="object"||e===null)return"";let c=$i[t.arrayFormat],u=c==="comma"&&t.commaRoundTrip;n||(n=Object.keys(e)),t.sort&&n.sort(t.sort);let d=new WeakMap;for(let f=0;f<n.length;++f){let w=n[f];t.skipNulls&&e[w]===null||Ni(o,Li(e[w],w,c,u,t.allowEmptyArrays,t.strictNullHandling,t.skipNulls,t.encodeDotInKeys,t.encode?t.encoder:null,t.filter,t.sort,t.allowDots,t.serializeDate,t.format,t.formatter,t.encodeValuesOnly,t.charset,d))}let m=o.join(t.delimiter),p=t.addQueryPrefix===!0?"?":"";return t.charsetSentinel&&(t.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),m.length>0?p+m:""}function Hi(r){return Fi(r,{arrayFormat:"brackets"})}var Bi="urn:ietf:params:oauth:grant-type:jwt-bearer",Wi="refresh_token",Kr="/v1/oauth/token",Ne="oauth-2025-04-20",Ui="oidc-federation-2026-04-01",qi=120,tt=30,ji=5,Di=1<<20;function Vr(r){if(!r)return;let s;try{s=new URL(r)}catch(t){throw new N(`Invalid token endpoint base URL "${r}": ${t}`)}if(s.protocol==="https:")return;let e=s.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!(s.protocol==="http:"&&(e==="localhost"||e==="127.0.0.1"||e==="::1")))throw new N(`Refusing to send credential over non-https token endpoint "${r}"`)}async function Jr(r,s){let e=await Pa(r),t;try{t=JSON.parse(e)}catch{throw new N(`Token endpoint returned non-JSON response (status ${r.status})`,r.status,J(e),s)}if(!t.access_token)throw new N(`Token endpoint response missing access_token: ${JSON.stringify(J(t))}`,r.status,J(t),s);if(t.token_type&&t.token_type.toLowerCase()!=="bearer")throw new N(`Token endpoint response: unsupported token_type "${t.token_type}" (want Bearer)`,r.status,J(t),s);return t}var Ss=2e3,Ia=new Set(["error","error_description","error_uri"]);function J(r){if(r==null)return r;if(typeof r=="string"){let s;try{s=JSON.parse(r)}catch{return r.length<=Ss?r:r.slice(0,Ss)+`... <${r.length-Ss} more chars>`}return JSON.stringify(J(s))}if(typeof r=="object"&&!Array.isArray(r)){let s={};for(let[e,t]of Object.entries(r))Ia.has(e)&&(s[e]=t);return s}return null}async function Yr(r,s=e=>console.warn(`anthropic-sdk: ${e}`)){if(typeof process>"u"||process.platform==="win32")return;let{fs:e}=await import("./node-2XIHQ2M4.js"),t=r,n;try{t=await e.promises.realpath(r),n=await e.promises.stat(t)}catch{return}let i=n.mode&511;if(i&18)throw new N(`Credentials file at ${t} is group/world-writable (mode 0o${i.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${t}\`.`);if(i&36)throw new N(`Credentials file at ${t} is group/world-readable (mode 0o${i.toString(8)}); run \`chmod 600 ${t}\` before retrying.`);typeof process.getuid=="function"&&n.uid!==process.getuid()&&s(`credentials file at ${t} is owned by uid ${n.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function Xr(r,s){let{fs:e,path:t}=await import("./node-2XIHQ2M4.js"),n=t.dirname(r);await e.promises.mkdir(n,{recursive:!0,mode:448});let i=`${r}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{let o=await e.promises.open(i,"w",384);try{await o.writeFile(JSON.stringify(s,null,2)),await o.sync()}finally{await o.close()}await e.promises.rename(i,r)}catch(o){throw await e.promises.unlink(i).catch(()=>{}),o}try{let o=await e.promises.open(n,"r");try{await o.sync()}finally{await o.close()}}catch{}}async function Pa(r){if(!r.body)return"";let s=r.body.getReader(),e=[],t=0;for(;;){let{done:i,value:o}=await s.read();if(i)break;if(t+o.length>Di){let c=Di-t;c>0&&e.push(o.subarray(0,c)),await s.cancel();break}e.push(o),t+=o.length}let n;if(e.length===1)n=e[0];else{n=new Uint8Array(e.reduce((o,c)=>o+c.length,0));let i=0;for(let o of e)n.set(o,i),i+=o.length}return new TextDecoder("utf-8").decode(n)}var N=class extends k{constructor(s,e=null,t=null,n=null){super(s),this.statusCode=e,this.body=t,this.requestId=n}};function de(){return Math.floor(Date.now()/1e3)}var Gr=class{constructor(s,e){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=s,this.onAdvisoryRefreshError=e}async getToken(){let s=this.nextForce;this.nextForce=!1;let e=this.cached;if(s||e==null)return(await this.refresh(s)).token;if(e.expiresAt==null)return e.token;let t=e.expiresAt-de();return t>qi?e.token:t>tt?(this.backgroundRefresh(),e.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(s=!1){return this.pendingRefresh&&!s?this.pendingRefresh:this.doRefresh(s)}backgroundRefresh(){this.pendingRefresh||de()-this.lastAdvisoryError<ji||this.doRefresh().catch(s=>{this.lastAdvisoryError=de(),this.onAdvisoryRefreshError?.(s)})}doRefresh(s=!1){return this.pendingRefresh=this.provider(s?{forceRefresh:!0}:void 0).then(e=>(this.cached=e,this.pendingRefresh=null,e),e=>{throw this.pendingRefresh=null,e}),this.pendingRefresh}};var M=r=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()||void 0};function Vi(r){let s=0;for(let n of r)s+=n.length;let e=new Uint8Array(s),t=0;for(let n of r)e.set(n,t),t+=n.length;return e}var zi;function Zt(r){let s;return(zi??(s=new globalThis.TextEncoder,zi=s.encode.bind(s)))(r)}var Ki;function er(r){let s;return(Ki??(s=new globalThis.TextDecoder,Ki=s.decode.bind(s)))(r)}var Ji=r=>{if(typeof globalThis.Buffer<"u"){let s=globalThis.Buffer.from(r,"base64");return new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}if(typeof atob<"u"){let s=atob(r),e=new Uint8Array(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}throw new k("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")};var rr="warn",Zr={off:0,error:200,warn:300,info:400,debug:500},en=(r,s,e)=>{if(r){if(bi(Zr,r))return r;e.warn(`${s} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(Zr))}`)}};function tr(){}function Qr(r,s,e){return!s||Zr[r]>Zr[e]?tr:s[r].bind(s)}var Ta={error:tr,warn:tr,info:tr,debug:tr},Yi=new WeakMap;function vs(r,s){let e=Yi.get(r);if(e&&e[0]===s)return e[1];let t={error:Qr("error",r,s),warn:Qr("warn",r,s),info:Qr("info",r,s),debug:Qr("debug",r,s)};return Yi.set(r,[s,t]),t}function C(r){let s=r.logger,e=r.logLevel??"off";return s?vs(s,e):Ta}var Xi,xs;function Gi(){let r=M("ANTHROPIC_LOG");return(!xs||r!==Xi)&&(Xi=r,xs=vs(console,en(r,"process.env['ANTHROPIC_LOG']",vs(console,rr))??rr)),xs}var _e=r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([s,e])=>[s,s.toLowerCase()==="authorization"||s.toLowerCase()==="api-key"||s.toLowerCase()==="x-api-key"||s.toLowerCase()==="cookie"||s.toLowerCase()==="set-cookie"?"***":e]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r);var tn=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return tn=r.randomUUID.bind(r),r.randomUUID();let s=new Uint8Array(1),e=r?()=>r.getRandomValues(s)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,t=>(+t^e()&15>>+t/4).toString(16))};var rn="1.0",Ma=/^[A-Za-z0-9_.-]+$/;function Qi(r){if(!r)throw new Error("profile name is empty");if(r==="."||r==="..")throw new Error(`profile name "${r}" is not allowed`);if(r.includes("/")||r.includes("\\"))throw new Error(`profile name "${r}" must not contain path separators`);if(!Ma.test(r))throw new Error(`profile name "${r}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var Zi=async r=>{var s,e;let t=await As();if(t===null)return null;let n=r??await to();if(n===null)return null;Qi(n);let{fs:i,path:o}=await import("./node-2XIHQ2M4.js"),c=o.join(t,"configs",`${n}.json`),u;try{u=await i.promises.readFile(c,"utf-8")}catch(p){if(p?.code!=="ENOENT")throw new Error(`failed to read config file ${c}: ${p}`);u=null}if(u===null){let p=M("ANTHROPIC_ORGANIZATION_ID"),f=M("ANTHROPIC_IDENTITY_TOKEN_FILE"),w=M("ANTHROPIC_FEDERATION_RULE_ID");return w&&p?{fromFile:!1,config:{organization_id:p,workspace_id:M("ANTHROPIC_WORKSPACE_ID"),base_url:M("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:w,service_account_id:M("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:f?{source:"file",path:f}:void 0,scope:M("ANTHROPIC_SCOPE")}}}:null}let d;try{d=JSON.parse(u)}catch(p){throw new Error(`failed to parse config file ${c}: ${p}`)}if(!d.authentication)throw new Error(`config file ${c} is missing "authentication"`);let m=d.authentication.type;if(m!=="oidc_federation"&&m!=="user_oauth")throw new Error(`authentication.type "${m}" is not a known authentication type`);if(d.organization_id??(d.organization_id=M("ANTHROPIC_ORGANIZATION_ID")),d.workspace_id??(d.workspace_id=M("ANTHROPIC_WORKSPACE_ID")),d.base_url??(d.base_url=M("ANTHROPIC_BASE_URL")),(s=d.authentication).scope??(s.scope=M("ANTHROPIC_SCOPE")),d.authentication.type==="oidc_federation"){if(!d.authentication.identity_token){let p=M("ANTHROPIC_IDENTITY_TOKEN_FILE");p&&(d.authentication.identity_token={source:"file",path:p})}d.authentication.federation_rule_id||(d.authentication.federation_rule_id=M("ANTHROPIC_FEDERATION_RULE_ID")??""),(e=d.authentication).service_account_id??(e.service_account_id=M("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:d,fromFile:!0}};var eo=async(r,s)=>{if(r?.authentication.credentials_path)return r.authentication.credentials_path;let e=await As();if(!e)return null;let t=s??await to();if(!t)return null;Qi(t);let{path:n}=await import("./node-2XIHQ2M4.js");return n.join(e,"credentials",`${t}.json`)},As=async()=>{if(!Oa())return null;let{path:r}=await import("./node-2XIHQ2M4.js"),s=M("ANTHROPIC_CONFIG_DIR");if(s)return s;if(Gt()["X-Stainless-OS"]==="Windows"){let i=M("APPDATA");if(i)return r.join(i,"Anthropic");let o=M("USERPROFILE");return o?r.join(o,"AppData","Roaming","Anthropic"):null}let t=M("XDG_CONFIG_HOME");if(t)return r.join(t,"anthropic");let n=M("HOME");return n?r.join(n,".config","anthropic"):null},Oa=()=>{let r=Gt()["X-Stainless-Runtime"];return r==="node"||r==="deno"},to=async()=>{let r=await As();if(!r)return null;let s=M("ANTHROPIC_PROFILE");if(s)return s;let{fs:e,path:t}=await import("./node-2XIHQ2M4.js"),n=t.join(r,"active_config");try{return(await e.promises.readFile(n,"utf-8")).trim()||"default"}catch(i){if(i?.code!=="ENOENT")throw new Error(`failed to read ${n}: ${i}`);return"default"}};function Es(r){if(!r)throw new k("Identity token file path is empty");return async()=>{let{fs:s}=await import("./node-2XIHQ2M4.js"),e;try{e=await s.promises.readFile(r,"utf-8")}catch(n){throw new k(`Failed to read identity token file at ${r}: ${n}`)}let t=e.trim();if(!t)throw new k(`Identity token file at ${r} is empty`);return t}}function ro(r){if(!r)throw new k("Identity token value is empty");return()=>r}function no(r){return async()=>{Vr(r.baseURL);let s=await r.identityTokenProvider();if(s.length>16*1024)throw new N(`Identity token is ${Math.ceil(s.length/1024)} KiB, exceeds the 16 KiB assertion limit`);let e={grant_type:Bi,assertion:s,federation_rule_id:r.federationRuleId,organization_id:r.organizationId};r.serviceAccountId&&(e.service_account_id=r.serviceAccountId),r.workspaceId&&(e.workspace_id=r.workspaceId);let t=`${r.baseURL}${Kr}`,n;try{n=await r.fetch(t,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${Ne},${Ui}`,"User-Agent":r.userAgent||`anthropic-sdk-typescript/${ne} oidcFederationProvider`},body:JSON.stringify(e)})}catch(u){throw new N(`Failed to reach token endpoint ${t}: ${u}`)}let i=n.headers.get("Request-Id");if(!n.ok){let u=await n.text().catch(()=>""),d=J(u),m="";throw n.status===401&&(m=` Ensure your federation rule matches your identity token. ${r.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new N(`Token exchange failed with status ${n.status}${i?` (request-id ${i})`:""}: ${d}${m}`,n.status,d,i)}let o=await Jr(n,i),c=Number(o.expires_in);if(!Number.isFinite(c))throw new N(`Token endpoint response missing required fields: ${JSON.stringify(J(o))}`,n.status,J(o),i);return{token:o.access_token,expiresAt:de()+c}}}function so(r){return async s=>{let{fs:e}=await import("./node-2XIHQ2M4.js");await Yr(r.credentialsPath,r.onSafetyWarning);let t;try{t=await e.promises.readFile(r.credentialsPath,"utf-8")}catch(A){throw new N(`Credentials file not found at ${r.credentialsPath}: ${A}`)}let n;try{n=JSON.parse(t)}catch(A){throw new N(`Credentials file at ${r.credentialsPath} is not valid JSON: ${A}`)}let i=n.access_token;if(!i)throw new N(`Credentials file at ${r.credentialsPath} must include 'access_token'`);let o=n.expires_at;if(!s?.forceRefresh&&(o==null||de()<o-tt))return{token:i,expiresAt:o??null};let c=n.refresh_token;if(!r.clientId||!c)throw new N(`Access token at ${r.credentialsPath} has expired and no refresh is available (client_id ${r.clientId?"set":"empty"}, refresh_token ${c?"set":"empty"})`);Vr(r.baseURL);let u={grant_type:Wi,refresh_token:c,client_id:r.clientId},d=`${r.baseURL}${Kr}`,m;try{m=await r.fetch(d,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":Ne,"User-Agent":r.userAgent||`anthropic-sdk-typescript/${ne} userOAuthProvider`},body:JSON.stringify(u)})}catch(A){throw new N(`User OAuth refresh failed to reach token endpoint: ${A}`)}let p=m.headers.get("Request-Id");if(!m.ok){let A=await m.text().catch(()=>"");throw new N(`User OAuth refresh failed (HTTP ${m.status}): ${J(A)}`,m.status,J(A),p)}let f=await Jr(m,p),w=Number(f.expires_in);if(!Number.isFinite(w))throw new N(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(J(f))}`,m.status,J(f),p);let _=de()+w,v=f.refresh_token||c;return await Xr(r.credentialsPath,{...n,version:rn,type:"oauth_token",access_token:f.access_token,expires_at:_,refresh_token:v}),{token:f.access_token,expiresAt:_}}}function Rs(r,s){let e=r.authentication.credentials_path??null,t=(r.base_url||s.baseURL).replace(/\/+$/,""),n=Ca(r,e,t,s),i={};return r.workspace_id&&r.authentication.type==="user_oauth"&&(i["anthropic-workspace-id"]=r.workspace_id),{provider:n,extraHeaders:i,baseURL:r.base_url||void 0}}async function io(r,s){let e=await Zi(s);if(!e)return null;let{config:t,fromFile:n}=e,i=t.authentication.credentials_path||!n?t:{...t,authentication:{...t.authentication,credentials_path:await eo(t,s)??void 0}};return Rs(i,r)}function Ca(r,s,e,t){switch(r.authentication.type){case"oidc_federation":{let n=r.authentication,i=$a(n);if(!i)throw new N("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 N("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");if(!r.organization_id)throw new N("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");let o=no({identityTokenProvider:i,federationRuleId:n.federation_rule_id,organizationId:r.organization_id,serviceAccountId:n.service_account_id,workspaceId:r.workspace_id,baseURL:e,fetch:t.fetch,userAgent:t.userAgent});return s?Na(o,s,t.onCacheWriteError,t.onSafetyWarning):o}case"user_oauth":{if(!s)throw new N("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return so({credentialsPath:s,clientId:r.authentication.client_id,baseURL:e,fetch:t.fetch,userAgent:t.userAgent,onSafetyWarning:t.onSafetyWarning})}default:{let n=r.authentication.type;throw new N(`authentication.type "${n}" is not a known authentication type`)}}}function $a(r){if(r.identity_token){let t=r.identity_token.source;if(t!=="file")throw new N(`identity_token.source "${t}" is not supported by this SDK version (only "file")`);if(!r.identity_token.path)throw new N('identity_token.source "file" requires a non-empty path');return Es(r.identity_token.path)}let s=M("ANTHROPIC_IDENTITY_TOKEN_FILE");if(s)return Es(s);let e=M("ANTHROPIC_IDENTITY_TOKEN");return e?ro(e):null}function Na(r,s,e,t){return async n=>{let{fs:i}=await import("./node-2XIHQ2M4.js");await Yr(s,t);let o;try{let u=await i.promises.readFile(s,"utf-8");o=JSON.parse(u);let d=o?.access_token;if(d&&!n?.forceRefresh){let m=o?.expires_at;if(m==null||de()<m-tt)return{token:d,expiresAt:m??null}}}catch(u){u?.code!=="ENOENT"&&!(u instanceof SyntaxError)&&e?.(u)}let c=await r(n);try{await Xr(s,{...o??{},version:rn,type:"oauth_token",access_token:c.token,expires_at:c.expiresAt})}catch(u){e?.(u)}return c}}var Q,Z,nr=(()=>{class r{constructor(){Q.set(this,void 0),Z.set(this,void 0),g(this,Q,new Uint8Array,"f"),g(this,Z,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Zt(e):e;g(this,Q,Vi([a(this,Q,"f"),t]),"f");let n=[],i;for(;(i=La(a(this,Q,"f"),a(this,Z,"f")))!=null;){if(i.carriage&&a(this,Z,"f")==null){g(this,Z,i.index,"f");continue}if(a(this,Z,"f")!=null&&(i.index!==a(this,Z,"f")+1||i.carriage)){n.push(er(a(this,Q,"f").subarray(0,a(this,Z,"f")-1))),g(this,Q,a(this,Q,"f").subarray(a(this,Z,"f")),"f"),g(this,Z,null,"f");continue}let o=a(this,Z,"f")!==null?i.preceding-1:i.preceding,c=er(a(this,Q,"f").subarray(0,o));n.push(c),g(this,Q,a(this,Q,"f").subarray(i.index),"f"),g(this,Z,null,"f")}return n}flush(){return a(this,Q,"f").length?this.decode(`
|
|
2
|
+
`):[]}}return Q=new WeakMap,Z=new WeakMap,r.NEWLINE_CHARS=new Set([`
|
|
3
|
+
`,"\r"]),r.NEWLINE_REGEXP=/\r\n|[\n\r]/g,r})();function La(r,s){for(let n=s??0;n<r.length;n++){if(r[n]===10)return{preceding:n,index:n+1,carriage:!1};if(r[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function oo(r){for(let t=0;t<r.length-1;t++){if(r[t]===10&&r[t+1]===10||r[t]===13&&r[t+1]===13)return t+2;if(r[t]===13&&r[t+1]===10&&t+3<r.length&&r[t+2]===13&&r[t+3]===10)return t+4}return-1}var sr,se=(()=>{class r{constructor(e,t,n){this.iterator=e,sr.set(this,void 0),this.controller=t,g(this,sr,n,"f")}static rawEvents(e,t=new AbortController){return ao(e,t)}static fromSSEResponse(e,t,n){let i=!1,o=n?C(n):console;async function*c(){if(i)throw new k("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let u=!1;try{for await(let d of ao(e,t)){if(d.event==="completion")try{yield JSON.parse(d.data)}catch(m){throw o.error("Could not parse message into JSON:",d.data),o.error("From chunk:",d.raw),m}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(m){throw o.error("Could not parse message into JSON:",d.data),o.error("From chunk:",d.raw),m}if(d.event!=="ping"&&d.event==="error"){let m=$e(d.data)??d.data,p=m?.error?.type;throw new F(void 0,m,void 0,e.headers,p)}}u=!0}catch(d){if(G(d))return;throw d}finally{u||t.abort(),pe(t)}}return new r(c,t,n)}static fromReadableStream(e,t,n){let i=!1;async function*o(){let u=new nr,d=Qt(e);for await(let m of d)for(let p of u.decode(m))yield p;for(let m of u.flush())yield m}async function*c(){if(i)throw new k("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let u=!1;try{for await(let d of o())u||d&&(yield JSON.parse(d));u=!0}catch(d){if(G(d))return;throw d}finally{u||t.abort(),pe(t)}}return new r(c,t,n)}[(sr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),i=o=>({next:()=>{if(o.length===0){let c=n.next();e.push(c),t.push(c)}return o.shift()}});return[new r(()=>i(e),this.controller,a(this,sr,"f")),new r(()=>i(t),this.controller,a(this,sr,"f"))]}toReadableStream(){let e=this,t;return ms({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:i,done:o}=await t.next();if(o)return n.close();let c=Zt(JSON.stringify(i)+`
|
|
4
|
+
`);n.enqueue(c)}catch(i){n.error(i)}},async cancel(){await t.return?.()}})}}return r})();async function*ao(r,s){if(!r.body)throw s.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new k("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 k("Attempted to iterate over a response with no body");let e=new Is,t=new nr,n=Qt(r.body);for await(let i of Fa(n))for(let o of t.decode(i)){let c=e.decode(o);c&&(yield c)}for(let i of t.flush()){let o=e.decode(i);o&&(yield o)}}async function*Fa(r){let s=new Uint8Array;for await(let e of r){if(e==null)continue;let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Zt(e):e,n=new Uint8Array(s.length+t.length);n.set(s),n.set(t,s.length),s=n;let i;for(;(i=oo(s))!==-1;)yield s.subarray(0,i),s=s.subarray(i)}s.length>0&&(yield s)}var Is=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(s){if(s.endsWith("\r")&&(s=s.substring(0,s.length-1)),!s){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
|
|
5
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(s),s.startsWith(":"))return null;let[e,t,n]=Ha(s,":");return n.startsWith(" ")&&(n=n.substring(1)),e==="event"?this.event=n:e==="data"&&this.data.push(n),null}};function Ha(r,s){let e=r.indexOf(s);return e!==-1?[r.substring(0,e),s,r.substring(e+s.length)]:[r,"",""]}async function nn(r,s){let{response:e,requestLogID:t,retryOfRequestLogID:n,startTime:i}=s,o=await(async()=>{if(s.options.stream)return C(r).debug("response",e.status,e.url,e.headers,e.body),se.fromSSEResponse(e,s.controller,r);if(e.status===204)return null;if(s.options.__binaryResponse)return e;let u=e.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){if(e.headers.get("content-length")==="0")return;let f=await e.json();return ir(f,e)}return await e.text()})().finally(()=>{!s.options.stream&&!s.options.__binaryResponse&&pe(s.controller)});return C(r).debug(`[${t}] response parsed`,_e({retryOfRequestLogID:n,url:e.url,status:e.status,body:o,durationMs:Date.now()-i})),o}function ir(r,s){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperties(r,{_request_id:{value:s.headers.get("request-id"),enumerable:!1},_workspace_id:{value:s.headers.get("anthropic-workspace-id"),enumerable:!1}})}var lo=new WeakSet;function Ps(r){return typeof r=="object"&&r!==null&&lo.has(r)}function uo(r){let s=new Set;for(;typeof r=="object"&&r!==null&&!s.has(r);){if(s.add(r),Ps(r)||G(r)||r instanceof fe||r instanceof Yt)return!0;r=r.cause}return!1}function Ts(r,s,e,t){return async(n,i={})=>{if(s.length===0)return r.call(void 0,n,i);let o=i.headers instanceof Headers?i.headers:new Headers(i.headers),c=await Ba(r,s,e,t)({...i,headers:o,url:typeof n=="string"?n:n instanceof URL?n.href:n.url});if(c.bodyUsed||c.body?.locked)throw new k("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 Da(r,s){let e=new WeakMap;return{options:r,logger:s?C(s):Gi(),parse(t){if(r?.stream&&t.ok)return co(t,r,s);let n=e.get(t);return n||(n=co(t,r,s),e.set(t,n)),n}}}async function co(r,s,e){if(r.bodyUsed||r.body?.locked)throw new k("cannot ctx.parse() a response whose body was already consumed; call ctx.parse() instead of reading the body, or read via response.clone()");if(s?.stream&&r.ok)return se.fromSSEResponse(r.clone(),new AbortController,e);if(r.status===204)return null;if(s?.__binaryResponse)return r;let n=r.headers.get("content-type")?.split(";")[0]?.trim();return n?.includes("application/json")||n?.endsWith("+json")?r.headers.get("content-length")==="0"?void 0:ir(await r.clone().json(),r):await r.clone().text()}function Ba(r,s,e,t){let n=async({url:o,...c})=>{try{return await r.call(void 0,o,c)}catch(u){let d=Ce(u);throw lo.add(d),d}},i=Da(e,t);for(let o=s.length-1;o>=0;o--){let c=s[o],u=n;n=async d=>c(d,u,i)}return n}var or,ar=(()=>{class r extends Promise{constructor(e,t,n=nn){super(i=>{i(null)}),this.responsePromise=t,this.parseResponse=n,or.set(this,void 0),g(this,or,e,"f")}_thenUnwrap(e){return new r(a(this,or,"f"),this.responsePromise,async(t,n)=>ir(e(await this.parseResponse(t,n),n),n.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,or,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}return or=new WeakMap,r})();var sn,Ms=(()=>{class r{constructor(e,t,n,i){sn.set(this,void 0),g(this,sn,e,"f"),this.options=i,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new k("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await a(this,sn,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(sn=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}return r})(),Os=(()=>{class r extends ar{constructor(e,t,n){super(e,t,async(i,o)=>new n(i,o.response,await nn(i,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}}return r})(),B=class extends Ms{constructor(s,e,t,n){super(s,e,t,n),this.data=t.data||[],this.has_more=t.has_more||!1,this.first_id=t.first_id||null,this.last_id=t.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let e=this.first_id;return e?{...this.options,query:{...Xt(this.options.query),before_id:e}}:null}let s=this.last_id;return s?{...this.options,query:{...Xt(this.options.query),after_id:s}}:null}};var S=class extends Ms{constructor(s,e,t,n){super(s,e,t,n),this.data=t.data||[],this.next_page=t.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let s=this.next_page;return s?{...this.options,query:{...Xt(this.options.query),page:s}}:null}},on=class extends Ms{constructor(s,e,t,n){super(s,e,t,n),this.data=t.data||[],this.next_page=t.next_page||null,this.prev_page=t.prev_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let s=this.next_page;return s?{...this.options,query:{...Xt(this.options.query),page:s}}:null}};var $s=()=>{if(typeof File>"u"){let{process:r}=globalThis,s=typeof r?.versions?.node=="string"&&parseInt(r.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(s?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Le(r,s,e){return $s(),new File(r,s??"unknown_file",e)}function cr(r,s){let e=typeof r=="object"&&r!==null&&("name"in r&&r.name&&String(r.name)||"url"in r&&r.url&&String(r.url)||"filename"in r&&r.filename&&String(r.filename)||"path"in r&&r.path&&String(r.path))||"";return s?e.split(/[\\/]/).pop()||void 0:e}var Ns=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function";var ie=async(r,s,e=!0)=>({...r,body:await qa(r.body,s,e)}),ho=new WeakMap;function Ua(r){let s=typeof r=="function"?r:r.fetch,e=ho.get(s);if(e)return e;let t=(async()=>{try{let n="Response"in s?s.Response:(await s("data:,")).constructor,i=new FormData;return i.toString()!==await new n(i).text()}catch{return!0}})();return ho.set(s,t),t}var qa=async(r,s,e=!0)=>{if(!await Ua(s))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let t=new FormData;return await Promise.all(Object.entries(r||{}).map(([n,i])=>Cs(t,n,i,e))),t};var Cs=async(r,s,e,t)=>{if(e!==void 0){if(e==null)throw new TypeError(`Received null for "${s}"; to pass null in FormData, you must use the string 'null'`);if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")r.append(s,String(e));else if(e instanceof Response){let n={},i=e.headers.get("Content-Type");i&&(n={type:i}),r.append(s,Le([await e.blob()],cr(e,t),n))}else if(Ns(e))r.append(s,Le([await new Response(qr(e)).blob()],cr(e,t)));else if(e instanceof Blob)r.append(s,Le([e],cr(e,t)||void 0,{type:e.type}));else if(Array.isArray(e))await Promise.all(e.map(n=>Cs(r,s+"[]",n,t)));else{if(typeof e.then=="function")throw new TypeError(`Received a Promise for "${s}"; await it first, e.g. \`await toFile(...)\``);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))throw new TypeError(`Received ${e.constructor.name} for "${s}"; to upload raw bytes, wrap them with \`await toFile(bytes, 'filename')\``);if(typeof e=="object")await Promise.all(Object.entries(e).map(([n,i])=>Cs(r,`${s}[${n}]`,i,t)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${e} instead`)}}};var fo=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function",ja=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&fo(r),za=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function";async function an(r,s,e){if($s(),r=await r,s||(s=cr(r,!0)),ja(r))return r instanceof File&&s==null&&e==null?r:Le([await r.arrayBuffer()],s??r.name,{type:r.type,lastModified:r.lastModified,...e});if(za(r)){let n=await r.blob();return s||(s=new URL(r.url).pathname.split(/[\\/]/).pop()),Le(await Ls(n),s,e)}let t=await Ls(r);if(!e?.type){let n=t.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof n=="string"&&(e={...e,type:n})}return Le(t,s,e)}async function Ls(r){let s=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)s.push(r);else if(fo(r))s.push(r instanceof Blob?r:await r.arrayBuffer());else if(Ns(r))for await(let e of r)s.push(...await Ls(e));else{let e=r?.constructor?.name;throw new Error(`Unexpected data type: ${typeof r}${e?`; constructor: ${e}`:""}${Ka(r)}`)}return s}function Ka(r){return typeof r!="object"||r===null?"":`; props: [${Object.getOwnPropertyNames(r).map(e=>`"${e}"`).join(", ")}]`}var b=class{constructor(s){this._client=s}};var po=Symbol.for("brand.privateNullableHeaders");function*Ja(r){if(!r)return;if(po in r){let{values:t,nulls:n}=r;yield*t.entries();for(let i of n)yield[i,null];return}let s=!1,e;r instanceof Headers?e=r.entries():hs(r)?e=r:(s=!0,e=Object.entries(r??{}));for(let t of e){let n=t[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let i=hs(t[1])?t[1]:[t[1]],o=!1;for(let c of i)c!==void 0&&(s&&!o&&(o=!0,yield[n,cn]),yield[n,c])}}var cn=Symbol("clear"),Ya=new Set(["x-stainless-helper"]),Fs=(r,s)=>{let e=r?r.split(",").map(t=>t.trim()).filter(Boolean):[];for(let t of s.split(",").map(n=>n.trim()))t&&!e.includes(t)&&e.push(t);return e.join(", ")},l=r=>{let s=new Headers,e=new Set;for(let t of r){let n=new Set;for(let[i,o]of Ja(t)){let c=i.toLowerCase();if(Ya.has(c)){if(o===cn)continue;o===null?(s.delete(i),e.add(c)):(s.set(i,Fs(s.get(i),o)),e.delete(c));continue}(o===cn||!n.has(c))&&(s.delete(i),n.add(c),o===cn)||(o===null?(s.delete(i),e.add(c)):(s.append(i,o),e.delete(c)))}}return{[po]:!0,values:s,nulls:e}};function _o(r){return r.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var mo=Object.freeze(Object.create(null)),Xa=(r=_o)=>function(e,...t){if(e.length===1)return e[0];let n=!1,i=[],o=e.reduce((m,p,f)=>{/[?#]/.test(p)&&(n=!0);let w=t[f],_=(n?encodeURIComponent:r)(""+w);return f!==t.length&&(w==null||typeof w=="object"&&w.toString===Object.getPrototypeOf(Object.getPrototypeOf(w.hasOwnProperty??mo)??mo)?.toString)&&(_=w+"",i.push({start:m.length+p.length,length:_.length,error:`Value of type ${Object.prototype.toString.call(w).slice(8,-1)} is not a valid path parameter`})),m+p+(f===t.length?"":_)},""),c=o.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,d;for(;(d=u.exec(c))!==null;)i.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(i.sort((m,p)=>m.start-p.start),i.length>0){let m=0,p=i.reduce((f,w)=>{let _=" ".repeat(w.start-m),v="^".repeat(w.length);return m=w.start+w.length,f+_+v},"");throw new k(`Path parameters result in path with invalid segments:
|
|
6
|
+
${i.map(f=>f.error).join(`
|
|
7
|
+
`)}
|
|
8
|
+
${o}
|
|
9
|
+
${p}`)}return o},h=Xa(_o);var rt=class extends b{retrieve(s,e={},t){let{betas:n,workspace_id:i}=e??{};return this._client.get(h`/v1/deployment_runs/${s}?beta=true`,{...t,headers:l([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}list(s={},e){let{betas:t,workspace_id:n,...i}=s??{};return this._client.getAPIList("/v1/deployment_runs?beta=true",S,{query:i,...e,headers:l([{"anthropic-beta":[...t??[],"managed-agents-2026-04-01"].toString(),...n!=null?{"anthropic-workspace-id":n}:void 0},e?.headers])})}};var nt=class extends b{create(s,e){let{betas:t,workspace_id:n,...i}=s;return this._client.post("/v1/deployments?beta=true",{body:i,...e,headers:l([{"anthropic-beta":[...t??[],"managed-agents-2026-04-01"].toString(),...n!=null?{"anthropic-workspace-id":n}:void 0},e?.headers])})}retrieve(s,e={},t){let{betas:n,workspace_id:i}=e??{};return this._client.get(h`/v1/deployments/${s}?beta=true`,{...t,headers:l([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}update(s,e,t){let{betas:n,workspace_id:i,...o}=e;return this._client.post(h`/v1/deployments/${s}?beta=true`,{body:o,...t,headers:l([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}list(s={},e){let{betas:t,workspace_id:n,...i}=s??{};return this._client.getAPIList("/v1/deployments?beta=true",S,{query:i,...e,headers:l([{"anthropic-beta":[...t??[],"managed-agents-2026-04-01"].toString(),...n!=null?{"anthropic-workspace-id":n}:void 0},e?.headers])})}archive(s,e={},t){let{betas:n,workspace_id:i}=e??{};return this._client.post(h`/v1/deployments/${s}/archive?beta=true`,{...t,headers:l([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}pause(s,e={},t){let{betas:n,workspace_id:i}=e??{};return this._client.post(h`/v1/deployments/${s}/pause?beta=true`,{...t,headers:l([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}run(s,e={},t){let{betas:n,workspace_id:i}=e??{};return this._client.post(h`/v1/deployments/${s}/run?beta=true`,{...t,headers:l([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}unpause(s,e={},t){let{betas:n,workspace_id:i}=e??{};return this._client.post(h`/v1/deployments/${s}/unpause?beta=true`,{...t,headers:l([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}};var st=class extends b{create(s,e){let{betas:t,workspace_id:n,...i}=s;return this._client.post("/v1/dreams?beta=true",{body:i,...e,headers:l([{"anthropic-beta":[...t??[],"dreaming-2026-04-21"].toString(),...n!=null?{"anthropic-workspace-id":n}:void 0},e?.headers])})}retrieve(s,e={},t){let{betas:n,workspace_id:i}=e??{};return this._client.get(h`/v1/dreams/${s}?beta=true`,{...t,headers:l([{"anthropic-beta":[...n??[],"dreaming-2026-04-21"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}list(s={},e){let{betas:t,workspace_id:n,...i}=s??{};return this._client.getAPIList("/v1/dreams?beta=true",S,{query:i,...e,headers:l([{"anthropic-beta":[...t??[],"dreaming-2026-04-21"].toString(),...n!=null?{"anthropic-workspace-id":n}:void 0},e?.headers])})}archive(s,e={},t){let{betas:n,workspace_id:i}=e??{};return this._client.post(h`/v1/dreams/${s}/archive?beta=true`,{...t,headers:l([{"anthropic-beta":[...n??[],"dreaming-2026-04-21"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}cancel(s,e={},t){let{betas:n,workspace_id:i}=e??{};return this._client.post(h`/v1/dreams/${s}/cancel?beta=true`,{...t,headers:l([{"anthropic-beta":[...n??[],"dreaming-2026-04-21"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}};var ge="x-stainless-helper",dn="x-stainless-helper-method";function dr(r){return{[ge]:r}}var lr=Symbol("anthropic.sdk.stainlessHelper");function ln(r){return typeof r=="object"&&r!==null&&lr in r}function Hs(r,s){let e=new Set;if(r)for(let t of r)ln(t)&&e.add(t[lr]);if(s)for(let t of s){ln(t)&&e.add(t[lr]);let n=t.content;if(Array.isArray(n))for(let i of n)ln(i)&&e.add(i[lr])}return Array.from(e)}function un(r,s){let e=Hs(r,s);return e.length===0?{}:{[ge]:e.join(", ")}}function hn(r){return ln(r)?{[ge]:r[lr]}:{}}var it=class extends b{list(s={},e){let{betas:t,workspace_id:n,...i}=s??{};return this._client.getAPIList("/v1/files?beta=true",S,{query:i,...e,headers:l([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0,...n!=null?{"anthropic-workspace-id":n}:void 0},e?.headers])})}delete(s,e={},t){let{betas:n,workspace_id:i}=e??{};return this._client.delete(h`/v1/files/${s}?beta=true`,{...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}download(s,e={},t){let{betas:n,workspace_id:i}=e??{};return this._client.get(h`/v1/files/${s}/content?beta=true`,{...t,headers:l([{Accept:"application/binary",...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers]),__binaryResponse:!0})}retrieveMetadata(s,e={},t){let{betas:n,workspace_id:i}=e??{};return this._client.get(h`/v1/files/${s}?beta=true`,{...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}upload(s,e){let{betas:t,workspace_id:n,...i}=s;return this._client.post("/v1/files?beta=true",ie({body:i,...e,headers:l([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0,...n!=null?{"anthropic-workspace-id":n}:void 0},hn(i.file),e?.headers])},this._client))}};var ot=class extends b{retrieve(s,e={},t){let{betas:n,workspace_id:i}=e??{};return this._client.get(h`/v1/models/${s}?beta=true`,{...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}list(s={},e){let{betas:t,workspace_id:n,...i}=s??{};return this._client.getAPIList("/v1/models?beta=true",B,{query:i,...e,headers:l([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0,...n!=null?{"anthropic-workspace-id":n}:void 0},e?.headers])})}};var at=class extends b{create(s,e){let{betas:t,workspace_id:n,...i}=s;return this._client.post("/v1/user_profiles?beta=true",{body:i,...e,headers:l([{"anthropic-beta":[...t??[],"user-profiles-2026-08-18"].toString(),...n!=null?{"anthropic-workspace-id":n}:void 0},e?.headers])})}retrieve(s,e={},t){let{betas:n,workspace_id:i}=e??{};return this._client.get(h`/v1/user_profiles/${s}?beta=true`,{...t,headers:l([{"anthropic-beta":[...n??[],"user-profiles-2026-08-18"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}update(s,e,t){let{betas:n,workspace_id:i,...o}=e;return this._client.post(h`/v1/user_profiles/${s}?beta=true`,{body:o,...t,headers:l([{"anthropic-beta":[...n??[],"user-profiles-2026-08-18"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}list(s={},e){let{betas:t,workspace_id:n,...i}=s??{};return this._client.getAPIList("/v1/user_profiles?beta=true",S,{query:i,...e,headers:l([{"anthropic-beta":[...t??[],"user-profiles-2026-08-18"].toString(),...n!=null?{"anthropic-workspace-id":n}:void 0},e?.headers])})}createEnrollmentURL(s,e={},t){let{betas:n,workspace_id:i}=e??{};return this._client.post(h`/v1/user_profiles/${s}/enrollment_url?beta=true`,{...t,headers:l([{"anthropic-beta":[...n??[],"user-profiles-2026-08-18"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}};var Ro=_a(Eo(),1),lt=class extends b{parseUnverified(s){return JSON.parse(s)}unwrap(s,e){let t=e?.headers;if(t==null)throw new Error("Webhook headers are required in order to verify the signature");let n=e.key===void 0?this._client.webhookKey:e.key;if(!n)throw new Error("Webhook key must not be null or empty in order to unwrap");return new Ro.Webhook(n).verify(s,t),JSON.parse(s)}};var dt=class extends b{list(s,e={},t){let{betas:n,workspace_id:i,...o}=e??{};return this._client.getAPIList(h`/v1/agents/${s}/versions?beta=true`,S,{query:o,...t,headers:l([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}};var mn=(()=>{class r extends b{constructor(){super(...arguments),this.versions=new dt(this._client)}create(e,t){let{betas:n,workspace_id:i,...o}=e;return this._client.post("/v1/agents?beta=true",{body:o,...t,headers:l([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}retrieve(e,t={},n){let{betas:i,workspace_id:o,...c}=t??{};return this._client.get(h`/v1/agents/${e}?beta=true`,{query:c,...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}update(e,t,n){let{betas:i,workspace_id:o,...c}=t;return this._client.post(h`/v1/agents/${e}?beta=true`,{body:c,...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}list(e={},t){let{betas:n,workspace_id:i,...o}=e??{};return this._client.getAPIList("/v1/agents?beta=true",S,{query:o,...t,headers:l([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}archive(e,t={},n){let{betas:i,workspace_id:o}=t??{};return this._client.post(h`/v1/agents/${e}/archive?beta=true`,{...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}}return r.Versions=dt,r})();function ve(r,s){if(!r)return()=>{};if(r.aborted)return s.abort(),()=>{};let e=()=>s.abort();return r.addEventListener("abort",e),()=>r.removeEventListener("abort",e)}function Ae(r,s){return r instanceof F&&r.status===s}function pc(r){return r instanceof F&&typeof r.status=="number"&&r.status>=400&&r.status<500}function Fe(r){return pc(r)&&!Ae(r,408)&&!Ae(r,409)&&!Ae(r,429)}function _n(r,s,e){return Math.min(s*2**r,e)}function Io(r,s){return r+Math.random()*(s-r)}function gn(r){return r*(1-Math.random()*.25)}function wn(r,{authToken:s,helper:e}){if(!s)throw new k(`copyClientForHelper: expected a non-empty authToken but received ${JSON.stringify(s)}`);let t=r,n=t._options.defaultHeaders,i=t._authState?.extraHeaders,o=i?Object.fromEntries(Object.entries(i).filter(([u])=>{let d=u.toLowerCase();return d!=="authorization"&&d!=="x-api-key"})):void 0,c=l([o,n,{[ge]:e}]);return r.withOptions({apiKey:null,authToken:s,baseURL:r.baseURL,credentials:void 0,defaultHeaders:c})}var ut,bn,oe,yn,kn,Sn,hr,fr,ht,ft,xn,pt,pr,mc=999,_c=1e3,gc=6e4,wc=3e5,mr=(()=>{class r{constructor(e){ut.set(this,void 0),bn.set(this,!1),oe.set(this,void 0),yn.set(this,void 0),kn.set(this,void 0),Sn.set(this,void 0),hr.set(this,void 0),fr.set(this,void 0),ht.set(this,void 0),this.client=e.client,this.environmentId=e.environmentId,this.environmentKey=e.environmentKey,this.workerId=e.workerId??kc(),g(this,ut,wn(e.client,{authToken:e.environmentKey,helper:"environments-work-poller"}),"f"),g(this,kn,e.autoStop??!0,"f"),g(this,Sn,e.drain??!1,"f"),g(this,hr,e.blockMs===void 0?mc:e.blockMs,"f"),g(this,fr,e.reclaimOlderThanMs??null,"f"),g(this,ht,e.requestOptions,"f"),g(this,oe,new AbortController,"f"),g(this,yn,ve(e.signal,a(this,oe,"f")),"f")}get signal(){return a(this,oe,"f").signal}abort(){a(this,oe,"f").abort()}async*[(ut=new WeakMap,bn=new WeakMap,oe=new WeakMap,yn=new WeakMap,kn=new WeakMap,Sn=new WeakMap,hr=new WeakMap,fr=new WeakMap,ht=new WeakMap,Symbol.asyncIterator)](){if(a(this,bn,"f"))throw new k("Cannot iterate over a consumed WorkPoller");g(this,bn,!0,"f");let e=C(this.client);e.info("poller starting",{component:"work-poller",environment_id:this.environmentId});let t=new yc(e,this.environmentId);try{let n=0;for(;!a(this,oe,"f").signal.aborted;){let i;try{i=await a(this,ut,"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,fr,"f")!==null?{reclaim_older_than_ms:a(this,fr,"f")}:{}},{headers:l([a(this,ht,"f")?.headers]),signal:a(this,oe,"f").signal})}catch(o){if(a(this,oe,"f").signal.aborted)return;if(Fe(o))throw e.error("poll failed permanently, stopping poller",{error:String(o)}),o;let c=gn(bc(n));e.warn("poll failed, backing off",{error:String(o),backoff_ms:c}),n++,await le(c,a(this,oe,"f").signal);continue}if(n=0,i==null){if(a(this,Sn,"f"))return;t.onEmptyPoll(),await le(Io(1e3,3e3),a(this,oe,"f").signal);continue}t.onClaim(),e.info("claimed work",{component:"work-poller",environment_id:this.environmentId,work_id:i.id,work_type:i.data.type});try{await a(this,ut,"f").beta.environments.work.ack(i.id,{environment_id:i.environment_id},{headers:l([a(this,ht,"f")?.headers]),signal:a(this,oe,"f").signal})}catch(o){e.error("ack failed",{work_id:i.id,error:String(o)});continue}try{yield i}finally{if(a(this,kn,"f"))try{await a(this,ut,"f").beta.environments.work.stop(i.id,{environment_id:i.environment_id},{headers:l([a(this,ht,"f")?.headers])})}catch(o){Ae(o,409)||e.warn("stop failed",{work_id:i.id,error:String(o)})}}}}finally{a(this,yn,"f").call(this)}}}return r})();function bc(r){return _n(r,_c,gc)}var yc=(()=>{class r{constructor(e,t){ft.set(this,void 0),xn.set(this,void 0),pt.set(this,void 0),pr.set(this,0),g(this,ft,e,"f"),g(this,xn,t,"f")}onEmptyPoll(){let e=Date.now(),t={component:"work-poller",environment_id:a(this,xn,"f")};a(this,pt,"f")===void 0?(g(this,pt,g(this,pr,e,"f"),"f"),a(this,ft,"f").info("idle; polling for work",t)):e-a(this,pr,"f")>=wc?(g(this,pr,e,"f"),a(this,ft,"f").info(`still polling; idle for ${Math.round((e-a(this,pt,"f"))/1e3)}s`,t)):a(this,ft,"f").debug("poll returned no work",t)}onClaim(){g(this,pt,void 0,"f")}}return ft=new WeakMap,xn=new WeakMap,pt=new WeakMap,pr=new WeakMap,r})();function kc(){let s=globalThis.process?.env?.HOSTNAME;return s?`${s}-${tn()}`:tn()}var mt,Ee,_t,Po=(()=>{class r{constructor(){mt.set(this,[]),Ee.set(this,[]),_t.set(this,!1)}push(e){if(a(this,_t,"f"))return!1;let t=a(this,Ee,"f").shift();return t?t({done:!1,value:e}):a(this,mt,"f").push(e),!0}close(){if(!a(this,_t,"f"))for(g(this,_t,!0,"f");a(this,Ee,"f").length>0;)a(this,Ee,"f").shift()({done:!0,value:void 0})}next(e){return a(this,mt,"f").length>0?Promise.resolve({done:!1,value:a(this,mt,"f").shift()}):a(this,_t,"f")||e?.aborted?Promise.resolve({done:!0,value:void 0}):new Promise(t=>{let n=o=>{e?.removeEventListener("abort",i),t(o)},i=()=>{let o=a(this,Ee,"f").indexOf(n);o>=0&&a(this,Ee,"f").splice(o,1),t({done:!0,value:void 0})};a(this,Ee,"f").push(n),e?.addEventListener("abort",i,{once:!0})})}tryShift(){return a(this,mt,"f").shift()}}return mt=new WeakMap,Ee=new WeakMap,_t=new WeakMap,r})();var gt=(()=>{class r extends Error{constructor(e){let t=typeof e=="string"?e:e.map(n=>n.type==="text"?n.text:`[${n.type}]`).join(" ");super(t),this.name="ToolError",this.content=e}}return r})();function Us(r){return"name"in r?r.name:"mcp_server_name"in r?r.mcp_server_name:r.type}function Sc(r){return r instanceof gt?r.content:`Error: ${r instanceof Error?r.message:String(r)}`}async function To(r,s,e){try{let t=r.parse?r.parse(s):s;return{content:await r.run(t,e),isError:!1}}catch(t){return{content:Sc(t),isError:!0}}}var _r,vn,wt,He,ue,H,An,K,En,gr,Tn,U,yt,te,kt,Re,bt,ye,Mn,wr,ae,Rn,Fo,Mo,Oo,Co,qs,$o,In,Pn,js,No,Ho;var Lo=500,xc=1e4,vc=12e4,Ac=3e4,Ec=1e3,Rc=3e4,Ic=5*6e4,Pc=6e4;function Do(r){return r.type==="session.status_idle"&&r.stop_reason?.type==="end_turn"}var Tc=(()=>{class r{constructor(e,t){_r.set(this,void 0),vn.set(this,void 0),wt.set(this,new Set),He.set(this,!1),ue.set(this,void 0),g(this,_r,e,"f"),g(this,vn,t,"f")}noteEvent(e){e.type!=="user.tool_confirmation"&&(Do(e)?this.arm():this.disarm())}block(e){a(this,wt,"f").add(e),a(this,ue,"f")!==void 0&&(g(this,He,!0,"f"),clearTimeout(a(this,ue,"f")),g(this,ue,void 0,"f"))}unblock(e){a(this,wt,"f").delete(e),a(this,wt,"f").size===0&&a(this,He,"f")&&this.arm()}arm(){if(!(a(this,_r,"f")<=0)){if(a(this,wt,"f").size>0){g(this,He,!0,"f");return}g(this,He,!1,"f"),a(this,ue,"f")!==void 0&&clearTimeout(a(this,ue,"f")),g(this,ue,setTimeout(a(this,vn,"f"),a(this,_r,"f")),"f")}}disarm(){g(this,He,!1,"f"),a(this,ue,"f")!==void 0&&(clearTimeout(a(this,ue,"f")),g(this,ue,void 0,"f"))}}return _r=new WeakMap,vn=new WeakMap,wt=new WeakMap,He=new WeakMap,ue=new WeakMap,r})(),br=(()=>{class r{constructor(e,t){H.add(this),An.set(this,!1),K.set(this,void 0),En.set(this,void 0),gr.set(this,void 0),Tn.set(this,void 0),U.set(this,void 0),yt.set(this,new Set),te.set(this,new Set),kt.set(this,new Map),Re.set(this,new Map),bt.set(this,new Po),ye.set(this,0),Mn.set(this,Ic),wr.set(this,null),ae.set(this,void 0),this.client=t.client,this.sessionId=e,this.tools=t.tools,this.maxIdleMs=t.maxIdleMs??Pc,g(this,U,C(t.client),"f"),g(this,Tn,new Map(t.tools.map(n=>[Us(n),n])),"f"),g(this,K,new AbortController,"f"),g(this,En,ve(t.signal,a(this,K,"f")),"f"),g(this,gr,t.requestOptions,"f"),g(this,ae,new Tc(this.maxIdleMs,()=>{a(this,U,"f").info("session idle after end_turn; stopping",{component:"session-tool-runner",session_id:this.sessionId,max_idle_ms:this.maxIdleMs}),a(this,K,"f").abort()}),"f")}get signal(){return a(this,K,"f").signal}abort(){a(this,K,"f").abort()}_setSendRetryWindow(e){g(this,Mn,e,"f")}async*[(An=new WeakMap,K=new WeakMap,En=new WeakMap,gr=new WeakMap,Tn=new WeakMap,U=new WeakMap,yt=new WeakMap,te=new WeakMap,kt=new WeakMap,Re=new WeakMap,bt=new WeakMap,ye=new WeakMap,Mn=new WeakMap,wr=new WeakMap,ae=new WeakMap,H=new WeakSet,Symbol.asyncIterator)](){if(a(this,An,"f"))throw new k("Cannot iterate over a consumed SessionToolRunner");g(this,An,!0,"f"),a(this,U,"f").info("session tool runner starting",{component:"session-tool-runner",session_id:this.sessionId});let e=a(this,H,"m",Fo).call(this).catch(t=>{a(this,K,"f").signal.aborted||a(this,U,"f").error("stream loop failed",{error:String(t)}),a(this,K,"f").abort()});try{for(;;){let n=await a(this,bt,"f").next(a(this,K,"f").signal);if(n.done)break;yield n.value}await e;let t;for(;(t=a(this,bt,"f").tryShift())!==void 0;)yield t}finally{a(this,K,"f").abort(),a(this,ae,"f").disarm(),await e;try{await a(this,H,"m",Ho).call(this)}catch(t){a(this,U,"f").warn("drain failed",{error:String(t)})}a(this,bt,"f").close();for(let t of this.tools)try{await t.close?.()}catch(n){a(this,U,"f").warn("tool.close failed",{tool:Us(t),error:String(n)})}a(this,En,"f").call(this)}}}return r})();Rn=function(){return{...a(this,gr,"f"),headers:l([dr("session-tool-runner"),a(this,gr,"f")?.headers]),signal:a(this,K,"f").signal}},Fo=async function(){let s=a(this,K,"f"),e=Lo;for(;!s.signal.aborted;){try{let t=await this.client.beta.sessions.events.stream(this.sessionId,{},a(this,H,"m",Rn).call(this));await a(this,H,"m",Mo).call(this);for await(let n of t)if(e=Lo,await a(this,H,"m",Co).call(this,n))return}catch(t){if(s.signal.throwIfAborted(),Fe(t))throw a(this,U,"f").error("permanent stream failure, shutting down",{error:String(t)}),s.abort(),t;a(this,U,"f").warn("stream disconnected, reconnecting",{error:String(t),backoff_ms:e})}s.signal.throwIfAborted(),await le(e,s.signal),e=Math.min(e*2,xc)}},Mo=async function(){let s=a(this,K,"f"),e=[],t=!1;try{for await(let o of this.client.beta.sessions.events.list(this.sessionId,{limit:1e3},a(this,H,"m",Rn).call(this)))a(this,H,"m",Oo).call(this,o,e),t=Do(o)}catch(o){s.signal.throwIfAborted(),a(this,U,"f").warn("reconcile list failed",{error:String(o)});for(let c of e)a(this,yt,"f").delete(c.id);return}let n=e.filter(o=>!a(this,te,"f").has(o.id));a(this,ae,"f").disarm();for(let o of n)await a(this,H,"m",qs).call(this,o);for(let o of[...a(this,Re,"f").values()]){let c=a(this,kt,"f").get(o.id);c!==void 0&&await a(this,H,"m",In).call(this,o,c)}let i=n.filter(o=>!a(this,te,"f").has(o.id)&&!a(this,Re,"f").has(o.id));t&&i.length===0?a(this,ae,"f").arm():a(this,ae,"f").disarm()},Oo=function(s,e){s.type==="agent.tool_use"||s.type==="agent.custom_tool_use"?(a(this,yt,"f").add(s.id),a(this,te,"f").has(s.id)||e.push(s)):s.type==="user.tool_result"?a(this,te,"f").add(s.tool_use_id):s.type==="user.custom_tool_result"?a(this,te,"f").add(s.custom_tool_use_id):s.type==="user.tool_confirmation"&&(a(this,te,"f").has(s.tool_use_id)||a(this,kt,"f").set(s.tool_use_id,s.result))},Co=async function(s){switch(a(this,ae,"f").noteEvent(s),s.type){case"agent.tool_use":case"agent.custom_tool_use":return a(this,yt,"f").has(s.id)||(a(this,yt,"f").add(s.id),await a(this,H,"m",qs).call(this,s)),!1;case"user.tool_confirmation":return await a(this,H,"m",$o).call(this,s),!1;case"user.tool_result":return a(this,te,"f").add(s.tool_use_id),!1;case"user.custom_tool_result":return a(this,te,"f").add(s.custom_tool_use_id),!1;case"session.status_terminated":case"session.deleted":return a(this,U,"f").info("session terminated",{component:"session-tool-runner",session_id:this.sessionId}),a(this,K,"f").abort(),!0;default:return!1}},qs=async function(s){let e=s.evaluated_permission,t=e==="deny"?"deny":a(this,kt,"f").get(s.id);if(t===void 0){e===void 0||e==="allow"?await a(this,H,"m",js).call(this,s,void 0):a(this,Re,"f").has(s.id)||(a(this,U,"f").info("tool call awaiting confirmation; holding",{component:"session-tool-runner",session_id:this.sessionId,tool:s.name,tool_use_id:s.id}),a(this,Re,"f").set(s.id,s),a(this,ae,"f").block(s.id));return}await a(this,H,"m",In).call(this,s,t)},$o=async function(s){a(this,kt,"f").set(s.tool_use_id,s.result);let e=a(this,Re,"f").get(s.tool_use_id);e!==void 0&&await a(this,H,"m",In).call(this,e,s.result)},In=async function(s,e){let t=a(this,Re,"f").delete(s.id);if(e==="allow"){a(this,U,"f").info("tool call confirmed",{component:"session-tool-runner",session_id:this.sessionId,tool:s.name,tool_use_id:s.id}),t||a(this,ae,"f").block(s.id);try{await a(this,H,"m",js).call(this,s,"allow")}finally{a(this,ae,"f").unblock(s.id)}return}t&&a(this,ae,"f").unblock(s.id),a(this,te,"f").add(s.id),a(this,U,"f").info("tool call denied; not executing",{component:"session-tool-runner",session_id:this.sessionId,tool:s.name,tool_use_id:s.id}),a(this,H,"m",Pn).call(this,{event:s,toolUseId:s.id,name:s.name,isError:!1,posted:!1,confirmation:"deny"})},Pn=function(s){a(this,bt,"f").push(s)},js=async function(s,e){var t,n;if(!a(this,te,"f").has(s.id)){a(this,U,"f").info("executing tool",{component:"session-tool-runner",session_id:this.sessionId,tool:s.name,tool_use_id:s.id}),g(this,ye,(t=a(this,ye,"f"),t++,t),"f");try{let i=a(this,Tn,"f").get(s.name);if(!i){a(this,U,"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:s.name,tool_use_id:s.id}),a(this,H,"m",Pn).call(this,{event:s,toolUseId:s.id,name:s.name,isError:!1,posted:!1,confirmation:e});return}let o,c,u=new AbortController,d=ve(a(this,K,"f").signal,u),m=setTimeout(()=>u.abort(),vc);try{let w=await To(i,s.input,{toolUse:s,toolUseBlock:s,signal:u.signal});o=w.content,c=w.isError}finally{clearTimeout(m),d()}let p=Mc(s,c,Oc(o)),f=await a(this,H,"m",No).call(this,p,s.id);a(this,H,"m",Pn).call(this,{event:s,result:p,toolUseId:s.id,name:s.name,isError:c,posted:f,confirmation:e})}finally{g(this,ye,(n=a(this,ye,"f"),n--,n),"f"),a(this,ye,"f")===0&&a(this,wr,"f")?.call(this)}}},No=async function(s,e){let t=a(this,K,"f"),n=Date.now(),i,o=0;for(;;){o++,t.signal.throwIfAborted();try{return await this.client.beta.sessions.events.send(this.sessionId,{events:[s]},a(this,H,"m",Rn).call(this)),a(this,te,"f").add(e),!0}catch(c){if(i=c,Fe(c))break;let u=a(this,Mn,"f")-(Date.now()-n);if(u<=0)break;let d=Math.min(gn(_n(o-1,Ec,Rc)),u);a(this,U,"f").warn("tool result send failed; retrying",{tool_use_id:e,attempt:o,backoff_ms:d,error:String(c)}),await le(d,t.signal)}}return a(this,U,"f").error("failed to send tool result",{tool_use_id:e,attempts:o,error:String(i)}),!1},Ho=async function(){a(this,ye,"f")!==0&&(await Promise.race([new Promise(s=>g(this,wr,s,"f")),le(Ac)]),g(this,wr,null,"f"),a(this,ye,"f")>0&&a(this,U,"f").warn("drain timeout exceeded"))};function Mc(r,s,e){return r.type==="agent.custom_tool_use"?{type:"user.custom_tool_result",custom_tool_use_id:r.id,is_error:s,content:e}:{type:"user.tool_result",tool_use_id:r.id,is_error:s,content:e}}function Oc(r){if(typeof r=="string")return[{type:"text",text:r||"(no output)"}];let s=r.map(e=>e.type==="text"?{type:"text",text:e.text||"(no output)"}:e.type==="image"||e.type==="document"?e:e.type==="search_result"?{type:"search_result",source:e.source,title:e.title,content:e.content.map(t=>({type:"text",text:t.text})),citations:{enabled:e.citations?.enabled??!1}}:{type:"text",text:JSON.stringify(e)});return s.length>0?s:[{type:"text",text:"(no output)"}]}var af=15e3,Bo=5e3;function Wo(r,s){if(!(r>=Bo))throw new k(`${s} must be at least ${Bo}ms (got ${r}); to run without memory sync, pass \`memorySyncIntervalMs: null\` to the worker instead`)}var On,yr,zs,kr,St,Uo=3e4,Cc=9e4,$c="NO_HEARTBEAT";function Nc(r){return r.resources.some(s=>s.type==="memory_store")}function Lc(r){if(!r)return null;let s;try{let t=r.replace(/-/g,"+").replace(/_/g,"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");s=JSON.parse(er(Ji(n)))}catch{return null}if(s===null||typeof s!="object"||Array.isArray(s))return null;let e=s.sessions_token;return typeof e=="string"&&e!==""?e:null}var Ks=(()=>{class r{constructor(e){if(On.add(this),yr.set(this,void 0),e.unrestrictedPaths!==void 0)throw new k("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&&Wo(e.memorySyncIntervalMs,"memorySyncIntervalMs"),this.memorySyncIntervalMs=e.memorySyncIntervalMs,this.memorySyncDeletions=e.memorySyncDeletions??"enabled",this.workerId=e.workerId,this.requestOptions=e.requestOptions,g(this,yr,e.signal,"f")}async run(e){let{environmentId:t,environmentKey:n}=this;if(t===void 0||n===void 0)throw new k("EnvironmentWorker.run: environmentId and environmentKey are required to poll for work");let i=e??a(this,yr,"f"),o=new mr({client:this.client,environmentId:t,environmentKey:n,...this.workerId!==void 0?{workerId:this.workerId}:{},...i?{signal:i}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},autoStop:!1});for await(let c of o)try{await a(this,On,"m",zs).call(this,c,n,o.signal)}catch(u){if(o.signal?.aborted)throw u;C(this.client).error("work item failed",{work_id:c.id,error:String(u)})}}async handleItem(e){let t=e?.workId??M("ANTHROPIC_WORK_ID"),n=e?.environmentId??M("ANTHROPIC_ENVIRONMENT_ID"),i=e?.sessionId??M("ANTHROPIC_SESSION_ID"),o=(e?.environmentKey??this.environmentKey??M("ANTHROPIC_ENVIRONMENT_KEY"))||void 0,c=e?.workSecret||M("ANTHROPIC_WORK_SECRET")||null;if(!t)throw new k("handleItem: workId is required \u2014 pass it or set ANTHROPIC_WORK_ID");if(!n)throw new k("handleItem: environmentId is required \u2014 pass it or set ANTHROPIC_ENVIRONMENT_ID");if(!i)throw new k("handleItem: sessionId is required \u2014 pass it or set ANTHROPIC_SESSION_ID");if(!o&&!c)throw new k("handleItem: environmentKey is required when there is no work secret \u2014 pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY");let u={id:t,environment_id:n,secret:c,data:{type:"session",id:i}};await a(this,On,"m",zs).call(this,u,o,e?.signal??a(this,yr,"f"))}}return yr=new WeakMap,On=new WeakSet,zs=async function(e,t,n){let i=C(this.client),o=Lc(e.secret),c=o??t;if(c===void 0)throw new k("handleItem: the work item carried a secret payload but no sessions token could be extracted, and there is no environment key to fall back to; the poller must issue a secret whose payload carries `sessions_token`, or provide the environment key (pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY)");e.secret&&o===null&&i.warn("work item carried a secret payload but no sessions token could be extracted; falling back to the environment key",{work_id:e.id});let u=wn(this.client,{authToken:c,helper:"environments-worker"}),d=e.data.id,m=new AbortController,p=ve(n,m),f=new Hc(m),w=await import("./node-BXYZKSJY.js"),_,v,A=Bc(u,e,f,i,this.requestOptions,x=>{_=x,v?._setSendRetryWindow(x)}).catch(x=>{m.signal.aborted||i.error("heartbeat loop failed",{work_id:e.id,error:String(x)}),m.abort()}),E=async()=>{},y,I=!1;try{if(e.data.type!=="session"){i.debug("skipping non-session work item",{work_id:e.id,type:e.data.type});return}let x=await u.beta.sessions.retrieve(d);if(o===null&&this.memorySyncIntervalMs!==null&&Nc(x))throw new w.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 R={workdir:this.workdir,client:u,session:x,...this.maxFileBytes!==void 0?{maxFileBytes:this.maxFileBytes}:{}};try{E=await w.setupSkills(R)}catch(T){i.warn("skill setup failed",{session_id:d,work_id:e.id,error:String(T)})}o!==null&&this.memorySyncIntervalMs!==null?(y=new w.SessionMemoryStores(u,{workdir:this.workdir,...this.memorySyncIntervalMs!==void 0?{syncIntervalMs:this.memorySyncIntervalMs}:{},syncDeletions:this.memorySyncDeletions}),await y.download(x),R.allowedRoots=y.roots,R.readOnlyRoots=y.readOnlyRoots):i.debug("memory stores disabled for this item",{work_id:e.id});let P=typeof this.tools=="function"?this.tools(R):this.tools??w.betaAgentToolset20260401(R);v=new br(d,{client:u,tools:P,...this.maxIdleMs!==void 0?{maxIdleMs:this.maxIdleMs}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},signal:m.signal}),_!==void 0&&v._setSendRetryWindow(_);for await(let T of v)y&&await y.syncIfDue();I=!m.signal.aborted}finally{try{await E().catch(x=>{i.warn("skill cleanup failed",{session_id:d,work_id:e.id,error:String(x)})})}finally{if(y){let x=w.MEMORY_FLUSH_TIMEOUT_MS;I&&await qo(y.finish(),x)&&i.warn(`final memory sync cut off after ${x}ms; the flush that follows still uploads changed files`,{session_id:d,work_id:e.id});let R=new AbortController;await qo(y.flushWrites(R.signal),x)&&(R.abort(),i.warn(`memory flush cut off after ${x}ms; changed files it had not uploaded yet are not saved`,{session_id:d,work_id:e.id})),await y.dispose().catch(T=>{i.warn("memory store cleanup failed",{session_id:d,work_id:e.id,error:String(T)})})}}f.finish("runner_done"),p(),await A,f.lost?i.info("lease lost; released without stopping it",{session_id:d,work_id:e.id}):await Fc(u,e,i,this.requestOptions)}},r})();async function qo(r,s){let e;try{return await Promise.race([r.then(()=>!1,()=>!1),new Promise(t=>{e=setTimeout(()=>t(!0),s)})])}finally{e!==void 0&&clearTimeout(e)}}async function Fc(r,s,e,t){try{await r.beta.environments.work.stop(s.id,{environment_id:s.environment_id,force:!0},{...t,headers:l([t?.headers])})}catch(n){Ae(n,409)||e.error("force-stop on exit failed",{work_id:s.id,error:String(n)})}}var Hc=(()=>{class r{constructor(e){kr.set(this,void 0),St.set(this,void 0),g(this,kr,e,"f")}get signal(){return a(this,kr,"f").signal}finish(e){g(this,St,a(this,St,"f")??e,"f"),a(this,kr,"f").abort()}get lost(){return a(this,St,"f")==="lease_lost"||a(this,St,"f")==="assumed_lost"}}return kr=new WeakMap,St=new WeakMap,r})();function Dc(r){let s=r instanceof F?r.error:void 0;for(let e of["error","details","current_state"]){if(!ps(s))return{};s=s[e]}return ps(s)?s:{}}async function Bc(r,s,e,t,n,i){let o=Uo,c=Cc,u=Date.now(),d=$c,m=async()=>{let p=new AbortController,f=ve(e.signal,p),w=setTimeout(()=>p.abort(),o);try{let _=await r.beta.environments.work.heartbeat(s.id,{environment_id:s.environment_id,expected_last_heartbeat:d},{...n,headers:l([n?.headers]),signal:p.signal});u=Date.now(),d=_.last_heartbeat,_.ttl_seconds>0&&(c=_.ttl_seconds*1e3,o=Math.max(1e3,Math.min(c/2,Uo)),i?.(c)),(_.state==="stopping"||_.state==="stopped")&&(t.info("heartbeat signals shutdown",{work_id:s.id,state:_.state}),e.finish("control_plane_stop")),_.lease_extended||(t.warn("lease not extended, shutting down",{work_id:s.id}),e.finish("control_plane_stop"))}catch(_){if(e.signal.throwIfAborted(),Ae(_,412)){let v=Dc(_);t.error("lease lost: heartbeat precondition failed",{work_id:s.id,server_state:v.state,server_ttl_seconds:v.ttl_seconds,server_last_heartbeat:v.last_heartbeat}),e.finish("lease_lost");return}if(Fe(_))throw t.error("permanent heartbeat failure",{work_id:s.id,error:String(_)}),e.finish("heartbeat_rejected"),_;if(Date.now()-u>c){t.error("lease assumed lost: no successful heartbeat in ttl",{work_id:s.id,ttl_ms:c,error:String(_)}),e.finish("assumed_lost");return}t.warn("transient heartbeat failure",{work_id:s.id,error:String(_)})}finally{clearTimeout(w),f()}};for(await m();!e.signal.aborted;)await le(o,e.signal),e.signal.throwIfAborted(),await m()}var Cn=(()=>{class r extends b{retrieve(e,t,n){let{environment_id:i,betas:o,workspace_id:c}=t;return this._client.get(h`/v1/environments/${i}/work/${e}?beta=true`,{...n,headers:l([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},n?.headers])})}update(e,t,n){let{environment_id:i,betas:o,workspace_id:c,...u}=t;return this._client.post(h`/v1/environments/${i}/work/${e}?beta=true`,{body:u,...n,headers:l([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},n?.headers])})}list(e,t={},n){let{betas:i,...o}=t??{};return this._client.getAPIList(h`/v1/environments/${e}/work?beta=true`,S,{query:o,...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}ack(e,t,n){let{environment_id:i,betas:o}=t;return this._client.post(h`/v1/environments/${i}/work/${e}/ack?beta=true`,{...n,headers:l([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}heartbeat(e,t,n){let{environment_id:i,desired_ttl_seconds:o,expected_last_heartbeat:c,betas:u}=t;return this._client.post(h`/v1/environments/${i}/work/${e}/heartbeat?beta=true`,{query:{desired_ttl_seconds:o,expected_last_heartbeat:c},...n,headers:l([{"anthropic-beta":[...u??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}poll(e,t={},n){let{betas:i,"Anthropic-Worker-ID":o,...c}=t??{};return this._client.get(h`/v1/environments/${e}/work/poll?beta=true`,{query:c,...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"Anthropic-Worker-ID":o}:void 0},n?.headers])})}stats(e,t={},n){let{betas:i,workspace_id:o}=t??{};return this._client.get(h`/v1/environments/${e}/work/stats?beta=true`,{...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}stop(e,t,n){let{environment_id:i,betas:o,workspace_id:c,...u}=t;return this._client.post(h`/v1/environments/${i}/work/${e}/stop?beta=true`,{body:u,...n,headers:l([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},n?.headers])})}poller(e){return new mr({...e,client:this._client})}worker(e){return new Ks({...e,client:this._client})}}return r.WorkPoller=mr,r.EnvironmentWorker=Ks,r})();var $n=(()=>{class r extends b{constructor(){super(...arguments),this.work=new Cn(this._client)}create(e,t){let{betas:n,workspace_id:i,...o}=e;return this._client.post("/v1/environments?beta=true",{body:o,...t,headers:l([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}retrieve(e,t={},n){let{betas:i,workspace_id:o}=t??{};return this._client.get(h`/v1/environments/${e}?beta=true`,{...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}update(e,t,n){let{betas:i,workspace_id:o,...c}=t;return this._client.post(h`/v1/environments/${e}?beta=true`,{body:c,...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}list(e={},t){let{betas:n,workspace_id:i,...o}=e??{};return this._client.getAPIList("/v1/environments?beta=true",S,{query:o,...t,headers:l([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}delete(e,t={},n){let{betas:i,workspace_id:o}=t??{};return this._client.delete(h`/v1/environments/${e}?beta=true`,{...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}archive(e,t={},n){let{betas:i,workspace_id:o}=t??{};return this._client.post(h`/v1/environments/${e}/archive?beta=true`,{...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}}return r.Work=Cn,r})();var xt=class extends b{create(s,e,t){let{view:n,betas:i,workspace_id:o,...c}=e;return this._client.post(h`/v1/memory_stores/${s}/memories?beta=true`,{query:{view:n},body:c,...t,headers:l([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},t?.headers])})}retrieve(s,e,t){let{memory_store_id:n,betas:i,workspace_id:o,...c}=e;return this._client.get(h`/v1/memory_stores/${n}/memories/${s}?beta=true`,{query:c,...t,headers:l([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},t?.headers])})}update(s,e,t){let{memory_store_id:n,view:i,betas:o,workspace_id:c,...u}=e;return this._client.post(h`/v1/memory_stores/${n}/memories/${s}?beta=true`,{query:{view:i},body:u,...t,headers:l([{"anthropic-beta":[...o??[],"agent-memory-2026-07-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}list(s,e={},t){let{betas:n,workspace_id:i,...o}=e??{};return this._client.getAPIList(h`/v1/memory_stores/${s}/memories?beta=true`,S,{query:o,...t,headers:l([{"anthropic-beta":[...n??[],"agent-memory-2026-07-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}delete(s,e,t){let{memory_store_id:n,expected_content_sha256:i,betas:o,workspace_id:c}=e;return this._client.delete(h`/v1/memory_stores/${n}/memories/${s}?beta=true`,{query:{expected_content_sha256:i},...t,headers:l([{"anthropic-beta":[...o??[],"agent-memory-2026-07-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}};var vt=class extends b{retrieve(s,e,t){let{memory_store_id:n,betas:i,workspace_id:o,...c}=e;return this._client.get(h`/v1/memory_stores/${n}/memory_versions/${s}?beta=true`,{query:c,...t,headers:l([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},t?.headers])})}list(s,e={},t){let{betas:n,workspace_id:i,...o}=e??{};return this._client.getAPIList(h`/v1/memory_stores/${s}/memory_versions?beta=true`,S,{query:o,...t,headers:l([{"anthropic-beta":[...n??[],"agent-memory-2026-07-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}redact(s,e,t){let{memory_store_id:n,betas:i,workspace_id:o}=e;return this._client.post(h`/v1/memory_stores/${n}/memory_versions/${s}/redact?beta=true`,{...t,headers:l([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},t?.headers])})}};var Nn=(()=>{class r extends b{constructor(){super(...arguments),this.memories=new xt(this._client),this.memoryVersions=new vt(this._client)}create(e,t){let{betas:n,workspace_id:i,...o}=e;return this._client.post("/v1/memory_stores?beta=true",{body:o,...t,headers:l([{"anthropic-beta":[...n??[],"agent-memory-2026-07-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}retrieve(e,t={},n){let{betas:i,workspace_id:o}=t??{};return this._client.get(h`/v1/memory_stores/${e}?beta=true`,{...n,headers:l([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}update(e,t,n){let{betas:i,workspace_id:o,...c}=t;return this._client.post(h`/v1/memory_stores/${e}?beta=true`,{body:c,...n,headers:l([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}list(e={},t){let{betas:n,workspace_id:i,...o}=e??{};return this._client.getAPIList("/v1/memory_stores?beta=true",S,{query:o,...t,headers:l([{"anthropic-beta":[...n??[],"agent-memory-2026-07-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}delete(e,t={},n){let{betas:i,workspace_id:o}=t??{};return this._client.delete(h`/v1/memory_stores/${e}?beta=true`,{...n,headers:l([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}archive(e,t={},n){let{betas:i,workspace_id:o}=t??{};return this._client.post(h`/v1/memory_stores/${e}/archive?beta=true`,{...n,headers:l([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}}return r.Memories=xt,r.MemoryVersions=vt,r})();var Ln=(()=>{class r{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new nr;for await(let t of this.iterator)for(let n of e.decode(t))yield JSON.parse(n);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 k("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 k("Attempted to iterate over a response with no body");return new r(Qt(e.body),t)}}return r})();var At=class extends b{create(s,e){let{betas:t,user_profile_id:n,workspace_id:i,...o}=s;return this._client.post("/v1/messages/batches?beta=true",{body:o,...e,headers:l([{"anthropic-beta":[...t??[],"message-batches-2024-09-24"].toString(),...n!=null?{"anthropic-user-profile-id":n}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},e?.headers])})}retrieve(s,e={},t){let{betas:n,workspace_id:i}=e??{};return this._client.get(h`/v1/messages/batches/${s}?beta=true`,{...t,headers:l([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}list(s={},e){let{betas:t,workspace_id:n,...i}=s??{};return this._client.getAPIList("/v1/messages/batches?beta=true",B,{query:i,...e,headers:l([{"anthropic-beta":[...t??[],"message-batches-2024-09-24"].toString(),...n!=null?{"anthropic-workspace-id":n}:void 0},e?.headers])})}delete(s,e={},t){let{betas:n,workspace_id:i}=e??{};return this._client.delete(h`/v1/messages/batches/${s}?beta=true`,{...t,headers:l([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}cancel(s,e={},t){let{betas:n,workspace_id:i}=e??{};return this._client.post(h`/v1/messages/batches/${s}/cancel?beta=true`,{...t,headers:l([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}async results(s,e={},t){let n=await this.retrieve(s,e,t);if(!n.results_url)throw new k(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);let{betas:i,workspace_id:o}=e??{};return this._client.get(n.results_url,{...t,headers:l([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...o!=null?{"anthropic-workspace-id":o}:void 0},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((c,u)=>Ln.fromResponse(u.response,u.controller))}};var Fn={"claude-opus-4@20250514":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function jo(r){return r?.output_format??r?.output_config?.format}function Vs(r,s,e){let t=jo(s);return!s||!("parse"in(t??{}))?{...r,content:r.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 e.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return n}),parsed_output:null}:Js(r,s,e)}function Js(r,s,e){let t=null,n=r.content.map(i=>{if(i.type==="text"){let o=Vc(s,i.text);t===null&&(t=o);let c=Object.defineProperty({...i},"parsed_output",{value:o,enumerable:!1});return Object.defineProperty(c,"parsed",{get(){return e.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),o},enumerable:!1})}return i});return{...r,content:n,parsed_output:t}}function Vc(r,s){let e=jo(r);if(e?.type!=="json_schema")return null;try{return"parse"in e?e.parse(s):JSON.parse(s)}catch(t){throw new k(`Failed to parse structured output: ${t}`)}}var Jc=r=>{let s=0,e=[];for(;s<r.length;){let t=r[s];if(t==="\\"){s++;continue}if(t==="{"){e.push({type:"brace",value:"{"}),s++;continue}if(t==="}"){e.push({type:"brace",value:"}"}),s++;continue}if(t==="["){e.push({type:"paren",value:"["}),s++;continue}if(t==="]"){e.push({type:"paren",value:"]"}),s++;continue}if(t===":"){e.push({type:"separator",value:":"}),s++;continue}if(t===","){e.push({type:"delimiter",value:","}),s++;continue}if(t==='"'){let c="",u=!1;for(t=r[++s];t!=='"';){if(s===r.length){u=!0;break}if(t==="\\"){if(s++,s===r.length){u=!0;break}c+=t+r[s],t=r[++s]}else c+=t,t=r[++s]}t=r[++s],u||e.push({type:"string",value:c});continue}if(t&&/\s/.test(t)){s++;continue}let i=/[0-9]/;if(t&&i.test(t)||t==="-"||t==="."){let c="";for(t==="-"&&(c+=t,t=r[++s]);t&&(i.test(t)||t==="."||t==="e"||t==="E"||(t==="-"||t==="+")&&(c[c.length-1]==="e"||c[c.length-1]==="E"));)c+=t,t=r[++s];e.push({type:"number",value:c});continue}let o=/[a-z]/i;if(t&&o.test(t)){let c="";for(;t&&o.test(t)&&s!==r.length;)c+=t,t=r[++s];if(c=="true"||c=="false"||c==="null")e.push({type:"name",value:c});else{s++;continue}continue}s++}return e},Et=r=>{if(r.length===0)return r;let s=r[r.length-1];switch(s.type){case"separator":return r=r.slice(0,r.length-1),Et(r);break;case"number":let e=s.value[s.value.length-1];if(e==="."||e==="-"||e==="+"||e==="e"||e==="E")return r=r.slice(0,r.length-1),Et(r);case"string":let t=r[r.length-2];if(t?.type==="delimiter")return r=r.slice(0,r.length-1),Et(r);if(t?.type==="brace"&&t.value==="{")return r=r.slice(0,r.length-1),Et(r);break;case"delimiter":return r=r.slice(0,r.length-1),Et(r);break}return r},Yc=r=>{let s=[];return r.map(e=>{e.type==="brace"&&(e.value==="{"?s.push("}"):s.splice(s.lastIndexOf("}"),1)),e.type==="paren"&&(e.value==="["?s.push("]"):s.splice(s.lastIndexOf("]"),1))}),s.length>0&&s.reverse().map(e=>{e==="}"?r.push({type:"brace",value:"}"}):e==="]"&&r.push({type:"paren",value:"]"})}),r},Xc=r=>{let s="";return r.map(e=>{e.type==="string"?s+='"'+e.value+'"':s+=e.value}),s},zo=r=>JSON.parse(Xc(Yc(Et(Jc(r)))));var Ie="__json_buf";function Hn(r,s){let e={};for(let i of Object.keys(r))i!=="input"&&(e[i]=r[i]);Object.defineProperty(e,Ie,{value:s,enumerable:!1,writable:!0});let t,n=!1;return Object.defineProperty(e,"input",{enumerable:!0,configurable:!0,get(){return n||(t=s?zo(s):{},n=!0),t}}),e}var Y,Pe,Rt,Sr,Dn,xr,vr,Bn,Ar,we,Er,Wn,Un,De,qn,jn,zn,Rr,Ys,Ko,Ir,Xs,Gs,Qs,Vo,Zs;function ei(r){return r.type==="tool_use"||r.type==="server_tool_use"||r.type==="mcp_tool_use"}var Jo=(()=>{class r{constructor(e,t){Y.add(this),this.messages=[],this.receivedMessages=[],Pe.set(this,void 0),Rt.set(this,null),this.controller=new AbortController,Sr.set(this,void 0),Dn.set(this,()=>{}),xr.set(this,()=>{}),vr.set(this,void 0),Bn.set(this,()=>{}),Ar.set(this,()=>{}),we.set(this,{}),Er.set(this,!1),Wn.set(this,!1),Un.set(this,!1),De.set(this,!1),qn.set(this,void 0),jn.set(this,void 0),zn.set(this,void 0),Rr.set(this,void 0),Ir.set(this,n=>{if(g(this,Wn,!0,"f"),G(n)&&(n=new z),n instanceof z)return g(this,Un,!0,"f"),this._emit("abort",n);if(n instanceof k)return this._emit("error",n);if(n instanceof Error){let i=new k(n.message);return i.cause=n,this._emit("error",i)}return this._emit("error",new k(String(n)))}),g(this,Sr,new Promise((n,i)=>{g(this,Dn,n,"f"),g(this,xr,i,"f")}),"f"),g(this,vr,new Promise((n,i)=>{g(this,Bn,n,"f"),g(this,Ar,i,"f")}),"f"),a(this,Sr,"f").catch(()=>{}),a(this,vr,"f").catch(()=>{}),g(this,Rt,e,"f"),g(this,Rr,t?.logger??console,"f")}get response(){return a(this,qn,"f")}get request_id(){return a(this,jn,"f")}get workspace_id(){return a(this,zn,"f")}async withResponse(){g(this,De,!0,"f");let e=await a(this,Sr,"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 r(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n,{logger:i}={}){let o=new r(t,{logger:i});for(let c of t.messages)o._addMessageParam(c);return g(o,Rt,{...t,stream:!0},"f"),o._run(()=>o._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,[dn]:"stream"}})),o}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},a(this,Ir,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){let i=n?.signal,o;i&&(i.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),i.addEventListener("abort",o));try{a(this,Y,"m",Xs).call(this);let{response:c,data:u}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(c);for await(let d of u)a(this,Y,"m",Gs).call(this,d);if(u.controller.signal?.aborted)throw new z;a(this,Y,"m",Qs).call(this)}finally{i&&o&&i.removeEventListener("abort",o)}}_connected(e){this.ended||(g(this,qn,e,"f"),g(this,jn,e?.headers.get("request-id"),"f"),g(this,zn,e?.headers.get("anthropic-workspace-id"),"f"),a(this,Dn,"f").call(this,e),this._emit("connect"))}get ended(){return a(this,Er,"f")}get errored(){return a(this,Wn,"f")}get aborted(){return a(this,Un,"f")}abort(){this.controller.abort()}on(e,t){return(a(this,we,"f")[e]||(a(this,we,"f")[e]=[])).push({listener:t}),this}off(e,t){let n=a(this,we,"f")[e];if(!n)return this;let i=n.findIndex(o=>o.listener===t);return i>=0&&n.splice(i,1),this}once(e,t){return(a(this,we,"f")[e]||(a(this,we,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{g(this,De,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){g(this,De,!0,"f"),await a(this,vr,"f")}get currentMessage(){return a(this,Pe,"f")}async finalMessage(){return await this.done(),a(this,Y,"m",Ys).call(this)}async finalText(){return await this.done(),a(this,Y,"m",Ko).call(this)}_emit(e,...t){if(a(this,Er,"f"))return;e==="end"&&(g(this,Er,!0,"f"),a(this,Bn,"f").call(this));let n=a(this,we,"f")[e];if(n&&(a(this,we,"f")[e]=n.filter(i=>!i.once),n.forEach(({listener:i})=>i(...t))),e==="abort"){let i=t[0];!a(this,De,"f")&&!n?.length&&Promise.reject(i),a(this,xr,"f").call(this,i),a(this,Ar,"f").call(this,i),this._emit("end");return}if(e==="error"){let i=t[0];!a(this,De,"f")&&!n?.length&&Promise.reject(i),a(this,xr,"f").call(this,i),a(this,Ar,"f").call(this,i),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",a(this,Y,"m",Ys).call(this))}async _fromReadableStream(e,t){let n=t?.signal,i;n&&(n.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),n.addEventListener("abort",i));try{a(this,Y,"m",Xs).call(this),this._connected(null);let o=se.fromReadableStream(e,this.controller);for await(let c of o)a(this,Y,"m",Gs).call(this,c);if(o.controller.signal?.aborted)throw new z;a(this,Y,"m",Qs).call(this)}finally{n&&i&&n.removeEventListener("abort",i)}}[(Pe=new WeakMap,Rt=new WeakMap,Sr=new WeakMap,Dn=new WeakMap,xr=new WeakMap,vr=new WeakMap,Bn=new WeakMap,Ar=new WeakMap,we=new WeakMap,Er=new WeakMap,Wn=new WeakMap,Un=new WeakMap,De=new WeakMap,qn=new WeakMap,jn=new WeakMap,zn=new WeakMap,Rr=new WeakMap,Ir=new WeakMap,Y=new WeakSet,Ys=function(){if(this.receivedMessages.length===0)throw new k("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Ko=function(){if(this.receivedMessages.length===0)throw new k("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new k("stream ended without producing a content block with type=text");return t.join(" ")},Xs=function(){this.ended||g(this,Pe,void 0,"f")},Gs=function(t){if(this.ended)return;let n=a(this,Y,"m",Vo).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{let i=n.content.at(-1);switch(t.delta.type){case"text_delta":{i.type==="text"&&this._emit("text",t.delta.text,i.text||"");break}case"citations_delta":{i.type==="text"&&this._emit("citation",t.delta.citation,i.citations??[]);break}case"input_json_delta":{if(ei(i)&&a(this,we,"f").inputJson?.length){let o;try{o=i.input}catch(c){a(this,Ir,"f").call(this,a(this,Y,"m",Zs).call(this,i,c));break}this._emit("inputJson",t.delta.partial_json,o)}break}case"thinking_delta":{i.type==="thinking"&&this._emit("thinking",t.delta.thinking,i.thinking);break}case"signature_delta":{i.type==="thinking"&&this._emit("signature",i.signature);break}case"compaction_delta":{i.type==="compaction"&&i.content&&this._emit("compaction",i.content);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(Vs(n,a(this,Rt,"f"),{logger:a(this,Rr,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{g(this,Pe,n,"f");break}case"content_block_start":case"message_delta":break}},Qs=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");let t=a(this,Pe,"f");if(!t)throw new k("request ended without sending any chunks");return g(this,Pe,void 0,"f"),Vs(t,a(this,Rt,"f"),{logger:a(this,Rr,"f")})},Vo=function(t){let n=a(this,Pe,"f");if(t.type==="message_start"){if(n)throw new k(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new k(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.stop_details=t.delta.stop_details,n.usage.output_tokens=t.usage.output_tokens,t.delta.container!=null&&(n.container=t.delta.container),t.context_management!=null&&(n.context_management=t.context_management),t.input_transformations!=null&&(n.input_transformations=t.input_transformations),t.usage.input_tokens!=null&&(n.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(n.usage.server_tool_use=t.usage.server_tool_use),t.usage.iterations!=null&&(n.usage.iterations=t.usage.iterations),t.usage.fallback_credit!=null&&(n.usage.fallback_credit=t.usage.fallback_credit),t.usage.output_tokens_details!=null&&(n.usage.output_tokens_details=t.usage.output_tokens_details),n;case"content_block_start":return n.content.push(t.content_block),t.content_block.type==="fallback"&&(n.model=t.content_block.to.model),n;case"content_block_delta":{let i=n.content.at(t.index);switch(t.delta.type){case"text_delta":{i?.type==="text"&&(n.content[t.index]={...i,text:(i.text||"")+t.delta.text});break}case"citations_delta":{i?.type==="text"&&(n.content[t.index]={...i,citations:[...i.citations??[],t.delta.citation]});break}case"input_json_delta":{if(i&&ei(i)){let o=(i[Ie]||"")+t.delta.partial_json;n.content[t.index]=Hn(i,o)}break}case"thinking_delta":{i?.type==="thinking"&&(n.content[t.index]={...i,thinking:i.thinking+t.delta.thinking});break}case"signature_delta":{i?.type==="thinking"&&(n.content[t.index]={...i,signature:t.delta.signature});break}case"compaction_delta":{i?.type==="compaction"&&(n.content[t.index]={...i,content:(i.content||"")+t.delta.content,encrypted_content:t.delta.encrypted_content});break}default:t.delta}return n}case"content_block_stop":{let i=n.content.at(t.index);if(i&&ei(i)&&Ie in i){let o;try{o=i.input}catch(c){o={},a(this,Ir,"f").call(this,a(this,Y,"m",Zs).call(this,i,c))}Object.defineProperty(i,"input",{value:o,enumerable:!0,configurable:!0,writable:!0})}return n}}},Zs=function(t,n){let i=t[Ie];return new k(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${n}. JSON: ${i}`)},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("streamEvent",i=>{let o=t.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{n=!0;for(let o of t)o.reject(i);t.length=0}),this.on("error",i=>{n=!0;for(let o of t)o.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,c)=>t.push({resolve:o,reject:c})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new se(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}return r})();function ti(){let r,s;return{promise:new Promise((t,n)=>{r=t,s=n}),resolve:r,reject:s}}var Yo=`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:
|
|
10
|
+
1. Task Overview
|
|
11
|
+
The user's core request and success criteria
|
|
12
|
+
Any clarifications or constraints they specified
|
|
13
|
+
2. Current State
|
|
14
|
+
What has been completed so far
|
|
15
|
+
Files created, modified, or analyzed (with paths if relevant)
|
|
16
|
+
Key outputs or artifacts produced
|
|
17
|
+
3. Important Discoveries
|
|
18
|
+
Technical constraints or requirements uncovered
|
|
19
|
+
Decisions made and their rationale
|
|
20
|
+
Errors encountered and how they were resolved
|
|
21
|
+
What approaches were tried that didn't work (and why)
|
|
22
|
+
4. Next Steps
|
|
23
|
+
Specific actions needed to complete the task
|
|
24
|
+
Any blockers or open questions to resolve
|
|
25
|
+
Priority order if multiple steps remain
|
|
26
|
+
5. Context to Preserve
|
|
27
|
+
User preferences or style requirements
|
|
28
|
+
Domain-specific details that aren't obvious
|
|
29
|
+
Any promises made to the user
|
|
30
|
+
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.
|
|
31
|
+
Wrap your summary in <summary></summary> tags.`;var Pr,It,Be,D,X,re,ke,Te,Tr,Xo,ri,ni=(()=>{class r{constructor(e,t,n){Pr.add(this),this.client=e,It.set(this,!1),Be.set(this,!1),D.set(this,void 0),X.set(this,void 0),re.set(this,void 0),ke.set(this,void 0),Te.set(this,void 0),Tr.set(this,0),g(this,D,{params:{...t,messages:structuredClone(t.messages)}},"f");let i=Hs(t.tools,t.messages);g(this,X,{...n,headers:l([dr("BetaToolRunner"),i.length?{[ge]:i.join(", ")}:void 0,n?.headers])},"f"),g(this,Te,ti(),"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*[(It=new WeakMap,Be=new WeakMap,D=new WeakMap,X=new WeakMap,re=new WeakMap,ke=new WeakMap,Te=new WeakMap,Tr=new WeakMap,Pr=new WeakSet,Xo=async function(){let t=a(this,D,"f").params.compactionControl;if(!t||!t.enabled)return!1;let n=0;if(a(this,re,"f")!==void 0)try{let m=await a(this,re,"f");n=m.usage.input_tokens+(m.usage.cache_creation_input_tokens??0)+(m.usage.cache_read_input_tokens??0)+m.usage.output_tokens}catch{return!1}let i=t.contextTokenThreshold??1e5;if(n<i)return!1;let o=t.model??a(this,D,"f").params.model,c=t.summaryPrompt??Yo,u=a(this,D,"f").params.messages;if(u[u.length-1].role==="assistant"){let m=u[u.length-1];if(Array.isArray(m.content)){let p=m.content.filter(f=>f.type!=="tool_use");p.length===0?u.pop():m.content=p}}let d=await this.client.beta.messages.create({model:o,messages:[...u,{role:"user",content:[{type:"text",text:c}]}],max_tokens:a(this,D,"f").params.max_tokens},{signal:a(this,X,"f").signal,headers:l([a(this,X,"f").headers,dr("compaction")])});if(d.content[0]?.type!=="text")throw new k("Expected text response for compaction");return a(this,D,"f").params.messages=[{role:"user",content:d.content}],!0},Symbol.asyncIterator)](){var e;if(a(this,It,"f"))throw new k("Cannot iterate over a consumed stream");g(this,It,!0,"f"),g(this,Be,!0,"f"),g(this,ke,void 0,"f");try{for(;;){let t;try{if(a(this,D,"f").params.max_iterations&&a(this,Tr,"f")>=a(this,D,"f").params.max_iterations)break;g(this,Be,!1,"f"),g(this,ke,void 0,"f"),g(this,Tr,(e=a(this,Tr,"f"),e++,e),"f"),g(this,re,void 0,"f");let{max_iterations:n,compactionControl:i,...o}=a(this,D,"f").params;if(o.stream?(t=this.client.beta.messages.stream({...o},a(this,X,"f")),g(this,re,t.finalMessage(),"f"),a(this,re,"f").catch(()=>{}),yield t):(g(this,re,this.client.beta.messages.create({...o,stream:!1},a(this,X,"f")),"f"),yield a(this,re,"f")),!await a(this,Pr,"m",Xo).call(this)){if(!a(this,Be,"f")){let d=await a(this,re,"f"),m=sl(d.stop_reason);a(this,D,"f").params.messages.push({role:d.role,content:d.content});let{container:p}=a(this,D,"f").params;if(d.container&&(p==null?a(this,D,"f").params.container=d.container.id:typeof p=="object"&&p.id==null&&(a(this,D,"f").params.container={...p,id:d.container.id})),m==="stop")break;if(m==="resume")continue}let u=await a(this,Pr,"m",ri).call(this,a(this,D,"f").params.messages.at(-1));if(u)a(this,D,"f").params.messages.push(u);else if(!a(this,Be,"f"))break}}finally{t&&t.abort()}}if(!a(this,re,"f"))throw new k("ToolRunner concluded without a message from the server");a(this,Te,"f").resolve(await a(this,re,"f"))}catch(t){throw g(this,It,!1,"f"),a(this,Te,"f").promise.catch(()=>{}),a(this,Te,"f").reject(t),g(this,Te,ti(),"f"),t}}setMessagesParams(e){typeof e=="function"?a(this,D,"f").params=e(a(this,D,"f").params):a(this,D,"f").params=e,g(this,Be,!0,"f"),g(this,ke,void 0,"f")}setRequestOptions(e){typeof e=="function"?g(this,X,e(a(this,X,"f")),"f"):g(this,X,{...a(this,X,"f"),...e},"f")}async generateToolResponse(e=a(this,X,"f").signal){let t=await a(this,re,"f")??this.params.messages.at(-1);return t?a(this,Pr,"m",ri).call(this,t,e):null}done(){return a(this,Te,"f").promise}async runUntilDone(){if(!a(this,It,"f"))for await(let e of this);return this.done()}get params(){return a(this,D,"f").params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}}return ri=async function(e,t=a(this,X,"f").signal){return a(this,ke,"f")!==void 0?a(this,ke,"f"):(g(this,ke,Qc(a(this,D,"f").params,e,{...a(this,X,"f"),signal:t}),"f"),a(this,ke,"f"))},r})();async function Qc(r,s=r.messages.at(-1),e){if(!s||s.role!=="assistant"||!s.content||typeof s.content=="string")return null;let t=s.content.filter(o=>o.type==="tool_use");if(t.length===0)return null;let n=el(r);return{role:"user",content:await Promise.all(t.map(async o=>{let c=r.tools.find(u=>("name"in u?u.name:"mcp_server_name"in u?u.mcp_server_name:u.type)===o.name);if(!c||!("run"in c)||!n.has(o.name))return Zc(o);try{let u=o.input;"parse"in c&&c.parse&&(u=c.parse(u));let d=await c.run(u,{toolUse:o,toolUseBlock:o,signal:e?.signal});return{type:"tool_result",tool_use_id:o.id,content:d}}catch(u){return{type:"tool_result",tool_use_id:o.id,content:u instanceof gt?u.content:`Error: ${u instanceof Error?u.message:String(u)}`,is_error:!0}}}))}}function Zc(r){return{type:"tool_result",tool_use_id:r.id,content:`Error: Tool '${r.name}' not found`,is_error:!0}}function el(r){let s=new Set;for(let e of r.tools)"run"in e&&s.add(e.name);for(let e of r.messages)if(!(e.role!=="system"||typeof e.content=="string"))for(let t of e.content)tl(t,s);return s}function tl(r,s){switch(r.type){case"tool_removal":case"tool_addition":rl(r,s);break}}function rl(r,s){let e=nl(r.tool);e!==void 0&&(r.type==="tool_removal"?s.delete(e):s.add(e))}function nl(r){if(r.type==="tool_reference")return r.name}function sl(r){if(r===null)return"stop";switch(r){case"tool_use":return"run_tools";case"pause_turn":case"compaction":return"resume";case"end_turn":case"stop_sequence":case"max_tokens":case"model_context_window_exceeded":case"refusal":return"stop";default:return"stop"}}var Go={},il=["claude-mythos-preview","claude-opus-4-6"],Kn=(()=>{class r extends b{constructor(){super(...arguments),this.batches=new At(this._client)}create(e,t){let n=Qo(e),{betas:i,user_profile_id:o,workspace_id:c,...u}=n;u.model in Go&&console.warn(`The model '${u.model}' is deprecated and will reach end-of-life on ${Go[u.model]}
|
|
32
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),il.includes(u.model)&&u.thinking&&u.thinking.type==="enabled"&&console.warn(`Using Claude with ${u.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let d=t?.timeout??this._client._options.timeout;if(!u.stream&&d==null){let p=Fn[u.model]??void 0;d=this._client.calculateNonstreamingTimeout(u.max_tokens,p)}let m=un(u.tools,u.messages);return this._client.post("/v1/messages?beta=true",{body:u,timeout:d??6e5,...t,headers:l([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...o!=null?{"anthropic-user-profile-id":o}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},m,t?.headers]),stream:n.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(n=>Js(n,e,{logger:this._client.logger??console}))}stream(e,t){return Jo.createMessage(this,e,t)}countTokens(e,t){let n=Qo(e),{betas:i,user_profile_id:o,workspace_id:c,...u}=n;return this._client.post("/v1/messages/count_tokens?beta=true",{body:u,...t,headers:l([{"anthropic-beta":[...i??[],"token-counting-2024-11-01"].toString(),...o!=null?{"anthropic-user-profile-id":o}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},t?.headers])})}toolRunner(e,t){return new ni(this._client,e,t)}}return r.Batches=At,r.BetaToolRunner=ni,r.ToolError=gt,r})();function Qo(r){if(!r.output_format)return r;if(r.output_config?.format)throw new k("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:s,...e}=r;return{...e,output_config:{...r.output_config,format:s}}}var Pt=class extends b{retrieve(s,e){return this._client.get(h`/v1/organizations/api_keys/${s}?beta=true`,e)}update(s,e,t){return this._client.post(h`/v1/organizations/api_keys/${s}?beta=true`,{body:e,...t})}list(s={},e){return this._client.getAPIList("/v1/organizations/api_keys?beta=true",B,{query:s,...e})}};var Tt=class extends b{retrieve(s){return this._client.get("/v1/organizations/compliance_settings?beta=true",s)}update(s,e){return this._client.post("/v1/organizations/compliance_settings?beta=true",{body:s,...e})}};var Mt=class extends b{create(s,e){return this._client.post("/v1/organizations/external_keys?beta=true",{body:s,...e})}retrieve(s,e){return this._client.get(h`/v1/organizations/external_keys/${s}?beta=true`,e)}update(s,e,t){return this._client.post(h`/v1/organizations/external_keys/${s}?beta=true`,{body:e,...t})}list(s={},e){return this._client.getAPIList("/v1/organizations/external_keys?beta=true",S,{query:s,...e})}delete(s,e){return this._client.delete(h`/v1/organizations/external_keys/${s}?beta=true`,e)}validate(s,e){return this._client.post(h`/v1/organizations/external_keys/${s}/validate?beta=true`,e)}};var Ot=class extends b{create(s,e){return this._client.post("/v1/organizations/invites?beta=true",{body:s,...e})}retrieve(s,e){return this._client.get(h`/v1/organizations/invites/${s}?beta=true`,e)}list(s={},e){return this._client.getAPIList("/v1/organizations/invites?beta=true",B,{query:s,...e})}delete(s,e){return this._client.delete(h`/v1/organizations/invites/${s}?beta=true`,e)}};var Ct=class extends b{list(s={},e){return this._client.getAPIList("/v1/organizations/rate_limits?beta=true",S,{query:s,...e})}};var $t=class extends b{retrieve(s,e){return this._client.get(h`/v1/organizations/users/${s}?beta=true`,e)}update(s,e,t){return this._client.post(h`/v1/organizations/users/${s}?beta=true`,{body:e,...t})}list(s={},e){return this._client.getAPIList("/v1/organizations/users?beta=true",B,{query:s,...e})}remove(s,e){return this._client.delete(h`/v1/organizations/users/${s}?beta=true`,e)}};var Nt=class extends b{create(s,e){let{betas:t,...n}=s;return this._client.post("/v1/organizations/federation_issuers?beta=true",{body:n,...e,headers:l([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0},e?.headers])})}retrieve(s,e={},t){let{betas:n}=e??{};return this._client.get(h`/v1/organizations/federation_issuers/${s}?beta=true`,{...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}update(s,e,t){let{betas:n,...i}=e;return this._client.post(h`/v1/organizations/federation_issuers/${s}?beta=true`,{body:i,...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}list(s={},e){let{betas:t,...n}=s??{};return this._client.getAPIList("/v1/organizations/federation_issuers?beta=true",S,{query:n,...e,headers:l([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0},e?.headers])})}archive(s,e={},t){let{betas:n}=e??{};return this._client.post(h`/v1/organizations/federation_issuers/${s}/archive?beta=true`,{...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}};var Lt=class extends b{list(s,e={},t){let{betas:n,...i}=e??{};return this._client.getAPIList(h`/v1/organizations/federation_rules/${s}/workspaces?beta=true`,S,{query:i,...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}add(s,e,t){let{betas:n,...i}=e;return this._client.post(h`/v1/organizations/federation_rules/${s}/workspaces?beta=true`,{body:i,...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}remove(s,e,t){let{federation_rule_id:n,betas:i}=e;return this._client.delete(h`/v1/organizations/federation_rules/${n}/workspaces/${s}?beta=true`,{...t,headers:l([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},t?.headers])})}};var Vn=(()=>{class r extends b{constructor(){super(...arguments),this.workspaces=new Lt(this._client)}create(e,t){let{betas:n,...i}=e;return this._client.post("/v1/organizations/federation_rules?beta=true",{body:i,...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}retrieve(e,t={},n){let{betas:i}=t??{};return this._client.get(h`/v1/organizations/federation_rules/${e}?beta=true`,{...n,headers:l([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},n?.headers])})}update(e,t,n){let{betas:i,...o}=t;return this._client.post(h`/v1/organizations/federation_rules/${e}?beta=true`,{body:o,...n,headers:l([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},n?.headers])})}list(e={},t){let{betas:n,...i}=e??{};return this._client.getAPIList("/v1/organizations/federation_rules?beta=true",S,{query:i,...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}archive(e,t={},n){let{betas:i}=t??{};return this._client.post(h`/v1/organizations/federation_rules/${e}/archive?beta=true`,{...n,headers:l([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},n?.headers])})}}return r.Workspaces=Lt,r})();var Jn=(()=>{class r extends b{constructor(){super(...arguments),this.issuers=new Nt(this._client),this.rules=new Vn(this._client)}}return r.Issuers=Nt,r.Rules=Vn,r})();var Ft=class extends b{list(s,e={},t){let{betas:n,...i}=e??{};return this._client.getAPIList(h`/v1/organizations/service_accounts/${s}/workspaces?beta=true`,S,{query:i,...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}add(s,e,t){let{betas:n,...i}=e;return this._client.post(h`/v1/organizations/service_accounts/${s}/workspaces?beta=true`,{body:i,...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}remove(s,e,t){let{service_account_id:n,betas:i}=e;return this._client.delete(h`/v1/organizations/service_accounts/${n}/workspaces/${s}?beta=true`,{...t,headers:l([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},t?.headers])})}};var Yn=(()=>{class r extends b{constructor(){super(...arguments),this.workspaces=new Ft(this._client)}create(e,t){let{betas:n,...i}=e;return this._client.post("/v1/organizations/service_accounts?beta=true",{body:i,...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}retrieve(e,t={},n){let{betas:i}=t??{};return this._client.get(h`/v1/organizations/service_accounts/${e}?beta=true`,{...n,headers:l([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},n?.headers])})}update(e,t,n){let{betas:i,...o}=t;return this._client.post(h`/v1/organizations/service_accounts/${e}?beta=true`,{body:o,...n,headers:l([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},n?.headers])})}list(e={},t){let{betas:n,...i}=e??{};return this._client.getAPIList("/v1/organizations/service_accounts?beta=true",S,{query:i,...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}archive(e,t={},n){let{betas:i}=t??{};return this._client.post(h`/v1/organizations/service_accounts/${e}/archive?beta=true`,{...n,headers:l([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},n?.headers])})}}return r.Workspaces=Ft,r})();var Ht=class extends b{retrieve(s,e,t){let{workspace_id:n}=e;return this._client.get(h`/v1/organizations/workspaces/${n}/members/${s}?beta=true`,t)}update(s,e,t){let{workspace_id:n,...i}=e;return this._client.post(h`/v1/organizations/workspaces/${n}/members/${s}?beta=true`,{body:i,...t})}list(s,e={},t){return this._client.getAPIList(h`/v1/organizations/workspaces/${s}/members?beta=true`,B,{query:e,...t})}add(s,e,t){return this._client.post(h`/v1/organizations/workspaces/${s}/members?beta=true`,{body:e,...t})}remove(s,e,t){let{workspace_id:n}=e;return this._client.delete(h`/v1/organizations/workspaces/${n}/members/${s}?beta=true`,t)}};var Dt=class extends b{list(s,e={},t){return this._client.getAPIList(h`/v1/organizations/workspaces/${s}/rate_limits?beta=true`,S,{query:e,...t})}};var Bt=class extends b{retrieve(s,e,t){let{workspace_id:n,betas:i}=e;return this._client.get(h`/v1/organizations/workspaces/${n}/service_accounts/${s}?beta=true`,{...t,headers:l([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},t?.headers])})}update(s,e,t){let{workspace_id:n,betas:i,...o}=e;return this._client.post(h`/v1/organizations/workspaces/${n}/service_accounts/${s}?beta=true`,{body:o,...t,headers:l([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},t?.headers])})}list(s,e={},t){let{betas:n,...i}=e??{};return this._client.getAPIList(h`/v1/organizations/workspaces/${s}/service_accounts?beta=true`,S,{query:i,...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}add(s,e,t){let{betas:n,...i}=e;return this._client.post(h`/v1/organizations/workspaces/${s}/service_accounts?beta=true`,{body:i,...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}remove(s,e,t){let{workspace_id:n,betas:i}=e;return this._client.delete(h`/v1/organizations/workspaces/${n}/service_accounts/${s}?beta=true`,{...t,headers:l([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},t?.headers])})}};var Xn=(()=>{class r extends b{constructor(){super(...arguments),this.rateLimits=new Dt(this._client),this.members=new Ht(this._client),this.serviceAccounts=new Bt(this._client)}create(e,t){let{betas:n,...i}=e;return this._client.post("/v1/organizations/workspaces?beta=true",{body:i,...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}retrieve(e,t){return this._client.get(h`/v1/organizations/workspaces/${e}?beta=true`,t)}update(e,t,n){return this._client.post(h`/v1/organizations/workspaces/${e}?beta=true`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/v1/organizations/workspaces?beta=true",B,{query:e,...t})}archive(e,t){return this._client.post(h`/v1/organizations/workspaces/${e}/archive?beta=true`,t)}}return r.RateLimits=Dt,r.Members=Ht,r.ServiceAccounts=Bt,r})();var Gn=(()=>{class r extends b{constructor(){super(...arguments),this.apiKeys=new Pt(this._client),this.externalKeys=new Mt(this._client),this.federation=new Jn(this._client),this.invites=new Ot(this._client),this.serviceAccounts=new Yn(this._client),this.users=new $t(this._client),this.workspaces=new Xn(this._client),this.rateLimits=new Ct(this._client),this.complianceSettings=new Tt(this._client)}retrieve(e){return this._client.get("/v1/organizations/me?beta=true",e)}}return r.APIKeys=Pt,r.ExternalKeys=Mt,r.Federation=Jn,r.Invites=Ot,r.ServiceAccounts=Yn,r.Users=$t,r.Workspaces=Xn,r.RateLimits=Ct,r.ComplianceSettings=Tt,r})();var Qn=(()=>{class r extends b{list(e,t={},n){let{betas:i,workspace_id:o,...c}=t??{};return this._client.getAPIList(h`/v1/sessions/${e}/events?beta=true`,S,{query:c,...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}send(e,t,n){let{betas:i,workspace_id:o,...c}=t;return this._client.post(h`/v1/sessions/${e}/events?beta=true`,{body:c,...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}stream(e,t={},n){let{betas:i,workspace_id:o,...c}=t??{};return this._client.get(h`/v1/sessions/${e}/events/stream?beta=true`,{query:c,...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers]),stream:!0})}toolRunner(e,t){return new br(e,{...t,client:this._client})}}return r.SessionToolRunner=br,r})();var Wt=class extends b{retrieve(s,e,t){let{session_id:n,betas:i,workspace_id:o}=e;return this._client.get(h`/v1/sessions/${n}/resources/${s}?beta=true`,{...t,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},t?.headers])})}update(s,e,t){let{session_id:n,betas:i,workspace_id:o,...c}=e;return this._client.post(h`/v1/sessions/${n}/resources/${s}?beta=true`,{body:c,...t,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},t?.headers])})}list(s,e={},t){let{betas:n,workspace_id:i,...o}=e??{};return this._client.getAPIList(h`/v1/sessions/${s}/resources?beta=true`,S,{query:o,...t,headers:l([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}delete(s,e,t){let{session_id:n,betas:i,workspace_id:o}=e;return this._client.delete(h`/v1/sessions/${n}/resources/${s}?beta=true`,{...t,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},t?.headers])})}add(s,e,t){let{betas:n,workspace_id:i,...o}=e;return this._client.post(h`/v1/sessions/${s}/resources?beta=true`,{body:o,...t,headers:l([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}};var Ut=class extends b{list(s,e,t){let{session_id:n,betas:i,workspace_id:o,...c}=e;return this._client.getAPIList(h`/v1/sessions/${n}/threads/${s}/events?beta=true`,S,{query:c,...t,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},t?.headers])})}stream(s,e,t){let{session_id:n,betas:i,workspace_id:o,...c}=e;return this._client.get(h`/v1/sessions/${n}/threads/${s}/stream?beta=true`,{query:c,...t,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},t?.headers]),stream:!0})}};var Zn=(()=>{class r extends b{constructor(){super(...arguments),this.events=new Ut(this._client)}retrieve(e,t,n){let{session_id:i,betas:o,workspace_id:c}=t;return this._client.get(h`/v1/sessions/${i}/threads/${e}?beta=true`,{...n,headers:l([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},n?.headers])})}list(e,t={},n){let{betas:i,workspace_id:o,...c}=t??{};return this._client.getAPIList(h`/v1/sessions/${e}/threads?beta=true`,S,{query:c,...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}archive(e,t,n){let{session_id:i,betas:o,workspace_id:c}=t;return this._client.post(h`/v1/sessions/${i}/threads/${e}/archive?beta=true`,{...n,headers:l([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},n?.headers])})}}return r.Events=Ut,r})();var es=(()=>{class r extends b{constructor(){super(...arguments),this.events=new Qn(this._client),this.resources=new Wt(this._client),this.threads=new Zn(this._client)}create(e,t){let{betas:n,workspace_id:i,...o}=e;return this._client.post("/v1/sessions?beta=true",{body:o,...t,headers:l([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}retrieve(e,t={},n){let{betas:i,workspace_id:o}=t??{};return this._client.get(h`/v1/sessions/${e}?beta=true`,{...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}update(e,t,n){let{betas:i,workspace_id:o,...c}=t;return this._client.post(h`/v1/sessions/${e}?beta=true`,{body:c,...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}list(e={},t){let{betas:n,workspace_id:i,...o}=e??{};return this._client.getAPIList("/v1/sessions?beta=true",on,{query:o,...t,headers:l([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}delete(e,t={},n){let{betas:i,workspace_id:o}=t??{};return this._client.delete(h`/v1/sessions/${e}?beta=true`,{...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}archive(e,t={},n){let{betas:i,workspace_id:o}=t??{};return this._client.post(h`/v1/sessions/${e}/archive?beta=true`,{...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}}return r.Events=Qn,r.Resources=Wt,r.Threads=Zn,r})();var qt=class extends b{create(s,e,t){let{betas:n,workspace_id:i,...o}=e;return this._client.post(h`/v1/skills/${s}/versions?beta=true`,ie({body:o,...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])},this._client,!1))}retrieve(s,e,t){let{skill_id:n,betas:i,workspace_id:o}=e;return this._client.get(h`/v1/skills/${n}/versions/${s}?beta=true`,{...t,headers:l([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...o!=null?{"anthropic-workspace-id":o}:void 0},t?.headers])})}list(s,e={},t){let{betas:n,workspace_id:i,...o}=e??{};return this._client.getAPIList(h`/v1/skills/${s}/versions?beta=true`,S,{query:o,...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}delete(s,e,t){let{skill_id:n,betas:i,workspace_id:o}=e;return this._client.delete(h`/v1/skills/${n}/versions/${s}?beta=true`,{...t,headers:l([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...o!=null?{"anthropic-workspace-id":o}:void 0},t?.headers])})}download(s,e,t){let{skill_id:n,betas:i,workspace_id:o}=e;return this._client.get(h`/v1/skills/${n}/versions/${s}/content?beta=true`,{...t,headers:l([{Accept:"application/binary",...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...o!=null?{"anthropic-workspace-id":o}:void 0},t?.headers]),__binaryResponse:!0})}};var ts=(()=>{class r extends b{constructor(){super(...arguments),this.versions=new qt(this._client)}create(e,t){let{betas:n,workspace_id:i,...o}=e;return this._client.post("/v1/skills?beta=true",ie({body:o,...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])},this._client,!1))}retrieve(e,t={},n){let{betas:i,workspace_id:o}=t??{};return this._client.get(h`/v1/skills/${e}?beta=true`,{...n,headers:l([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}list(e={},t){let{betas:n,workspace_id:i,...o}=e??{};return this._client.getAPIList("/v1/skills?beta=true",S,{query:o,...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}delete(e,t={},n){let{betas:i,workspace_id:o}=t??{};return this._client.delete(h`/v1/skills/${e}?beta=true`,{...n,headers:l([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}}return r.Versions=qt,r})();var jt=class extends b{create(s,e,t){let{betas:n,workspace_id:i,...o}=e;return this._client.post(h`/v1/tunnels/${s}/certificates?beta=true`,{body:o,...t,headers:l([{"anthropic-beta":[...n??[],"mcp-tunnels-2026-06-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}retrieve(s,e,t){let{tunnel_id:n,betas:i,workspace_id:o}=e;return this._client.get(h`/v1/tunnels/${n}/certificates/${s}?beta=true`,{...t,headers:l([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},t?.headers])})}list(s,e={},t){let{betas:n,workspace_id:i,...o}=e??{};return this._client.getAPIList(h`/v1/tunnels/${s}/certificates?beta=true`,S,{query:o,...t,headers:l([{"anthropic-beta":[...n??[],"mcp-tunnels-2026-06-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}archive(s,e,t){let{tunnel_id:n,betas:i,workspace_id:o}=e;return this._client.post(h`/v1/tunnels/${n}/certificates/${s}/archive?beta=true`,{...t,headers:l([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},t?.headers])})}};var rs=(()=>{class r extends b{constructor(){super(...arguments),this.certificates=new jt(this._client)}create(e,t){let{betas:n,workspace_id:i,...o}=e;return this._client.post("/v1/tunnels?beta=true",{body:o,...t,headers:l([{"anthropic-beta":[...n??[],"mcp-tunnels-2026-06-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}retrieve(e,t={},n){let{betas:i,workspace_id:o}=t??{};return this._client.get(h`/v1/tunnels/${e}?beta=true`,{...n,headers:l([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}list(e={},t){let{betas:n,workspace_id:i,...o}=e??{};return this._client.getAPIList("/v1/tunnels?beta=true",S,{query:o,...t,headers:l([{"anthropic-beta":[...n??[],"mcp-tunnels-2026-06-22"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}archive(e,t={},n){let{betas:i,workspace_id:o}=t??{};return this._client.post(h`/v1/tunnels/${e}/archive?beta=true`,{...n,headers:l([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}revealToken(e,t={},n){let{betas:i,workspace_id:o}=t??{};return this._client.post(h`/v1/tunnels/${e}/reveal_token?beta=true`,{...n,headers:l([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}rotateToken(e,t,n){let{betas:i,workspace_id:o,...c}=t;return this._client.post(h`/v1/tunnels/${e}/rotate_token?beta=true`,{body:c,...n,headers:l([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}}return r.Certificates=jt,r})();var zt=class extends b{create(s,e,t){let{betas:n,workspace_id:i,...o}=e;return this._client.post(h`/v1/vaults/${s}/credentials?beta=true`,{body:o,...t,headers:l([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}retrieve(s,e,t){let{vault_id:n,betas:i,workspace_id:o}=e;return this._client.get(h`/v1/vaults/${n}/credentials/${s}?beta=true`,{...t,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},t?.headers])})}update(s,e,t){let{vault_id:n,betas:i,workspace_id:o,...c}=e;return this._client.post(h`/v1/vaults/${n}/credentials/${s}?beta=true`,{body:c,...t,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},t?.headers])})}list(s,e={},t){let{betas:n,workspace_id:i,...o}=e??{};return this._client.getAPIList(h`/v1/vaults/${s}/credentials?beta=true`,S,{query:o,...t,headers:l([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}delete(s,e,t){let{vault_id:n,betas:i,workspace_id:o}=e;return this._client.delete(h`/v1/vaults/${n}/credentials/${s}?beta=true`,{...t,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},t?.headers])})}archive(s,e,t){let{vault_id:n,betas:i,workspace_id:o}=e;return this._client.post(h`/v1/vaults/${n}/credentials/${s}/archive?beta=true`,{...t,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},t?.headers])})}mcpOAuthValidate(s,e,t){let{vault_id:n,betas:i,workspace_id:o}=e;return this._client.post(h`/v1/vaults/${n}/credentials/${s}/mcp_oauth_validate?beta=true`,{...t,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},t?.headers])})}};var ns=(()=>{class r extends b{constructor(){super(...arguments),this.credentials=new zt(this._client)}create(e,t){let{betas:n,workspace_id:i,...o}=e;return this._client.post("/v1/vaults?beta=true",{body:o,...t,headers:l([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}retrieve(e,t={},n){let{betas:i,workspace_id:o}=t??{};return this._client.get(h`/v1/vaults/${e}?beta=true`,{...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}update(e,t,n){let{betas:i,workspace_id:o,...c}=t;return this._client.post(h`/v1/vaults/${e}?beta=true`,{body:c,...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}list(e={},t){let{betas:n,workspace_id:i,...o}=e??{};return this._client.getAPIList("/v1/vaults?beta=true",S,{query:o,...t,headers:l([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}delete(e,t={},n){let{betas:i,workspace_id:o}=t??{};return this._client.delete(h`/v1/vaults/${e}?beta=true`,{...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}archive(e,t={},n){let{betas:i,workspace_id:o}=t??{};return this._client.post(h`/v1/vaults/${e}/archive?beta=true`,{...n,headers:l([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"anthropic-workspace-id":o}:void 0},n?.headers])})}}return r.Credentials=zt,r})();var Mr=(()=>{class r extends b{constructor(){super(...arguments),this.models=new ot(this._client),this.messages=new Kn(this._client),this.agents=new mn(this._client),this.environments=new $n(this._client),this.sessions=new es(this._client),this.deployments=new nt(this._client),this.deploymentRuns=new rt(this._client),this.vaults=new ns(this._client),this.memoryStores=new Nn(this._client),this.files=new it(this._client),this.skills=new ts(this._client),this.webhooks=new lt(this._client),this.userProfiles=new at(this._client),this.dreams=new st(this._client),this.tunnels=new rs(this._client),this.organization=new Gn(this._client)}}return r.Models=ot,r.Messages=Kn,r.Agents=mn,r.Environments=$n,r.Sessions=es,r.Deployments=nt,r.DeploymentRuns=rt,r.Vaults=ns,r.MemoryStores=Nn,r.Files=it,r.Skills=ts,r.Webhooks=lt,r.UserProfiles=at,r.Dreams=st,r.Tunnels=rs,r.Organization=Gn,r})();var We=class extends b{create(s,e){let{betas:t,workspace_id:n,...i}=s;return this._client.post("/v1/complete",{body:i,timeout:this._client._options.timeout??6e5,...e,headers:l([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0,...n!=null?{"anthropic-workspace-id":n}:void 0},e?.headers]),stream:s.stream??!1})}};var Ue=class extends b{list(s={},e){let{workspace_id:t,...n}=s??{};return this._client.getAPIList("/v1/files",S,{query:n,...e,headers:l([{...t!=null?{"anthropic-workspace-id":t}:void 0},e?.headers])})}delete(s,e={},t){let{workspace_id:n}=e??{};return this._client.delete(h`/v1/files/${s}`,{...t,headers:l([{...n!=null?{"anthropic-workspace-id":n}:void 0},t?.headers])})}download(s,e={},t){let{workspace_id:n}=e??{};return this._client.get(h`/v1/files/${s}/content`,{...t,headers:l([{Accept:"application/binary",...n!=null?{"anthropic-workspace-id":n}:void 0},t?.headers]),__binaryResponse:!0})}retrieveMetadata(s,e={},t){let{workspace_id:n}=e??{};return this._client.get(h`/v1/files/${s}`,{...t,headers:l([{...n!=null?{"anthropic-workspace-id":n}:void 0},t?.headers])})}upload(s,e){let{workspace_id:t,...n}=s;return this._client.post("/v1/files",ie({body:n,...e,headers:l([{...t!=null?{"anthropic-workspace-id":t}:void 0},hn(n.file),e?.headers])},this._client))}};function Zo(r){return r?.output_config?.format}function si(r,s,e){let t=Zo(s);return!s||!("parse"in(t??{}))?{...r,content:r.content.map(n=>n.type==="text"?Object.defineProperty({...n},"parsed_output",{value:null,enumerable:!1}):n),parsed_output:null}:ii(r,s,e)}function ii(r,s,e){let t=null,n=r.content.map(i=>{if(i.type==="text"){let o=Nl(s,i.text);return t===null&&(t=o),Object.defineProperty({...i},"parsed_output",{value:o,enumerable:!1})}return i});return{...r,content:n,parsed_output:t}}function Nl(r,s){let e=Zo(r);if(e?.type!=="json_schema")return null;try{return"parse"in e?e.parse(s):JSON.parse(s)}catch(t){throw new k(`Failed to parse structured output: ${t}`)}}var ce,Me,Kt,Or,ss,Cr,$r,is,Nr,be,Lr,os,as,qe,cs,ls,ds,Fr,oi,ea,ai,ci,li,di,ta;function ui(r){return r.type==="tool_use"||r.type==="server_tool_use"}var ra=(()=>{class r{constructor(e,t){ce.add(this),this.messages=[],this.receivedMessages=[],Me.set(this,void 0),Kt.set(this,null),this.controller=new AbortController,Or.set(this,void 0),ss.set(this,()=>{}),Cr.set(this,()=>{}),$r.set(this,void 0),is.set(this,()=>{}),Nr.set(this,()=>{}),be.set(this,{}),Lr.set(this,!1),os.set(this,!1),as.set(this,!1),qe.set(this,!1),cs.set(this,void 0),ls.set(this,void 0),ds.set(this,void 0),Fr.set(this,void 0),ai.set(this,n=>{if(g(this,os,!0,"f"),G(n)&&(n=new z),n instanceof z)return g(this,as,!0,"f"),this._emit("abort",n);if(n instanceof k)return this._emit("error",n);if(n instanceof Error){let i=new k(n.message);return i.cause=n,this._emit("error",i)}return this._emit("error",new k(String(n)))}),g(this,Or,new Promise((n,i)=>{g(this,ss,n,"f"),g(this,Cr,i,"f")}),"f"),g(this,$r,new Promise((n,i)=>{g(this,is,n,"f"),g(this,Nr,i,"f")}),"f"),a(this,Or,"f").catch(()=>{}),a(this,$r,"f").catch(()=>{}),g(this,Kt,e,"f"),g(this,Fr,t?.logger??console,"f")}get response(){return a(this,cs,"f")}get request_id(){return a(this,ls,"f")}get workspace_id(){return a(this,ds,"f")}async withResponse(){g(this,qe,!0,"f");let e=await a(this,Or,"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 r(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n,{logger:i}={}){let o=new r(t,{logger:i});for(let c of t.messages)o._addMessageParam(c);return g(o,Kt,{...t,stream:!0},"f"),o._run(()=>o._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,[dn]:"stream"}})),o}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},a(this,ai,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){let i=n?.signal,o;i&&(i.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),i.addEventListener("abort",o));try{a(this,ce,"m",ci).call(this);let{response:c,data:u}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(c);for await(let d of u)a(this,ce,"m",li).call(this,d);if(u.controller.signal?.aborted)throw new z;a(this,ce,"m",di).call(this)}finally{i&&o&&i.removeEventListener("abort",o)}}_connected(e){this.ended||(g(this,cs,e,"f"),g(this,ls,e?.headers.get("request-id"),"f"),g(this,ds,e?.headers.get("anthropic-workspace-id"),"f"),a(this,ss,"f").call(this,e),this._emit("connect"))}get ended(){return a(this,Lr,"f")}get errored(){return a(this,os,"f")}get aborted(){return a(this,as,"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 n=a(this,be,"f")[e];if(!n)return this;let i=n.findIndex(o=>o.listener===t);return i>=0&&n.splice(i,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,n)=>{g(this,qe,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){g(this,qe,!0,"f"),await a(this,$r,"f")}get currentMessage(){return a(this,Me,"f")}async finalMessage(){return await this.done(),a(this,ce,"m",oi).call(this)}async finalText(){return await this.done(),a(this,ce,"m",ea).call(this)}_emit(e,...t){if(a(this,Lr,"f"))return;e==="end"&&(g(this,Lr,!0,"f"),a(this,is,"f").call(this));let n=a(this,be,"f")[e];if(n&&(a(this,be,"f")[e]=n.filter(i=>!i.once),n.forEach(({listener:i})=>i(...t))),e==="abort"){let i=t[0];!a(this,qe,"f")&&!n?.length&&Promise.reject(i),a(this,Cr,"f").call(this,i),a(this,Nr,"f").call(this,i),this._emit("end");return}if(e==="error"){let i=t[0];!a(this,qe,"f")&&!n?.length&&Promise.reject(i),a(this,Cr,"f").call(this,i),a(this,Nr,"f").call(this,i),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",a(this,ce,"m",oi).call(this))}async _fromReadableStream(e,t){let n=t?.signal,i;n&&(n.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),n.addEventListener("abort",i));try{a(this,ce,"m",ci).call(this),this._connected(null);let o=se.fromReadableStream(e,this.controller);for await(let c of o)a(this,ce,"m",li).call(this,c);if(o.controller.signal?.aborted)throw new z;a(this,ce,"m",di).call(this)}finally{n&&i&&n.removeEventListener("abort",i)}}[(Me=new WeakMap,Kt=new WeakMap,Or=new WeakMap,ss=new WeakMap,Cr=new WeakMap,$r=new WeakMap,is=new WeakMap,Nr=new WeakMap,be=new WeakMap,Lr=new WeakMap,os=new WeakMap,as=new WeakMap,qe=new WeakMap,cs=new WeakMap,ls=new WeakMap,ds=new WeakMap,Fr=new WeakMap,ai=new WeakMap,ce=new WeakSet,oi=function(){if(this.receivedMessages.length===0)throw new k("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},ea=function(){if(this.receivedMessages.length===0)throw new k("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new k("stream ended without producing a content block with type=text");return t.join(" ")},ci=function(){this.ended||g(this,Me,void 0,"f")},li=function(t){if(this.ended)return;let n=a(this,ce,"m",ta).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{let i=n.content.at(-1);switch(t.delta.type){case"text_delta":{i.type==="text"&&this._emit("text",t.delta.text,i.text||"");break}case"citations_delta":{i.type==="text"&&this._emit("citation",t.delta.citation,i.citations??[]);break}case"input_json_delta":{ui(i)&&a(this,be,"f").inputJson?.length&&this._emit("inputJson",t.delta.partial_json,i.input);break}case"thinking_delta":{i.type==="thinking"&&this._emit("thinking",t.delta.thinking,i.thinking);break}case"signature_delta":{i.type==="thinking"&&this._emit("signature",i.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(si(n,a(this,Kt,"f"),{logger:a(this,Fr,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{g(this,Me,n,"f");break}case"content_block_start":case"message_delta":break}},di=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");let t=a(this,Me,"f");if(!t)throw new k("request ended without sending any chunks");return g(this,Me,void 0,"f"),si(t,a(this,Kt,"f"),{logger:a(this,Fr,"f")})},ta=function(t){let n=a(this,Me,"f");if(t.type==="message_start"){if(n)throw new k(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new k(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.stop_details=t.delta.stop_details,n.usage.output_tokens=t.usage.output_tokens,t.delta.container!=null&&(n.container=t.delta.container),t.usage.input_tokens!=null&&(n.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(n.usage.server_tool_use=t.usage.server_tool_use),t.usage.output_tokens_details!=null&&(n.usage.output_tokens_details=t.usage.output_tokens_details),n;case"content_block_start":return n.content.push({...t.content_block}),n;case"content_block_delta":{let i=n.content.at(t.index);switch(t.delta.type){case"text_delta":{i?.type==="text"&&(n.content[t.index]={...i,text:(i.text||"")+t.delta.text});break}case"citations_delta":{i?.type==="text"&&(n.content[t.index]={...i,citations:[...i.citations??[],t.delta.citation]});break}case"input_json_delta":{if(i&&ui(i)){let o=(i[Ie]||"")+t.delta.partial_json;n.content[t.index]=Hn(i,o)}break}case"thinking_delta":{i?.type==="thinking"&&(n.content[t.index]={...i,thinking:i.thinking+t.delta.thinking});break}case"signature_delta":{i?.type==="thinking"&&(n.content[t.index]={...i,signature:t.delta.signature});break}default:t.delta}return n}case"content_block_stop":{let i=n.content.at(t.index);return i&&ui(i)&&Ie in i&&Object.defineProperty(i,"input",{value:i.input,enumerable:!0,configurable:!0,writable:!0}),n}}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("streamEvent",i=>{let o=t.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{n=!0;for(let o of t)o.reject(i);t.length=0}),this.on("error",i=>{n=!0;for(let o of t)o.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,c)=>t.push({resolve:o,reject:c})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new se(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}return r})();var Vt=class extends b{create(s,e){let{user_profile_id:t,workspace_id:n,...i}=s;return this._client.post("/v1/messages/batches",{body:i,...e,headers:l([{...t!=null?{"anthropic-user-profile-id":t}:void 0,...n!=null?{"anthropic-workspace-id":n}:void 0},e?.headers])})}retrieve(s,e={},t){let{workspace_id:n}=e??{};return this._client.get(h`/v1/messages/batches/${s}`,{...t,headers:l([{...n!=null?{"anthropic-workspace-id":n}:void 0},t?.headers])})}list(s={},e){let{workspace_id:t,...n}=s??{};return this._client.getAPIList("/v1/messages/batches",B,{query:n,...e,headers:l([{...t!=null?{"anthropic-workspace-id":t}:void 0},e?.headers])})}delete(s,e={},t){let{workspace_id:n}=e??{};return this._client.delete(h`/v1/messages/batches/${s}`,{...t,headers:l([{...n!=null?{"anthropic-workspace-id":n}:void 0},t?.headers])})}cancel(s,e={},t){let{workspace_id:n}=e??{};return this._client.post(h`/v1/messages/batches/${s}/cancel`,{...t,headers:l([{...n!=null?{"anthropic-workspace-id":n}:void 0},t?.headers])})}async results(s,e={},t){let n=await this.retrieve(s,e,t);if(!n.results_url)throw new k(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);let{workspace_id:i}=e??{};return this._client.get(n.results_url,{...t,headers:l([{Accept:"application/binary",...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((o,c)=>Ln.fromResponse(c.response,c.controller))}};var Hr=(()=>{class r extends b{constructor(){super(...arguments),this.batches=new Vt(this._client)}create(e,t){let{user_profile_id:n,workspace_id:i,...o}=e;o.model in na&&console.warn(`The model '${o.model}' is deprecated and will reach end-of-life on ${na[o.model]}
|
|
33
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),Fl.includes(o.model)&&o.thinking&&o.thinking.type==="enabled"&&console.warn(`Using Claude with ${o.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let c=t?.timeout??this._client._options.timeout;if(!o.stream&&c==null){let d=Fn[o.model]??void 0;c=this._client.calculateNonstreamingTimeout(o.max_tokens,d)}let u=un(o.tools,o.messages);return this._client.post("/v1/messages",{body:o,timeout:c??6e5,...t,headers:l([{...n!=null?{"anthropic-user-profile-id":n}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},u,t?.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then(n=>ii(n,e,{logger:this._client.logger??console}))}stream(e,t){return ra.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){let{user_profile_id:n,workspace_id:i,...o}=e;return this._client.post("/v1/messages/count_tokens",{body:o,...t,headers:l([{...n!=null?{"anthropic-user-profile-id":n}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}}return r.Batches=Vt,r})(),na={},Fl=["claude-mythos-preview","claude-opus-4-6"];var je=class extends b{retrieve(s,e={},t){let{betas:n,workspace_id:i}=e??{};return this._client.get(h`/v1/models/${s}`,{...t,headers:l([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}list(s={},e){let{betas:t,workspace_id:n,...i}=s??{};return this._client.getAPIList("/v1/models",B,{query:i,...e,headers:l([{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0,...n!=null?{"anthropic-workspace-id":n}:void 0},e?.headers])})}};var Jt=class extends b{create(s,e,t){let{workspace_id:n,...i}=e;return this._client.post(h`/v1/skills/${s}/versions`,ie({body:i,...t,headers:l([{...n!=null?{"anthropic-workspace-id":n}:void 0},t?.headers])},this._client,!1))}retrieve(s,e,t){let{skill_id:n,workspace_id:i}=e;return this._client.get(h`/v1/skills/${n}/versions/${s}`,{...t,headers:l([{...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}list(s,e={},t){let{workspace_id:n,...i}=e??{};return this._client.getAPIList(h`/v1/skills/${s}/versions`,S,{query:i,...t,headers:l([{...n!=null?{"anthropic-workspace-id":n}:void 0},t?.headers])})}delete(s,e,t){let{skill_id:n,workspace_id:i}=e;return this._client.delete(h`/v1/skills/${n}/versions/${s}`,{...t,headers:l([{...i!=null?{"anthropic-workspace-id":i}:void 0},t?.headers])})}};var Dr=(()=>{class r extends b{constructor(){super(...arguments),this.versions=new Jt(this._client)}create(e,t){let{workspace_id:n,...i}=e;return this._client.post("/v1/skills",ie({body:i,...t,headers:l([{...n!=null?{"anthropic-workspace-id":n}:void 0},t?.headers])},this._client,!1))}retrieve(e,t={},n){let{workspace_id:i}=t??{};return this._client.get(h`/v1/skills/${e}`,{...n,headers:l([{...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}list(e={},t){let{workspace_id:n,...i}=e??{};return this._client.getAPIList("/v1/skills",S,{query:i,...t,headers:l([{...n!=null?{"anthropic-workspace-id":n}:void 0},t?.headers])})}delete(e,t={},n){let{workspace_id:i}=t??{};return this._client.delete(h`/v1/skills/${e}`,{...n,headers:l([{...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers])})}}return r.Versions=Jt,r})();var hi,fi,us,sa,ia="\\n\\nHuman:",oa="\\n\\nAssistant:",aa=(()=>{class r{get credentials(){return this._authState.provider}constructor({baseURL:e=M("ANTHROPIC_BASE_URL"),apiKey:t,authToken:n,webhookKey:i=M("ANTHROPIC_WEBHOOK_SIGNING_KEY")??null,...o}={}){if(hi.add(this),this._requestAuthFlags=new WeakMap,us.set(this,void 0),t===void 0&&(t=o.profile!=null?null:M("ANTHROPIC_API_KEY")??null),n===void 0&&(n=o.profile!=null?null:M("ANTHROPIC_AUTH_TOKEN")??null),o.profile!=null&&(o.credentials!=null||o.config!=null))throw new TypeError("Pass at most one of `profile`, `credentials`, or `config`.");let c={apiKey:t,authToken:n,webhookKey:i,...o,baseURL:e||"https://api.anthropic.com"};if(!c.dangerouslyAllowBrowser&&xi())throw new k(`It looks like you're running in a browser-like environment.
|
|
34
|
+
|
|
35
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
36
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
37
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
38
|
+
|
|
39
|
+
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
40
|
+
`);this.baseURL=c.baseURL,this._baseURLIsExplicit=o.__baseURLIsExplicit??!!e,this.timeout=c.timeout??fi.DEFAULT_TIMEOUT,this.logger=c.logger??console,this.logLevel=rr,this.logLevel=en(c.logLevel,"ClientOptions.logLevel",C(this))??en(M("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",C(this))??rr,this.fetchOptions=c.fetchOptions,this.maxRetries=Wr("maxRetries",c.maxRetries??2),this.fetch=c.fetch??Ri(),g(this,us,Pi,"f"),this.middleware=[...c.middleware??[]];let u=M("ANTHROPIC_CUSTOM_HEADERS");if(u){let m={};for(let p of u.split(`
|
|
41
|
+
`)){let f=p.indexOf(":");f>=0&&(m[p.substring(0,f).trim()]=p.substring(f+1).trim())}c.defaultHeaders={...m,...c.defaultHeaders}}let d=o.__auth;if(delete c.__auth,delete c.__baseURLIsExplicit,this._options=c,this.apiKey=typeof t=="string"?t:null,this.authToken=n,this.webhookKey=i,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 m=c.credentials??null;if(m)this._authState.provider=m,this._authState.tokenCache=this._makeTokenCache(m);else if(c.config!=null){let p=Rs(c.config,this._credentialResolverOptions());this._authState.provider=p.provider,this._authState.tokenCache=this._makeTokenCache(p.provider),this._authState.extraHeaders=p.extraHeaders,this._applyCredentialBaseURL(p.baseURL)}else c.profile!=null?this._authState.resolution=this._resolveDefaultCredentials(c.profile):this._shouldResolveDefaultCredentials()&&(this._authState.resolution=this._resolveDefaultCredentials())}}_shouldResolveDefaultCredentials(){return!0}_applyCredentialBaseURL(e){if(!e)return;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=>{C(this).debug("credential cache write failed (best-effort)",e)},onSafetyWarning:e=>{C(this).warn(e)}}}_credentialsFetch(){return Ts(this.fetch,this.middleware,void 0,this)}_makeTokenCache(e){return new Gr(e,t=>{C(this).debug("advisory token refresh failed; serving cached token",t)})}withOptions(e){let t="credentials"in e||"config"in e||"profile"in e,n="apiKey"in e||"authToken"in e||t,i={...this._options,...this._baseURLIsExplicit?{baseURL:this.baseURL}:{},maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,middleware:this.middleware,apiKey:this.apiKey,authToken:this.authToken,webhookKey:this.webhookKey,credentials:this.credentials,...t?{credentials:void 0,config:void 0,profile:void 0}:{},...e,__auth:n?void 0:this._authState,__baseURLIsExplicit:"baseURL"in e?!0:this._baseURLIsExplicit};return new this.constructor(i)}async _resolveDefaultCredentials(e){try{let t=await io(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 k(`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 Hi(e)}getUserAgent(){return`Anthropic/JS ${ne}`}makeStatusError(e,t,n,i){return F.generate(e,t,n,i)}buildURL(e,t,n){let i=!a(this,hi,"m",sa).call(this)&&n||this.baseURL,o=wi(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),c=this.defaultQuery(),u=Object.fromEntries(o.searchParams);return(!fs(c)||!fs(u))&&(t={...u,...c,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new k("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){if(this._authState.tokenCache&&this.apiKey==null){let i=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[c,u]of Object.entries(this._authState.extraHeaders))i.has(c)||i.set(c,u);i.get("anthropic-beta")?.split(",").map(c=>c.trim())?.includes(Ne)||i.append("anthropic-beta",Ne),e.headers=i}}backendMiddleware(){return[]}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(i=>({method:e,path:t,...i})))}request(e,t=null){return new ar(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let i=await e,o=Wr("maxRetries",i.maxRetries??this.maxRetries);t==null&&(t=o,this._requestAuthFlags.delete(i)),await this.prepareOptions(i);let{req:c,url:u,timeout:d}=await this.buildRequest(i,{retryCount:o-t}),m="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),p=n===void 0?"":`, retryOf: ${n}`,f=Date.now();if(i.signal?.aborted)throw new z;let w=new AbortController,_=await this.fetchWithTimeout(u,c,d,w,i,{requestLogID:m,retryOfRequestLogID:n}).catch(Ce),v=Date.now();if(_ instanceof globalThis.Error){pe(w);let y=`retrying, ${t} attempts remaining`;if(i.signal?.aborted)throw new z;let I=G(_)||/timed? ?out/i.test(String(_)+("cause"in _?String(_.cause):"")),x=this.middleware.length>0||!!i.middleware?.length||this.backendMiddleware().length>0;if(x&&!I&&!uo(_))throw C(this).info(`[${m}] middleware error (not retryable)`),C(this).debug(`[${m}] middleware error (not retryable)`,_e({retryOfRequestLogID:n,url:u,durationMs:v-f,message:_.message})),_;if(t)return C(this).info(`[${m}] connection ${I?"timed out":"failed"} - ${y}`),C(this).debug(`[${m}] connection ${I?"timed out":"failed"} (${y})`,_e({retryOfRequestLogID:n,url:u,durationMs:v-f,message:_.message})),this.retryRequest(i,t,n??m);throw C(this).info(`[${m}] connection ${I?"timed out":"failed"} - error; no more retries left`),C(this).debug(`[${m}] connection ${I?"timed out":"failed"} (error; no more retries left)`,_e({retryOfRequestLogID:n,url:u,durationMs:v-f,message:_.message})),I?new Ke:x&&!Ps(_)?_:new fe({cause:_})}let A=[..._.headers.entries()].filter(([y])=>y==="request-id"||y==="anthropic-workspace-id").map(([y,I])=>", "+y+": "+JSON.stringify(I)).join(""),E=`[${m}${p}${A}] ${c.method} ${u} ${_.ok?"succeeded":"failed"} with status ${_.status} in ${v-f}ms`;if(!_.ok){let y=await this.shouldRetry(_,i);if(t&&y){let O=`retrying, ${t} attempts remaining`;return await Ii(_.body),pe(w),C(this).info(`${E} - ${O}`),C(this).debug(`[${m}] response error (${O})`,_e({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,durationMs:v-f})),this.retryRequest(i,t,n??m,_.headers)}let I=y?"error; no more retries left":"error; not retryable";C(this).info(`${E} - ${I}`);let x=await _.text().catch(O=>Ce(O).message),R=$e(x),P=R?void 0:x;throw C(this).debug(`[${m}] response error (${I})`,_e({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,message:P,durationMs:Date.now()-f})),pe(w),this.makeStatusError(_.status,R,P,_.headers)}return C(this).info(E),C(this).debug(`[${m}] response start`,_e({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,durationMs:v-f})),Ei(_.body??_,w),{response:_,options:i,controller:w,requestLogID:m,retryOfRequestLogID:n,startTime:f}}getAPIList(e,t,n){return this.requestAPIList(t,n&&"then"in n?n.then(i=>({method:"get",path:e,...i})):{method:"get",path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new Os(this,n,e)}async fetchWithTimeout(e,t,n,i,o,c){let{signal:u,method:d,...m}=t||{},p=this._makeAbort(i);u&&(u.addEventListener("abort",p,{once:!0}),Ai(i,u,p));let f=globalThis.ReadableStream&&m.body instanceof globalThis.ReadableStream||typeof m.body=="object"&&m.body!==null&&Symbol.asyncIterator in m.body,w={signal:i.signal,...f?{duplex:"half"}:{},method:"GET",...m};d&&(w.method=d.toUpperCase());let _=this.fetch,v=async(x,R)=>{let P=setTimeout(p,n);try{return await _.call(void 0,x,R)}finally{clearTimeout(P)}},A=o===void 0?v:(async(x,R={})=>{let P=typeof x=="string"?x:x instanceof URL?x.href:x.url;return R.headers=R.headers instanceof Headers?R.headers:new Headers(R.headers),await this.prepareRequest(R,{url:P,options:o}),c&&C(this).debug(`[${c.requestLogID}] sending request`,_e({retryOfRequestLogID:c.retryOfRequestLogID,method:R.method,url:P,options:o,headers:R.headers})),v(x,R)}),E=o?.middleware,y=this.backendMiddleware(),I=E?.length||y.length?[...this.middleware,...E??[],...y]:this.middleware;return await Ts(A,I,o,this)(e,w)}async shouldRetry(e,t){let n=this._authFlags(t);if(e.status===401&&this._authState.tokenCache&&n.usedTokenCache&&!n.didRefreshFor401)return n.didRefreshFor401=!0,this._authState.tokenCache.invalidate(),!0;let i=e.headers.get("x-should-retry");return i==="true"?!0:i==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,i){let o,c=i?.get("retry-after-ms");if(c){let d=parseFloat(c);Number.isNaN(d)||(o=d)}let u=i?.get("retry-after");if(u&&!o){let d=parseFloat(u);Number.isNaN(d)?o=Date.parse(u)-Date.now():o=d*1e3}if(o===void 0||!(o>0&&o<=2**31-1)){let d=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,d)}return await le(o,e.signal??void 0),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,c=Math.min(.5*Math.pow(2,o),8),u=1-Math.random()*.25;return c*u*1e3}calculateNonstreamingTimeout(e,t){if(36e5*e/128e3>6e5||t!=null&&e>t)throw new k("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 n={...e},{method:i,path:o,query:c,defaultBaseURL:u}=n;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(o,c,u);"timeout"in n&&Wr("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:m,body:p}=this.buildBody({options:n}),f=await this.buildHeaders({options:e,method:i,bodyHeaders:m,retryCount:t});return{req:{method:i,headers:f,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&p instanceof globalThis.ReadableStream&&{duplex:"half"},...p&&{body:p},...this.fetchOptions??{},...n.fetchOptions??{}},url:d,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:i}){let o=l([{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Gt(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=l([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:qr(e)}:typeof e=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:a(this,us,"f").call(this,{body:e,headers:n})}}return fi=r,us=new WeakMap,hi=new WeakSet,sa=function(){return this.baseURL!=="https://api.anthropic.com"},r.Anthropic=fi,r.HUMAN_PROMPT=ia,r.AI_PROMPT=oa,r.DEFAULT_TIMEOUT=6e5,r.AnthropicError=k,r.APIError=F,r.APIConnectionError=fe,r.APIConnectionTimeoutError=Ke,r.APIUserAbortError=z,r.NotFoundError=Xe,r.ConflictError=Ge,r.RateLimitError=Ze,r.BadRequestError=Ve,r.AuthenticationError=Je,r.InternalServerError=et,r.PermissionDeniedError=Ye,r.UnprocessableEntityError=Qe,r.toFile=an,r})(),ca=(()=>{class r extends aa{constructor(){super(...arguments),this.completions=new We(this),this.messages=new Hr(this),this.models=new je(this),this.files=new Ue(this),this.skills=new Dr(this),this.beta=new Mr(this)}}return r.Completions=We,r.Messages=Hr,r.Models=je,r.Files=Ue,r.Skills=Dr,r.Beta=Mr,r})();var fa=new TextEncoder,Bl=["fallback-credit-2026-07-01"];function Wl(r){let s=r.messages.flatMap(e=>{if(!Array.isArray(e.content))return[e];let t=e.content.filter(n=>n.type!=="fallback");return t.length===e.content.length?[e]:t.length>0?[{...e,content:t}]:[]});return{...r,messages:s}}function la(r,s){let e={...r};for(let[t,n]of Object.entries(s))if(t==="output_config"&&n!=null){let i={...e[t]??{}};for(let[o,c]of Object.entries(n))pi(i,o,c);pi(e,t,Object.keys(i).length?i:null)}else pi(e,t,n);return e}function pi(r,s,e){e!==void 0&&(e===null?delete r[s]:r[s]=e)}function Ul(r,s={}){let e=!1;return async(t,n,i)=>{let[o,c]=(i.options?.path??"").split("?");if(r.length===0||i.options?.method!=="post"||o!=="/v1/messages"||new URLSearchParams(c).get("beta")!=="true"||typeof i.options.body!="object"||i.options.body==null)return n(t);if(i.options.body.fallbacks!=null)throw new k("Sending the `fallbacks:` request param is not supported when using the `betaRefusalFallbackMiddleware`. You should either remove the middleware and send `fallbacks:` with the `server-side-fallback-2026-07-01` beta header to let the API handle refusal fallbacks, or omit the `fallbacks:` param if you'd like `betaRefusalFallbackMiddleware` to handle fallbacks on the client side.");let u=s.onError??(P=>i.logger.error(`anthropic-sdk: betaRefusalFallbackMiddleware: ${P.message}`));t=Vl(t,s.betas??Bl);let d=Wl(i.options.body),m=i.options.fallbackState,p=m?.index??-1;if(!Number.isInteger(p)||p<-1||p>=r.length)throw new k(`fallbackState.index ${p} is out of bounds for a chain of ${r.length} fallback(s); was the state shared with a different middleware?`);let f=P=>{m?m.index=P:e||(e=!0,i.logger.warn("anthropic-sdk: betaRefusalFallbackMiddleware fell back without a `fallbackState` request option; follow-up requests will retry models that already refused. Pass a shared `{ fallbackState: new BetaFallbackState() }` to pin them to the accepted model."))},w=p===-1?d:la(d,r[p]),_=typeof t.body!="string"?t:{...t,body:JSON.stringify(w)},v=await n(_);if(!v.ok)return v;if(i.options.stream===!0){let P=p+1;return P>=r.length||typeof _.body!="string"?v:ql({request:_,response:v,next:n,ctx:i,fallbacks:r,firstHop:P,onError:u,pin:f})}let A=p,E=v,y=w.model,I=[];for(;A<r.length-1;){let P=await i.parse(E);if(P?.type!=="message"||P.stop_reason!=="refusal")break;A+=1,f(A);let T=r[A];I.push({type:"fallback",from:{model:y??P.model},to:{model:T.model},trigger:{type:"refusal",category:P.stop_details?.category??null}}),y=T.model,E=await n({...t,body:JSON.stringify({...la(d,T),...P.stop_details?.fallback_credit_token?{fallback_credit_token:pa(P.stop_details.fallback_credit_token)}:void 0})})}if(I.length===0)return E;let x=await i.parse(E);if(x?.type!=="message"||x.stop_reason==="refusal"||!Array.isArray(x.content))return E;let R=new Headers(E.headers);return R.delete("content-length"),new Response(JSON.stringify({...x,content:[...I,...x.content]}),{status:E.status,statusText:E.statusText,headers:R})}}function ql(r){let s=new AbortController,e=r.request.signal;e?.aborted?s.abort(e.reason):e?.addEventListener("abort",Yl(s,e),{once:!0});let t=jl(r,s),n=new ReadableStream({async pull(i){try{let{value:o,done:c}=await t.next();if(c)return i.close();i.enqueue(o)}catch(o){i.error(o)}},async cancel(){s.abort(),await t.return?.(void 0)}});return new Response(n,r.response)}async function*jl({request:r,response:s,next:e,ctx:t,fallbacks:n,firstHop:i,onError:o,pin:c},u){let d=yield*da({response:s,controller:u,indexBase:0,hasNext:!0,onError:o,splice:null});if(!d.refused)return;let m=d.nextIndex,p=d.refused.token,f=[],w=d.refused.hasPrefillClaim?ua(d.blocks):[],_=d.model??"",v=d.refused.usage,A=d.refused.stopDetails,E=d.refused.inputTransformations,y=[_i("message",d.model??"",d.refused.usage)];for(let I=i;I<n.length;I++){let x=n[I].model,R=I+1<n.length;c(I);let P=m++;yield Se("content_block_start",{type:"content_block_start",index:P,content_block:{type:"fallback",from:{model:_},to:{model:x},trigger:{type:"refusal",category:A?.category??null}}}),yield Se("content_block_stop",{type:"content_block_stop",index:P});let T=[...f,...w],O=null,L=null;for(let j=0;j<2;j++){let he=zl(r,{model:x,creditToken:p,continuation:T});he.signal=u.signal;try{O=await e(he)}catch(ze){if(G(ze))throw ze;L={kind:"request_failed",message:`fallback request failed: ${ze}`,model:x,status:null,detail:ze};break}if(O.ok)break;let Oe=await t.parse(O).catch(()=>null);if(j===0&&O.status===400&&w.length){t.logger.warn(`anthropic-sdk: betaRefusalFallbackMiddleware: fallback request with the partial output appended was rejected (HTTP 400: ${JSON.stringify(Oe)}); retrying without it`),T=f,O=null;continue}L={kind:"request_failed",message:`fallback request failed: HTTP ${O.status}: ${JSON.stringify(Oe)}`,model:x,status:O.status,detail:Oe};break}if(L){if(o(L),R)continue;let j={...A,recommended_model:x};yield Se("message_delta",{type:"message_delta",context_management:null,delta:{stop_reason:"refusal",stop_sequence:null,container:null,stop_details:j},usage:v??{},...E!==void 0&&{input_transformations:E}}),yield Se("message_stop",{type:"message_stop"});return}let $=yield*da({response:O,controller:u,indexBase:m,hasNext:R,onError:o,splice:{iterations:y,model:x}});if(!$.refused)return;p=$.refused.token,A=$.refused.stopDetails,E=$.refused.inputTransformations,f=T,w=$.refused.hasPrefillClaim?ua($.blocks):[],y.push(_i("message",x,$.refused.usage)),v=$.refused.usage,_=x,m=$.nextIndex}}async function*da(r){let{response:s,controller:e,indexBase:t,hasNext:n,onError:i,splice:o}=r,c=new mi(t),u,d=null,m;for await(let p of se.rawEvents(s,e)){let f=$e(p.data);switch(f?.type){case"message_start":{if(u=f.message.model,d=f.message.usage,"input_transformations"in f.message&&(m=f.message.input_transformations),o)continue;break}case"content_block_start":{if(c.start(f),o){yield Se(f.type,f);continue}break}case"content_block_delta":{if(c.delta(f),o){yield Se(f.type,f);continue}break}case"content_block_stop":{if(c.stop(f),o){yield Se(f.type,f);continue}break}case"message_delta":{if(f.delta.stop_reason==="refusal"){let w=f.delta.stop_details?.type==="refusal"?f.delta.stop_details:null;if(w?.fallback_credit_token&&n){let _=ha(f.usage,d);return yield*c.closeOpenBlocks(),{refused:{token:w.fallback_credit_token,hasPrefillClaim:w.fallback_has_prefill_claim===!0,usage:_,stopDetails:w,inputTransformations:o?m:void 0},model:u,blocks:c.contentBlocks(),nextIndex:c.nextIndex}}w?.fallback_credit_token?i({kind:"chain_exhausted",message:"refusal but no fallback entries remain",event:f}):i({kind:"no_credit_token",message:"refusal stop_details has no fallback_credit_token",event:f})}if(o){let w=ha(f.usage,d);w.iterations=[...o.iterations,_i("fallback_message",o.model,w)],f.usage=w,!("input_transformations"in f)&&m!==void 0&&(f.input_transformations=m),yield Se("message_delta",f);continue}break}}yield Jl(p)}return{refused:null,model:u,blocks:c.contentBlocks(),nextIndex:c.nextIndex}}var mi=class{constructor(s=0){this.indexBase=s,this.blocks=[],this.open=[],this.nextIndex=s}contentBlocks(){return this.blocks.map(s=>s.block)}start(s){this.blocks.push({index:s.index,block:{...s.content_block}}),s.index+=this.indexBase,this.open.push(s.index),this.nextIndex=Math.max(this.nextIndex,s.index+1)}delta(s){Kl(this.blocks,s.index,s.delta),s.index+=this.indexBase}stop(s){s.index+=this.indexBase;let e=this.open.indexOf(s.index);e!==-1&&this.open.splice(e,1),this.nextIndex=Math.max(this.nextIndex,s.index+1)}*closeOpenBlocks(){for(let s of this.open)yield Se("content_block_stop",{type:"content_block_stop",index:s});this.open.length=0}};function pa(r){return{token:r,mode:"best_effort"}}function zl(r,{model:s,creditToken:e,continuation:t}){let n=JSON.parse(r.body);return n.model=s,n.fallback_credit_token=pa(e),t.length&&(n.messages=[...n.messages,{role:"assistant",content:t}]),{...r,headers:new Headers(r.headers),body:JSON.stringify(n)}}function Kl(r,s,e){let t=r.find(n=>n.index===s)?.block;if(t)switch(e.type){case"text_delta":{t.text=(t.text??"")+e.text;break}case"input_json_delta":{t._partial_json=(t._partial_json??"")+e.partial_json;break}case"citations_delta":(t.citations??(t.citations=[])).push(e.citation);break;case"thinking_delta":{t.thinking=(t.thinking??"")+e.thinking;break}case"signature_delta":{t.signature=e.signature;break}case"compaction_delta":break;default:}}function ua(r){return r.map(s=>{if(typeof s?._partial_json!="string")return s;let{_partial_json:e,...t}=s;return{...t,input:$e(e)??t.input}})}function Vl(r,s){let e=new Headers(r.headers),t=new Set(e.get("anthropic-beta")?.split(",").map(n=>n.trim()));for(let n of s)t.has(n)||(e.append("anthropic-beta",n),t.add(n));return e.set(ge,Fs(e.get(ge),"fallback-refusal-middleware")),{...r,headers:e}}function Se(r,s){let e={event:r,data:JSON.stringify(s),raw:[]};return fa.encode(ma(e))}function Jl(r){return fa.encode(r.raw.length?r.raw.join(`
|
|
42
|
+
`)+`
|
|
43
|
+
|
|
44
|
+
`:ma(r))}function _i(r,s,e){return{type:r,model:s,input_tokens:e?.input_tokens??0,output_tokens:e?.output_tokens??0,cache_read_input_tokens:e?.cache_read_input_tokens??0,cache_creation_input_tokens:e?.cache_creation_input_tokens??0,cache_creation:e?.cache_creation??null}}function ha(r,s){let e={...s??{},...r??{}};for(let t of Object.keys(e))e[t]==null&&s?.[t]!=null&&(e[t]=s[t]);return e}function ma(r){let s="";r.event!==null&&(s+=`event: ${r.event}
|
|
45
|
+
`);for(let e of r.data.split(`
|
|
46
|
+
`))s+=`data: ${e}
|
|
47
|
+
`;return s+`
|
|
48
|
+
`}function Yl(r,s){return()=>r.abort(s.reason)}export{g as a,a as b,k as c,F as d,z as e,fe as f,Ke as g,Yt as h,Ve as i,Je as j,Ye as k,Xe as l,Ge as m,Qe as n,Ze as o,et as p,jr as q,Zt as r,er as s,C as t,ar as u,Os as v,an as w,Ae as x,gt as y,af as z,Bo as A,Wo as B,ti as C,ia as D,oa as E,aa as F,ca as G,Ul as H};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as b,b as g,c as P}from"./chunk-3JTDWOAJ.js";import{i as N,j as R}from"./chunk-Y5E7ZCCX.js";import{m as L}from"./chunk-FE4MKOI4.js";var v=class extends Error{command;code;stderr;constructor(e,r,s,n){super(e),this.name="CommandError",this.command=r,this.code=s,this.stderr=n}};var B=async()=>{await b();let t=g();if(t===null)throw new Error("@eserstack/ajan native library is not available \u2014 EserAjanShellExec* requires FFI or command-mode WASM"+P());return t},j=t=>{let e=new Uint8Array(t.reduce((s,n)=>s+n.length,0)),r=0;for(let s of t)e.set(s,r),r+=s.length;return e},I=async t=>{let e=[],r=t.getReader();try{for(;;){let{done:s,value:n}=await r.read();if(s)break;n&&e.push(n)}}finally{r.releaseLock()}return e},O=(t,e)=>{let r=JSON.parse(t.symbols.EserAjanShellExecSpawn(JSON.stringify({command:e.command,args:e.args??[],cwd:e.cwd??"",env:e.env??[]})));if(r.error!==void 0)throw new Error(r.error);let s=r.handle,n=r.pid,o=!1,a=()=>o?-1:(o=!0,JSON.parse(t.symbols.EserAjanShellExecClose(s)).code??-1),p,u=new Promise(i=>{p=i}),c,y,f=!1,C=i=>{f||(f=!0,p({success:i===0,code:i}),c.close(),y.close())},S=()=>{if(f)return;let i=t.symbols.EserAjanShellExecRead(s);if(i==="null"){C(a());return}let m=JSON.parse(i);if(m.error!==void 0){if(f)return;f=!0;let A=new Error(m.error);c.error(A),y.error(A);return}let w=Uint8Array.from(atob(m.chunk??""),A=>A.charCodeAt(0));m.stream==="stderr"?y.enqueue(w):c.enqueue(w)},l=new ReadableStream({start(i){c=i},pull(){S()}}),h=new ReadableStream({start(i){y=i},pull(){S()}}),d=new WritableStream({write(i){let m=btoa(String.fromCharCode(...i)),w=JSON.parse(t.symbols.EserAjanShellExecWrite(JSON.stringify({handle:s,data:m})));if(w.error!==void 0)throw new Error(w.error)}});return{pid:n,stdin:d,stdout:l,stderr:h,status:u,async output(){let[i,m]=await Promise.all([I(l),I(h)]);return{...await u,stdout:j(i),stderr:j(m)}},kill(i){let m=a();C(m)}}},J=async t=>{let e=await B();return O(e,t)};var U=new TextEncoder,x=new TextDecoder,G=t=>t!==void 0?Object.entries(t).map(([e,r])=>`${e}=${r}`):void 0,E=class t{#t;#r;#e;constructor(e,r=[],s={}){this.#t=e,this.#r=r,this.#e={throwOnError:!0,stdout:"piped",stderr:"piped",...s}}cwd(e){return new t(this.#t,this.#r,{...this.#e,cwd:e})}env(e,r){let s=this.#e.env??{},n;return typeof e=="string"&&r!==void 0?n={...s,[e]:r}:e!==null&&typeof e=="object"?n={...s,...e}:n=s,new t(this.#t,this.#r,{...this.#e,env:n})}stdin(e){return new t(this.#t,this.#r,{...this.#e,stdin:e})}stdinText(e){return new t(this.#t,this.#r,{...this.#e,stdin:"piped",stdinText:e})}stdout(e){return new t(this.#t,this.#r,{...this.#e,stdout:e})}stderr(e){return new t(this.#t,this.#r,{...this.#e,stderr:e})}timeout(e){return new t(this.#t,this.#r,{...this.#e,timeout:e})}noThrow(){return new t(this.#t,this.#r,{...this.#e,throwOnError:!1})}quiet(){return new t(this.#t,this.#r,{...this.#e,stdout:"null",stderr:"null"})}printCommand(){let e=[this.#t,...this.#r].join(" ");return console.log(`$ ${e}`),this}async spawn(){if(!(this.#e.stdin==="piped"||this.#e.stdin==="inherit"||this.#e.stdout==="inherit"||this.#e.stderr==="inherit")){await b();let n=g();if(n!==null)try{let o=n.symbols.EserAjanShellExec(JSON.stringify({command:this.#t,args:this.#r,cwd:this.#e.cwd,env:G(this.#e.env),timeout:this.#e.timeout!==void 0?`${this.#e.timeout}ms`:void 0})),a=JSON.parse(o);if(!a.error){let p=U.encode(a.stdout),u=U.encode(a.stderr),c={code:a.code,success:a.code===0,stdout:p,stderr:u};if(!c.success&&this.#e.throwOnError===!0)throw new v(`Command failed with exit code ${c.code}: ${this.#t}`,this.#t,c.code,a.stderr);return c}}catch(o){if(o instanceof v)throw o}}let{runtime:r}=R,s=await r.exec.spawn(this.#t,this.#r,{cwd:this.#e.cwd,env:this.#e.env,stdin:this.#e.stdin,stdinText:this.#e.stdinText,stdout:this.#e.stdout,stderr:this.#e.stderr,signal:this.#e.timeout!==void 0?AbortSignal.timeout(this.#e.timeout):void 0});if(!s.success&&this.#e.throwOnError===!0){let n=x.decode(s.stderr);throw new v(`Command failed with exit code ${s.code}: ${this.#t}`,this.#t,s.code,n)}return s}async text(e="stdout"){let r=await this.spawn();switch(e){case"stdout":return x.decode(r.stdout).trim();case"stderr":return x.decode(r.stderr).trim();case"combined":return(x.decode(r.stdout)+x.decode(r.stderr)).trim()}}async json(){let e=await this.text();return JSON.parse(e)}async lines(){let e=await this.text();return e===""?[]:e.split(`
|
|
2
|
+
`)}async bytes(){return(await this.spawn()).stdout}async code(){return(await this.noThrow().spawn()).code}pipe(e){throw new Error("exec(...).pipe() is not implemented. It previously discarded the upstream output instead of writing it to the next command's stdin, so results were silently wrong. Build the pipeline with .child() and pipe the streams yourself: const a = exec`...`.child(); const b = exec`...`.child(); await a.stdout.pipeTo(b.stdin);")}child(){let e=g();if(e===null)throw new Error("@eserstack/ajan native library is not available \u2014 exec.child() requires FFI or command-mode WASM"+P());let r=G(this.#e.env);return O(e,{command:this.#t,args:this.#r,cwd:this.#e.cwd,env:r})}};var T=(t,e)=>{let r=[];for(let n=0;n<t.length;n++){let o=t[n];if(o!==void 0&&r.push(o),n<e.length){let a=e[n];Array.isArray(a)?r.push(a.map(p=>M(String(p))).join(" ")):a!=null&&r.push(M(String(a)))}}let s=r.join("").trim();return D(s)},M=t=>t===""?"''":/[\s"'\\$`]/.test(t)?`'${t.replace(/'/g,"'\\''")}'`:t,D=t=>{let e=[],r="",s=!1,n=!1,o=!1,a=!1;for(let u=0;u<t.length;u++){let c=t[u];if(o){r+=c,o=!1;continue}if(c==="\\"&&!s){o=!0;continue}if(c==="'"&&!n){s=!s,a=!0;continue}if(c==='"'&&!s){n=!n,a=!0;continue}if(c===" "&&!s&&!n){a&&(e.push(r),r="",a=!1);continue}r+=c,a=!0}a&&e.push(r);let p=e[0];return p===void 0?["",[]]:[p,e.slice(1)]};var W=(t,...e)=>{let[r,s]=T(t,e);return new E(r,s)};var q=async()=>{await b();let t=g();if(t===null)throw new Error("@eserstack/ajan native library is not available \u2014 EserAjanShellPty* requires FFI or command-mode WASM"+P());return t},z=t=>{let e="";for(let r of t)e+=String.fromCharCode(r);return btoa(e)},K=t=>Uint8Array.from(atob(t),e=>e.charCodeAt(0)),$=async t=>{let e=await q(),r=Object.entries({...t.env,TERM:"xterm-256color",COLUMNS:String(t.cols??80),LINES:String(t.rows??24)}).map(([d,i])=>`${d}=${i}`),s=JSON.parse(e.symbols.EserAjanShellPtySpawn(JSON.stringify({command:t.command,args:t.args??[],cwd:t.cwd??"",env:r,cols:t.cols??80,rows:t.rows??24})));if(s.error!==void 0)throw new Error(s.error);let n=s.handle,o=s.pid??-1,a=new TextDecoder,p=new TextEncoder,u=[],c=!1,y,f=new Promise(d=>{y=d}),C=()=>{if(c)return;c=!0;let d=a.decode();if(d.length>0)for(let m of u)m(d);let i=-1;try{i=JSON.parse(e.symbols.EserAjanShellPtyClose(n)).code??-1}catch{}y(i)},S=async()=>{try{for(;;){let d=await e.symbols.EserAjanShellPtyRead(n);if(d==="null")break;let i;try{i=JSON.parse(d)}catch{break}if(i.error!==void 0)break;if(i.chunk!==void 0&&i.chunk.length>0){let m=a.decode(K(i.chunk),{stream:!0});for(let w of u)w(m)}}}finally{C()}},l=!1,h=()=>{l||(l=!0,S())};return{onData(d){u.push(d),h()},write(d){try{e.symbols.EserAjanShellPtyWrite(JSON.stringify({handle:n,data:z(p.encode(d))}))}catch{}},resize(d,i){try{e.symbols.EserAjanShellPtyResize(JSON.stringify({handle:n,cols:d,rows:i}))}catch{}},kill(d){try{e.symbols.EserAjanShellPtyKill(JSON.stringify({handle:n,signal:d??"SIGTERM"}))}catch{}h()},get pid(){return o},get exitCode(){return f}}};var Q=/\x04/g,H=/^Script (started|done),? ?(output file is )?[^\n]*\n?/gm,Y=/^script: tcgetattr[^\n]*\n?/gm,_=t=>t.replace(Q,"").replace(H,"").replace(Y,""),X=(t,e)=>{let r=L();if(r==="darwin"){let s=e.map(o=>`'${o.replace(/'/g,"'\\''")}'`);return{cmd:"sh",args:["-c",`script -q /dev/null ${[t,...s].join(" ")} 2>/dev/null`],usesScript:!0}}return r==="linux"?{cmd:"sh",args:["-c",`script -qc '${(e.length>0?`${t} ${e.map(n=>`'${n.replace(/'/g,"'\\''")}'`).join(" ")}`:t).replace(/'/g,"'\\''")}' /dev/null 2>/dev/null`],usesScript:!0}:{cmd:t,args:e,usesScript:!1}},Z=async t=>{let e;try{e=N.env.get("ESERSTACK_PTY")}catch{}let r=!1;if(e!=="script")try{await b(),r=g()!==null}catch{r=!1}return r?await $(t):V(t)},V=async t=>{let{runtime:e}=R,r=t.args!==void 0?[...t.args]:[],s=X(t.command,r),n={...t.env,TERM:"xterm-256color",COLUMNS:String(t.cols??80),LINES:String(t.rows??24)},o=e.exec.spawnChild(s.cmd,[...s.args],{cwd:t.cwd,env:n,stdin:"piped",stdout:"piped",stderr:"piped"}),a=new TextDecoder,p=new TextEncoder,u=[],c=!1,y=l=>{let h=s.usesScript?_(l):l;if(h.length!==0)for(let d of u)d(h)},f=async l=>{let h=l.getReader();try{for(;;){let{done:d,value:i}=await h.read();if(d)break;y(a.decode(i))}}catch{}finally{h.releaseLock()}},C=()=>{c||(c=!0,o.stdout&&f(o.stdout),o.stderr&&f(o.stderr))},S=null;return o.stdin&&(S=o.stdin.getWriter()),{onData(l){u.push(l),C()},write(l){S?.write(p.encode(l)).catch(()=>{})},resize(l,h){},kill(l){try{o.kill(l==="SIGKILL"?"SIGKILL":"SIGTERM")}catch{}},get pid(){return o.pid},get exitCode(){return o.status.then(l=>l.code)}}};var k=class{#t=new Map;get size(){return this.#t.size}add(e,r){let s={id:e,process:r,active:!0};return this.#t.set(e,s),r.exitCode.then(()=>{s.active=!1}).catch(()=>{s.active=!1}),s}get(e){return this.#t.get(e)}remove(e){let r=this.#t.get(e);return r===void 0?!1:(r.active&&r.process.kill(),this.#t.delete(e),!0)}list(){return[...this.#t.values()]}async killAll(e="SIGTERM"){for(let n of this.#t.values())n.active&&n.process.kill(e);let r=3e3,s=Date.now();for(let n of this.#t.values())if(n.active){let o=r-(Date.now()-s);o>0&&await Promise.race([n.process.exitCode,new Promise(a=>setTimeout(a,o))])}}forceKillAll(){for(let e of this.#t.values())e.active&&(e.process.kill("SIGKILL"),e.active=!1);this.#t.clear()}};export{v as a,O as b,J as c,E as d,T as e,W as f,Z as g,k as h};
|