@swifty.js/swifty 0.0.31 → 0.0.33

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.
Files changed (86) hide show
  1. package/README.md +110 -3
  2. package/dist/acp-5WRTN2LL.js +14 -0
  3. package/dist/agent-3CAPJCPD.js +4 -0
  4. package/dist/anthropic-FXRRA63E.js +4 -0
  5. package/dist/{bwrap-TPE6G4BM.js → bwrap-ZTS67W2K.js} +1 -1
  6. package/dist/checker-3O7QF7XV.js +4 -0
  7. package/dist/chunk-2U4IWZ6E.js +4 -0
  8. package/dist/chunk-35X3GW25.js +4 -0
  9. package/dist/chunk-4C3KJLJV.js +4 -0
  10. package/dist/chunk-4HSQBZBI.js +4 -0
  11. package/dist/{chunk-AGJYBJ5M.js → chunk-4PQYUHSN.js} +1 -1
  12. package/dist/chunk-6I3HEMIE.js +4 -0
  13. package/dist/{chunk-C3WGLVVZ.js → chunk-7JQHFZRD.js} +2 -2
  14. package/dist/chunk-C5WLP3DH.js +5 -0
  15. package/dist/chunk-FUKVR3XO.js +608 -0
  16. package/dist/chunk-FZORZF22.js +16 -0
  17. package/dist/chunk-G2TE2QZM.js +4 -0
  18. package/dist/chunk-I7XJSLRI.js +4 -0
  19. package/dist/{chunk-OQCEP2F5.js → chunk-IKQTIDRL.js} +1 -1
  20. package/dist/chunk-IZ7QOBSB.js +4 -0
  21. package/dist/chunk-LC7ZWLIH.js +4 -0
  22. package/dist/chunk-LHSUYZO5.js +4 -0
  23. package/dist/chunk-M4D66APS.js +67 -0
  24. package/dist/chunk-NAAAN2TD.js +60 -0
  25. package/dist/chunk-NCZR3AGA.js +65 -0
  26. package/dist/{server-BNT2IIKB.js → chunk-PXQD6GWP.js} +15 -22
  27. package/dist/{chunk-FPQ2LBL4.js → chunk-QQVDL4QT.js} +1 -1
  28. package/dist/{chunk-TCQ4EB4G.js → chunk-TNF3EHFY.js} +1 -1
  29. package/dist/chunk-XGUH7SGV.js +4 -0
  30. package/dist/chunk-YIKI3EPG.js +150 -0
  31. package/dist/chunk-YKWIZE5D.js +4 -0
  32. package/dist/{devtools-OJ75EP3T.js → devtools-WJM4UVVT.js} +1 -1
  33. package/dist/esm-46WSO26W.js +4 -0
  34. package/dist/esm-4DBD7ONK.js +229 -0
  35. package/dist/esm-6EDGM6QS.js +4 -0
  36. package/dist/esm-D6BB3FBR.js +4 -0
  37. package/dist/esm-P2KEXEEK.js +4 -0
  38. package/dist/esm-XYKZYVLV.js +4 -0
  39. package/dist/esm-YJVVI2QX.js +4 -0
  40. package/dist/getMachineId-bsd-NBOQ3GRQ.js +4 -0
  41. package/dist/getMachineId-darwin-6VBNSUFR.js +5 -0
  42. package/dist/getMachineId-linux-RQ33NIOO.js +4 -0
  43. package/dist/getMachineId-unsupported-IWOYPUHZ.js +4 -0
  44. package/dist/getMachineId-win-ITT3WXP6.js +4 -0
  45. package/dist/lib/agent-NNYCUIOF.js +10 -0
  46. package/dist/lib/{anthropic-R6DMXE7U.js → anthropic-B33M2AVN.js} +4 -4
  47. package/dist/lib/{checker-M7RKMKJQ.js → checker-UPY4CXUL.js} +3 -3
  48. package/dist/lib/{chunk-OQIQOU5S.js → chunk-3OFLDUAW.js} +121 -1
  49. package/dist/lib/{chunk-EY7HE52Q.js → chunk-3XCGUKGJ.js} +18 -24
  50. package/dist/lib/{chunk-J6AV7SIF.js → chunk-AFYPVA5C.js} +261 -25
  51. package/dist/lib/{chunk-FZ4Y6MBN.js → chunk-BCBD34D2.js} +1 -1
  52. package/dist/lib/{chunk-A4MXZA5Q.js → chunk-CFYAZWDA.js} +10 -4
  53. package/dist/lib/{chunk-4MDCRPVV.js → chunk-FODSMOWP.js} +6 -6
  54. package/dist/lib/chunk-GTHYQZRL.js +31 -0
  55. package/dist/lib/{chunk-EWE5IWZE.js → chunk-LDWFI6MR.js} +15 -4
  56. package/dist/lib/{chunk-OEPCNATU.js → chunk-TJLAJGG4.js} +2 -2
  57. package/dist/lib/index.d.ts +2339 -1581
  58. package/dist/lib/index.js +12210 -10961
  59. package/dist/lib/{openai-5N42ZYIJ.js → openai-C2PZFGJ2.js} +3 -3
  60. package/dist/lib/providers-UJEWP7C7.js +419 -0
  61. package/dist/lib/{tool-filter-XG2GXFVN.js → tool-filter-BFEINZIA.js} +1 -1
  62. package/dist/main.js +190 -183
  63. package/dist/{node-4LTSRXL2.js → node-A6KBFKOV.js} +1 -1
  64. package/dist/{openai-NQYARTT6.js → openai-WPEICAZ4.js} +1 -1
  65. package/dist/providers-WNYZUMZ3.js +6 -0
  66. package/dist/seatbelt-PSPJ5LBR.js +5 -0
  67. package/dist/server-YPBLBRDN.js +4 -0
  68. package/dist/src-3A5BCUSZ.js +4 -0
  69. package/dist/src-CRYFVH7Y.js +12 -0
  70. package/dist/src-Y77IB66J.js +4 -0
  71. package/dist/src-ZCW4GCG2.js +4 -0
  72. package/dist/{tool-filter-5NDJMSTD.js → tool-filter-X6IYME2K.js} +1 -1
  73. package/dist/turndown.es-WNOSVZF6.js +83 -0
  74. package/package.json +38 -15
  75. package/dist/agent-O6C4FCQY.js +0 -4
  76. package/dist/anthropic-CFM2DXMB.js +0 -4
  77. package/dist/checker-A6PGACKZ.js +0 -4
  78. package/dist/chunk-4ABFUBO4.js +0 -601
  79. package/dist/chunk-AQ3A5CF4.js +0 -5
  80. package/dist/chunk-MVVSONAE.js +0 -4
  81. package/dist/chunk-OTVZGPHD.js +0 -121
  82. package/dist/chunk-X3UA5OZL.js +0 -4
  83. package/dist/chunk-Y2UUXOQA.js +0 -4
  84. package/dist/chunk-YAXZ2OUD.js +0 -150
  85. package/dist/lib/agent-YRTROHXU.js +0 -10
  86. package/dist/seatbelt-YXUQ5XR3.js +0 -5
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __swiftyCreateRequire } from "node:module";
3
3
  const require = __swiftyCreateRequire(import.meta.url);
4
- import{b as wr,d as ri}from"./chunk-X3UA5OZL.js";var po=wr(Z=>{"use strict";var Ui=Z&&Z.__extends||(function(){var s=function(e,t){return s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)n.hasOwnProperty(o)&&(r[o]=n[o])},s(e,t)};return function(e,t){s(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(Z,"__esModule",{value:!0});var H=256,Ws=(function(){function s(e){e===void 0&&(e="="),this._paddingCharacter=e}return s.prototype.encodedLength=function(e){return this._paddingCharacter?(e+2)/3*4|0:(e*8+5)/6|0},s.prototype.encode=function(e){for(var t="",r=0;r<e.length-2;r+=3){var n=e[r]<<16|e[r+1]<<8|e[r+2];t+=this._encodeByte(n>>>18&63),t+=this._encodeByte(n>>>12&63),t+=this._encodeByte(n>>>6&63),t+=this._encodeByte(n>>>0&63)}var o=e.length-r;if(o>0){var n=e[r]<<16|(o===2?e[r+1]<<8:0);t+=this._encodeByte(n>>>18&63),t+=this._encodeByte(n>>>12&63),o===2?t+=this._encodeByte(n>>>6&63):t+=this._paddingCharacter||"",t+=this._paddingCharacter||""}return t},s.prototype.maxDecodedLength=function(e){return this._paddingCharacter?e/4*3|0:(e*6+7)/8|0},s.prototype.decodedLength=function(e){return this.maxDecodedLength(e.length-this._getPaddingLength(e))},s.prototype.decode=function(e){if(e.length===0)return new Uint8Array(0);for(var t=this._getPaddingLength(e),r=e.length-t,n=new Uint8Array(this.maxDecodedLength(r)),o=0,a=0,c=0,l=0,h=0,b=0,d=0;a<r-4;a+=4)l=this._decodeChar(e.charCodeAt(a+0)),h=this._decodeChar(e.charCodeAt(a+1)),b=this._decodeChar(e.charCodeAt(a+2)),d=this._decodeChar(e.charCodeAt(a+3)),n[o++]=l<<2|h>>>4,n[o++]=h<<4|b>>>2,n[o++]=b<<6|d,c|=l&H,c|=h&H,c|=b&H,c|=d&H;if(a<r-1&&(l=this._decodeChar(e.charCodeAt(a)),h=this._decodeChar(e.charCodeAt(a+1)),n[o++]=l<<2|h>>>4,c|=l&H,c|=h&H),a<r-2&&(b=this._decodeChar(e.charCodeAt(a+2)),n[o++]=h<<4|b>>>2,c|=b&H),a<r-3&&(d=this._decodeChar(e.charCodeAt(a+3)),n[o++]=b<<6|d,c|=d&H),c!==0)throw new Error("Base64Coder: incorrect characters for decoding");return n},s.prototype._encodeByte=function(e){var t=e;return t+=65,t+=25-e>>>8&6,t+=51-e>>>8&-75,t+=61-e>>>8&-15,t+=62-e>>>8&3,String.fromCharCode(t)},s.prototype._decodeChar=function(e){var t=H;return t+=(42-e&e-44)>>>8&-H+e-43+62,t+=(46-e&e-48)>>>8&-H+e-47+63,t+=(47-e&e-58)>>>8&-H+e-48+52,t+=(64-e&e-91)>>>8&-H+e-65+0,t+=(96-e&e-123)>>>8&-H+e-97+26,t},s.prototype._getPaddingLength=function(e){var t=0;if(this._paddingCharacter){for(var r=e.length-1;r>=0&&e[r]===this._paddingCharacter;r--)t++;if(e.length<4||t>2)throw new Error("Base64Coder: incorrect padding")}return t},s})();Z.Coder=Ws;var Zt=new Ws;function ji(s){return Zt.encode(s)}Z.encode=ji;function Wi(s){return Zt.decode(s)}Z.decode=Wi;var ho=(function(s){Ui(e,s);function e(){return s!==null&&s.apply(this,arguments)||this}return e.prototype._encodeByte=function(t){var r=t;return r+=65,r+=25-t>>>8&6,r+=51-t>>>8&-75,r+=61-t>>>8&-13,r+=62-t>>>8&49,String.fromCharCode(r)},e.prototype._decodeChar=function(t){var r=H;return r+=(44-t&t-46)>>>8&-H+t-45+62,r+=(94-t&t-96)>>>8&-H+t-95+63,r+=(47-t&t-58)>>>8&-H+t-48+52,r+=(64-t&t-91)>>>8&-H+t-65+0,r+=(96-t&t-123)>>>8&-H+t-97+26,r},e})(Ws);Z.URLSafeCoder=ho;var fo=new ho;function qi(s){return fo.encode(s)}Z.encodeURLSafe=qi;function Ji(s){return fo.decode(s)}Z.decodeURLSafe=Ji;Z.encodedLength=function(s){return Zt.encodedLength(s)};Z.maxDecodedLength=function(s){return Zt.maxDecodedLength(s)};Z.decodedLength=function(s){return Zt.decodedLength(s)}});var go=wr((mo,Dr)=>{"use strict";(function(s,e){var t={};e(t);var r=t.default;for(var n in t)r[n]=t[n];typeof Dr=="object"&&typeof Dr.exports=="object"?Dr.exports=r:typeof define=="function"&&define.amd?define(function(){return r}):s.sha256=r})(mo,function(s){"use strict";s.__esModule=!0,s.digestLength=32,s.blockSize=64;var e=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function t(d,f,p,y,v){for(var S,k,w,I,R,P,V,M,L,N,$,te,$e;v>=64;){for(S=f[0],k=f[1],w=f[2],I=f[3],R=f[4],P=f[5],V=f[6],M=f[7],N=0;N<16;N++)$=y+N*4,d[N]=(p[$]&255)<<24|(p[$+1]&255)<<16|(p[$+2]&255)<<8|p[$+3]&255;for(N=16;N<64;N++)L=d[N-2],te=(L>>>17|L<<15)^(L>>>19|L<<13)^L>>>10,L=d[N-15],$e=(L>>>7|L<<25)^(L>>>18|L<<14)^L>>>3,d[N]=(te+d[N-7]|0)+($e+d[N-16]|0);for(N=0;N<64;N++)te=(((R>>>6|R<<26)^(R>>>11|R<<21)^(R>>>25|R<<7))+(R&P^~R&V)|0)+(M+(e[N]+d[N]|0)|0)|0,$e=((S>>>2|S<<30)^(S>>>13|S<<19)^(S>>>22|S<<10))+(S&k^S&w^k&w)|0,M=V,V=P,P=R,R=I+te|0,I=w,w=k,k=S,S=te+$e|0;f[0]+=S,f[1]+=k,f[2]+=w,f[3]+=I,f[4]+=R,f[5]+=P,f[6]+=V,f[7]+=M,y+=64,v-=64}return y}var r=(function(){function d(){this.digestLength=s.digestLength,this.blockSize=s.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return d.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},d.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()},d.prototype.update=function(f,p){if(p===void 0&&(p=f.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");var y=0;if(this.bytesHashed+=p,this.bufferLength>0){for(;this.bufferLength<64&&p>0;)this.buffer[this.bufferLength++]=f[y++],p--;this.bufferLength===64&&(t(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(p>=64&&(y=t(this.temp,this.state,f,y,p),p%=64);p>0;)this.buffer[this.bufferLength++]=f[y++],p--;return this},d.prototype.finish=function(f){if(!this.finished){var p=this.bytesHashed,y=this.bufferLength,v=p/536870912|0,S=p<<3,k=p%64<56?64:128;this.buffer[y]=128;for(var w=y+1;w<k-8;w++)this.buffer[w]=0;this.buffer[k-8]=v>>>24&255,this.buffer[k-7]=v>>>16&255,this.buffer[k-6]=v>>>8&255,this.buffer[k-5]=v>>>0&255,this.buffer[k-4]=S>>>24&255,this.buffer[k-3]=S>>>16&255,this.buffer[k-2]=S>>>8&255,this.buffer[k-1]=S>>>0&255,t(this.temp,this.state,this.buffer,0,k),this.finished=!0}for(var w=0;w<8;w++)f[w*4+0]=this.state[w]>>>24&255,f[w*4+1]=this.state[w]>>>16&255,f[w*4+2]=this.state[w]>>>8&255,f[w*4+3]=this.state[w]>>>0&255;return this},d.prototype.digest=function(){var f=new Uint8Array(this.digestLength);return this.finish(f),f},d.prototype._saveState=function(f){for(var p=0;p<this.state.length;p++)f[p]=this.state[p]},d.prototype._restoreState=function(f,p){for(var y=0;y<this.state.length;y++)this.state[y]=f[y];this.bytesHashed=p,this.finished=!1,this.bufferLength=0},d})();s.Hash=r;var n=(function(){function d(f){this.inner=new r,this.outer=new r,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var p=new Uint8Array(this.blockSize);if(f.length>this.blockSize)new r().update(f).finish(p).clean();else for(var y=0;y<f.length;y++)p[y]=f[y];for(var y=0;y<p.length;y++)p[y]^=54;this.inner.update(p);for(var y=0;y<p.length;y++)p[y]^=106;this.outer.update(p),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate);for(var y=0;y<p.length;y++)p[y]=0}return d.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},d.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()},d.prototype.update=function(f){return this.inner.update(f),this},d.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},d.prototype.digest=function(){var f=new Uint8Array(this.digestLength);return this.finish(f),f},d})();s.HMAC=n;function o(d){var f=new r().update(d),p=f.digest();return f.clean(),p}s.hash=o,s.default=o;function a(d,f){var p=new n(d).update(f),y=p.digest();return p.clean(),y}s.hmac=a;function c(d,f,p,y){var v=y[0];if(v===0)throw new Error("hkdf: cannot expand more");f.reset(),v>1&&f.update(d),p&&f.update(p),f.update(y),f.finish(d),y[0]++}var l=new Uint8Array(s.digestLength);function h(d,f,p,y){f===void 0&&(f=l),y===void 0&&(y=32);for(var v=new Uint8Array([1]),S=a(f,d),k=new n(S),w=new Uint8Array(k.digestLength),I=w.length,R=new Uint8Array(y),P=0;P<y;P++)I===w.length&&(c(w,k,p,v),I=0),R[P]=w[I++];return k.clean(),w.fill(0),v.fill(0),R}s.hkdf=h;function b(d,f,p,y){for(var v=new n(d),S=v.digestLength,k=new Uint8Array(4),w=new Uint8Array(S),I=new Uint8Array(S),R=new Uint8Array(y),P=0;P*S<y;P++){var V=P+1;k[0]=V>>>24&255,k[1]=V>>>16&255,k[2]=V>>>8&255,k[3]=V>>>0&255,v.reset(),v.update(f),v.update(k),v.finish(I);for(var M=0;M<S;M++)w[M]=I[M];for(var M=2;M<=p;M++){v.reset(),v.update(I).finish(I);for(var L=0;L<S;L++)w[L]^=I[L]}for(var M=0;M<S&&P*S+M<y;M++)R[P*S+M]=w[M]}for(var P=0;P<S;P++)w[P]=I[P]=0;for(var P=0;P<4;P++)k[P]=0;return v.clean(),R}s.pbkdf2=b})});var bo=wr(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.timingSafeEqual=Ki;function _o(s,e=""){if(!s)throw new Error(e)}function Ki(s,e){if(s.byteLength!==e.byteLength)return!1;s instanceof DataView||(s=new DataView(ArrayBuffer.isView(s)?s.buffer:s)),e instanceof DataView||(e=new DataView(ArrayBuffer.isView(e)?e.buffer:e)),_o(s instanceof DataView),_o(e instanceof DataView);let t=s.byteLength,r=0,n=-1;for(;++n<t;)r|=s.getUint8(n)^e.getUint8(n);return r===0}});var xo=wr(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.Webhook=_t.WebhookVerificationError=void 0;var yo=po(),Vi=go(),zi=bo(),wo=300,Js=class s extends Error{constructor(e){super(e),Object.setPrototypeOf(this,s.prototype),this.name="ExtendableError",this.stack=new Error(e).stack}},Se=class s extends Js{constructor(e){super(e),Object.setPrototypeOf(this,s.prototype),this.name="WebhookVerificationError"}};_t.WebhookVerificationError=Se;var Ur=class s{constructor(e,t){if(t?.format==="raw")e instanceof Uint8Array?this.key=e:this.key=Uint8Array.from(e,r=>r.charCodeAt(0));else{if(typeof e!="string")throw new Error("Expected secret to be of type string");e.startsWith(s.prefix)&&(e=e.substring(s.prefix.length)),this.key=yo.decode(e)}if(this.key.length===0)throw new Error("Secret can't be empty.")}verify(e,t,r){var n;let o=(n=r?.jsonParse)!==null&&n!==void 0?n:!0,a={};for(let v of Object.keys(t))a[v.toLowerCase()]=t[v];let c=a["webhook-id"],l=a["webhook-signature"],h=a["webhook-timestamp"];if(!l||!c||!h)throw new Se("Missing required headers");let b=this.verifyTimestamp(h),f=this.sign(c,b,e).split(",")[1],p=l.split(" "),y=new globalThis.TextEncoder;for(let v of p){let[S,k]=v.split(",");if(S==="v1"&&(0,zi.timingSafeEqual)(y.encode(k),y.encode(f))){let w=e.toString();return w===""?void 0:o?JSON.parse(w):void 0}}throw new Se("No matching signature found")}sign(e,t,r){if(typeof r!="string")if(r.constructor.name==="Buffer")r=r.toString();else throw new Error("Expected payload to be of type string or Buffer.");let n=new TextEncoder,o=Math.floor(t.getTime()/1e3),a=n.encode(`${e}.${o}.${r}`);return`v1,${yo.encode(Vi.hmac(this.key,a))}`}verifyTimestamp(e){let t=Math.floor(Date.now()/1e3),r=parseInt(e,10);if(Number.isNaN(r))throw new Se("Invalid Signature Headers");if(t-r>wo)throw new Se("Message timestamp too old");if(r>t+wo)throw new Se("Message timestamp too new");return new Date(r*1e3)}};_t.Webhook=Ur;Ur.prefix="whsec_"});function g(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t}function i(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)}function re(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}var Fe=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){let e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)};var _=class extends Error{},F=class s extends _{constructor(e,t,r,n,o){super(`${s.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.get("request-id"),this.error=t,this.type=o??null}static makeMessage(e,t,r){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new ue({message:r,cause:Fe(t)});let o=t,a=o?.error?.type;return e===400?new et(e,o,r,n,a):e===401?new tt(e,o,r,n,a):e===403?new rt(e,o,r,n,a):e===404?new st(e,o,r,n,a):e===409?new nt(e,o,r,n,a):e===422?new ot(e,o,r,n,a):e===429?new it(e,o,r,n,a):e>=500?new at(e,o,r,n,a):new s(e,o,r,n,a)}},W=class extends F{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ue=class extends F{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Ze=class extends ue{constructor({message:e}={}){super({message:e??"Request timed out."})}},Ut=class extends _{constructor(e,{cause:t}={}){super(e??"Retryable error."),t!==void 0&&(this.cause=t)}},et=class extends F{},tt=class extends F{},rt=class extends F{},st=class extends F{},nt=class extends F{},ot=class extends F{},it=class extends F{},at=class extends F{};var pe=class extends Error{constructor(e){let t=typeof e=="string"?e:e.map(r=>r.type==="text"?r.text:`[${r.type}]`).join(" ");super(t),this.name="ToolError",this.content=e}};function bs(){let s,e;return{promise:new Promise((r,n)=>{s=r,e=n}),resolve:s,reject:e}}var ct=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return ct=s.randomUUID.bind(s),s.randomUUID();let e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};var ni=/^[a-z][a-z0-9+.-]*:/i,mn=s=>ni.test(s),J=s=>(J=Array.isArray,J(s)),ys=J;function xr(s){return typeof s!="object"?{}:s??{}}function ws(s){if(!s)return!0;for(let e in s)return!1;return!0}function gn(s,e){return Object.prototype.hasOwnProperty.call(s,e)}var _n=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new _(`${s} must be an integer`);if(e<0)throw new _(`${s} must be a positive integer`);return e};var jt=s=>{try{return JSON.parse(s)}catch{return}};var ce=(s,e)=>new Promise(t=>{if(e?.aborted)return t();let r=()=>{clearTimeout(n),t()},n=setTimeout(()=>{e?.removeEventListener("abort",r),t()},s);e?.addEventListener("abort",r,{once:!0})});var se="0.104.2";var xn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function oi(){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 ii=()=>{let s=oi();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":yn(Deno.build.os),"X-Stainless-Arch":bn(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":se,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":yn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":bn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=ai();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ai(){if(typeof navigator>"u"||!navigator)return null;let s=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,o=r[2]||0,a=r[3]||0;return{browser:e,version:`${n}.${o}.${a}`}}}return null}var bn=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",yn=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),wn,Wt=()=>wn??(wn=ii());function Sn(){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 xs(...s){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...s)}function Sr(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return xs({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function qt(s){if(s[Symbol.asyncIterator])return s;let e=s.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function kn(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}let e=s.getReader(),t=e.cancel();e.releaseLock(),await t}var vn=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Ss="RFC3986",ks=s=>String(s),vs={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:ks},En="RFC1738";var kr=(s,e)=>(kr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),kr(s,e)),de=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var Es=1024,An=(s,e,t,r,n)=>{if(s.length===0)return s;let o=s;if(typeof s=="symbol"?o=Symbol.prototype.toString.call(s):typeof s!="string"&&(o=String(s)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let a="";for(let c=0;c<o.length;c+=Es){let l=o.length>=Es?o.slice(c,c+Es):o,h=[];for(let b=0;b<l.length;++b){let d=l.charCodeAt(b);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||n===En&&(d===40||d===41)){h[h.length]=l.charAt(b);continue}if(d<128){h[h.length]=de[d];continue}if(d<2048){h[h.length]=de[192|d>>6]+de[128|d&63];continue}if(d<55296||d>=57344){h[h.length]=de[224|d>>12]+de[128|d>>6&63]+de[128|d&63];continue}b+=1,d=65536+((d&1023)<<10|l.charCodeAt(b)&1023),h[h.length]=de[240|d>>18]+de[128|d>>12&63]+de[128|d>>6&63]+de[128|d&63]}a+=h.join("")}return a};function Rn(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function As(s,e){if(J(s)){let t=[];for(let r=0;r<s.length;r+=1)t.push(e(s[r]));return t}return e(s)}var Pn={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},Tn=function(s,e){Array.prototype.push.apply(s,J(e)?e:[e])},In,D={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:An,encodeValuesOnly:!1,format:Ss,formatter:ks,indices:!1,serializeDate(s){return(In??(In=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function ui(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var Rs={};function On(s,e,t,r,n,o,a,c,l,h,b,d,f,p,y,v,S,k){let w=s,I=k,R=0,P=!1;for(;(I=I.get(Rs))!==void 0&&!P;){let $=I.get(s);if(R+=1,typeof $<"u"){if($===R)throw new RangeError("Cyclic object value");P=!0}typeof I.get(Rs)>"u"&&(R=0)}if(typeof h=="function"?w=h(e,w):w instanceof Date?w=f?.(w):t==="comma"&&J(w)&&(w=As(w,function($){return $ instanceof Date?f?.($):$})),w===null){if(o)return l&&!v?l(e,D.encoder,S,"key",p):e;w=""}if(ui(w)||Rn(w)){if(l){let $=v?e:l(e,D.encoder,S,"key",p);return[y?.($)+"="+y?.(l(w,D.encoder,S,"value",p))]}return[y?.(e)+"="+y?.(String(w))]}let V=[];if(typeof w>"u")return V;let M;if(t==="comma"&&J(w))v&&l&&(w=As(w,l)),M=[{value:w.length>0?w.join(",")||null:void 0}];else if(J(h))M=h;else{let $=Object.keys(w);M=b?$.sort(b):$}let L=c?String(e).replace(/\./g,"%2E"):String(e),N=r&&J(w)&&w.length===1?L+"[]":L;if(n&&J(w)&&w.length===0)return N+"[]";for(let $=0;$<M.length;++$){let te=M[$],$e=typeof te=="object"&&typeof te.value<"u"?te.value:w[te];if(a&&$e===null)continue;let _s=d&&c?te.replace(/\./g,"%2E"):te,ti=J(w)?typeof t=="function"?t(N,_s):N:N+(d?"."+_s:"["+_s+"]");k.set(s,R);let pn=new WeakMap;pn.set(Rs,k),Tn(V,On($e,ti,t,r,n,o,a,c,t==="comma"&&v&&J(w)?null:l,h,b,d,f,p,y,v,S,pn))}return V}function di(s=D){if(typeof s.allowEmptyArrays<"u"&&typeof s.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys<"u"&&typeof s.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder<"u"&&typeof s.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=s.charset||D.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Ss;if(typeof s.format<"u"){if(!kr(vs,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=vs[t],n=D.filter;(typeof s.filter=="function"||J(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in Pn?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=D.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:D.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:D.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:D.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:D.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?D.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:D.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:D.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:D.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:D.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:D.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:D.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:D.strictNullHandling}}function Mn(s,e={}){let t=s,r=di(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):J(r.filter)&&(o=r.filter,n=o);let a=[];if(typeof t!="object"||t===null)return"";let c=Pn[r.arrayFormat],l=c==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let h=new WeakMap;for(let f=0;f<n.length;++f){let p=n[f];r.skipNulls&&t[p]===null||Tn(a,On(t[p],p,c,l,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,h))}let b=a.join(r.delimiter),d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),b.length>0?d+b:""}function Nn(s){return Mn(s,{arrayFormat:"brackets"})}var $n="urn:ietf:params:oauth:grant-type:jwt-bearer",Fn="refresh_token",vr="/v1/oauth/token",Le="oauth-2025-04-20",Ln="oidc-federation-2026-04-01",Hn=120,lt=30,Bn=5,Cn=1<<20;function Er(s){if(!s)return;let e;try{e=new URL(s)}catch(r){throw new O(`Invalid token endpoint base URL "${s}": ${r}`)}if(e.protocol==="https:")return;let t=e.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!(e.protocol==="http:"&&(t==="localhost"||t==="127.0.0.1"||t==="::1")))throw new O(`Refusing to send credential over non-https token endpoint "${s}"`)}async function Ar(s,e){let t=await pi(s),r;try{r=JSON.parse(t)}catch{throw new O(`Token endpoint returned non-JSON response (status ${s.status})`,s.status,z(t),e)}if(!r.access_token)throw new O(`Token endpoint response missing access_token: ${JSON.stringify(z(r))}`,s.status,z(r),e);if(r.token_type&&r.token_type.toLowerCase()!=="bearer")throw new O(`Token endpoint response: unsupported token_type "${r.token_type}" (want Bearer)`,s.status,z(r),e);return r}var Is=2e3,fi=new Set(["error","error_description","error_uri"]);function z(s){if(s==null)return s;if(typeof s=="string"){let e;try{e=JSON.parse(s)}catch{return s.length<=Is?s:s.slice(0,Is)+`... <${s.length-Is} more chars>`}return JSON.stringify(z(e))}if(typeof s=="object"&&!Array.isArray(s)){let e={};for(let[t,r]of Object.entries(s))fi.has(t)&&(e[t]=r);return e}return null}async function Rr(s,e=t=>console.warn(`anthropic-sdk: ${t}`)){if(typeof process>"u"||process.platform==="win32")return;let t=await import("fs"),r=s,n;try{r=await t.promises.realpath(s),n=await t.promises.stat(r)}catch{return}let o=n.mode&511;if(o&18)throw new O(`Credentials file at ${r} is group/world-writable (mode 0o${o.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${r}\`.`);if(o&36)throw new O(`Credentials file at ${r} is group/world-readable (mode 0o${o.toString(8)}); run \`chmod 600 ${r}\` before retrying.`);typeof process.getuid=="function"&&n.uid!==process.getuid()&&e(`credentials file at ${r} is owned by uid ${n.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function Ir(s,e){let t=await import("fs"),n=(await import("path")).dirname(s);await t.promises.mkdir(n,{recursive:!0,mode:448});let o=`${s}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{let a=await t.promises.open(o,"w",384);try{await a.writeFile(JSON.stringify(e,null,2)),await a.sync()}finally{await a.close()}await t.promises.rename(o,s)}catch(a){throw await t.promises.unlink(o).catch(()=>{}),a}try{let a=await t.promises.open(n,"r");try{await a.sync()}finally{await a.close()}}catch{}}async function pi(s){if(!s.body)return"";let e=s.body.getReader(),t=[],r=0;for(;;){let{done:o,value:a}=await e.read();if(o)break;if(r+a.length>Cn){let c=Cn-r;c>0&&t.push(a.subarray(0,c)),await e.cancel();break}t.push(a),r+=a.length}let n;if(t.length===1)n=t[0];else{n=new Uint8Array(t.reduce((a,c)=>a+c.length,0));let o=0;for(let a of t)n.set(a,o),o+=a.length}return new TextDecoder("utf-8").decode(n)}var O=class extends _{constructor(e,t=null,r=null,n=null){super(e),this.statusCode=t,this.body=r,this.requestId=n}};function le(){return Math.floor(Date.now()/1e3)}var Pr=class{constructor(e,t){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=e,this.onAdvisoryRefreshError=t}async getToken(){let e=this.nextForce;this.nextForce=!1;let t=this.cached;if(e||t==null)return(await this.refresh(e)).token;if(t.expiresAt==null)return t.token;let r=t.expiresAt-le();return r>Hn?t.token:r>lt?(this.backgroundRefresh(),t.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(e=!1){return this.pendingRefresh&&!e?this.pendingRefresh:this.doRefresh(e)}backgroundRefresh(){this.pendingRefresh||le()-this.lastAdvisoryError<Bn||this.doRefresh().catch(e=>{this.lastAdvisoryError=le(),this.onAdvisoryRefreshError?.(e)})}doRefresh(e=!1){return this.pendingRefresh=this.provider(e?{forceRefresh:!0}:void 0).then(t=>(this.cached=t,this.pendingRefresh=null,t),t=>{throw this.pendingRefresh=null,t}),this.pendingRefresh}};var A=s=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[s]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(s)?.trim()||void 0};function jn(s){let e=0;for(let n of s)e+=n.length;let t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var Dn;function ut(s){let e;return(Dn??(e=new globalThis.TextEncoder,Dn=e.encode.bind(e)))(s)}var Un;function Ps(s){let e;return(Un??(e=new globalThis.TextDecoder,Un=e.decode.bind(e)))(s)}var Kt="warn",Or={off:0,error:200,warn:300,info:400,debug:500},Mr=(s,e,t)=>{if(s){if(gn(Or,s))return s;t.warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(Or))}`)}};function Jt(){}function Tr(s,e,t){return!e||Or[s]>Or[t]?Jt:e[s].bind(e)}var mi={error:Jt,warn:Jt,info:Jt,debug:Jt},Wn=new WeakMap;function Os(s,e){let t=Wn.get(s);if(t&&t[0]===e)return t[1];let r={error:Tr("error",s,e),warn:Tr("warn",s,e),info:Tr("info",s,e),debug:Tr("debug",s,e)};return Wn.set(s,[e,r]),r}function T(s){let e=s.logger,t=s.logLevel??"off";return e?Os(e,t):mi}var qn,Ts;function Jn(){let s=A("ANTHROPIC_LOG");return(!Ts||s!==qn)&&(qn=s,Ts=Os(console,Mr(s,"process.env['ANTHROPIC_LOG']",Os(console,Kt))??Kt)),Ts}var he=s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s);var Nr="1.0",gi=/^[A-Za-z0-9_.-]+$/;function Kn(s){if(!s)throw new Error("profile name is empty");if(s==="."||s==="..")throw new Error(`profile name "${s}" is not allowed`);if(s.includes("/")||s.includes("\\"))throw new Error(`profile name "${s}" must not contain path separators`);if(!gi.test(s))throw new Error(`profile name "${s}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var Vn=async s=>{var e,t;let r=await Ms();if(r===null)return null;let n=s??await Xn();if(n===null)return null;Kn(n);let o=await import("fs"),c=(await import("path")).join(r,"configs",`${n}.json`),l;try{l=await o.promises.readFile(c,"utf-8")}catch(d){if(d?.code!=="ENOENT")throw new Error(`failed to read config file ${c}: ${d}`);l=null}if(l===null){let d=A("ANTHROPIC_ORGANIZATION_ID"),f=A("ANTHROPIC_IDENTITY_TOKEN_FILE"),p=A("ANTHROPIC_FEDERATION_RULE_ID");return p&&d?{fromFile:!1,config:{organization_id:d,workspace_id:A("ANTHROPIC_WORKSPACE_ID"),base_url:A("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:p,service_account_id:A("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:f?{source:"file",path:f}:void 0,scope:A("ANTHROPIC_SCOPE")}}}:null}let h;try{h=JSON.parse(l)}catch(d){throw new Error(`failed to parse config file ${c}: ${d}`)}if(!h.authentication)throw new Error(`config file ${c} is missing "authentication"`);let b=h.authentication.type;if(b!=="oidc_federation"&&b!=="user_oauth")throw new Error(`authentication.type "${b}" is not a known authentication type`);if(h.organization_id??(h.organization_id=A("ANTHROPIC_ORGANIZATION_ID")),h.workspace_id??(h.workspace_id=A("ANTHROPIC_WORKSPACE_ID")),h.base_url??(h.base_url=A("ANTHROPIC_BASE_URL")),(e=h.authentication).scope??(e.scope=A("ANTHROPIC_SCOPE")),h.authentication.type==="oidc_federation"){if(!h.authentication.identity_token){let d=A("ANTHROPIC_IDENTITY_TOKEN_FILE");d&&(h.authentication.identity_token={source:"file",path:d})}h.authentication.federation_rule_id||(h.authentication.federation_rule_id=A("ANTHROPIC_FEDERATION_RULE_ID")??""),(t=h.authentication).service_account_id??(t.service_account_id=A("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:h,fromFile:!0}};var zn=async(s,e)=>{if(s?.authentication.credentials_path)return s.authentication.credentials_path;let t=await Ms();if(!t)return null;let r=e??await Xn();return r?(Kn(r),(await import("path")).join(t,"credentials",`${r}.json`)):null},Ms=async()=>{if(!_i())return null;let s=await import("path"),e=A("ANTHROPIC_CONFIG_DIR");if(e)return e;if(Wt()["X-Stainless-OS"]==="Windows"){let o=A("APPDATA");if(o)return s.join(o,"Anthropic");let a=A("USERPROFILE");return a?s.join(a,"AppData","Roaming","Anthropic"):null}let r=A("XDG_CONFIG_HOME");if(r)return s.join(r,"anthropic");let n=A("HOME");return n?s.join(n,".config","anthropic"):null},_i=()=>{let s=Wt()["X-Stainless-Runtime"];return s==="node"||s==="deno"},Xn=async()=>{let s=await Ms();if(!s)return null;let e=A("ANTHROPIC_PROFILE");if(e)return e;let t=await import("fs"),n=(await import("path")).join(s,"active_config");try{return(await t.promises.readFile(n,"utf-8")).trim()||"default"}catch(o){if(o?.code!=="ENOENT")throw new Error(`failed to read ${n}: ${o}`);return"default"}};function Ns(s){if(!s)throw new _("Identity token file path is empty");return async()=>{let e=await import("fs"),t;try{t=await e.promises.readFile(s,"utf-8")}catch(n){throw new _(`Failed to read identity token file at ${s}: ${n}`)}let r=t.trim();if(!r)throw new _(`Identity token file at ${s} is empty`);return r}}function Gn(s){if(!s)throw new _("Identity token value is empty");return()=>s}function Yn(s){return async()=>{Er(s.baseURL);let e=await s.identityTokenProvider();if(e.length>16*1024)throw new O(`Identity token is ${Math.ceil(e.length/1024)} KiB, exceeds the 16 KiB assertion limit`);let t={grant_type:$n,assertion:e,federation_rule_id:s.federationRuleId,organization_id:s.organizationId};s.serviceAccountId&&(t.service_account_id=s.serviceAccountId),s.workspaceId&&(t.workspace_id=s.workspaceId);let r=`${s.baseURL}${vr}`,n;try{n=await s.fetch(r,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${Le},${Ln}`,"User-Agent":s.userAgent||`anthropic-sdk-typescript/${se} oidcFederationProvider`},body:JSON.stringify(t)})}catch(l){throw new O(`Failed to reach token endpoint ${r}: ${l}`)}let o=n.headers.get("Request-Id");if(!n.ok){let l=await n.text().catch(()=>""),h=z(l),b="";throw n.status===401&&(b=` Ensure your federation rule matches your identity token. ${s.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new O(`Token exchange failed with status ${n.status}${o?` (request-id ${o})`:""}: ${h}${b}`,n.status,h,o)}let a=await Ar(n,o),c=Number(a.expires_in);if(!Number.isFinite(c))throw new O(`Token endpoint response missing required fields: ${JSON.stringify(z(a))}`,n.status,z(a),o);return{token:a.access_token,expiresAt:le()+c}}}function Qn(s){return async e=>{let t=await import("fs");await Rr(s.credentialsPath,s.onSafetyWarning);let r;try{r=await t.promises.readFile(s.credentialsPath,"utf-8")}catch(S){throw new O(`Credentials file not found at ${s.credentialsPath}: ${S}`)}let n;try{n=JSON.parse(r)}catch(S){throw new O(`Credentials file at ${s.credentialsPath} is not valid JSON: ${S}`)}let o=n.access_token;if(!o)throw new O(`Credentials file at ${s.credentialsPath} must include 'access_token'`);let a=n.expires_at;if(!e?.forceRefresh&&(a==null||le()<a-lt))return{token:o,expiresAt:a??null};let c=n.refresh_token;if(!s.clientId||!c)throw new O(`Access token at ${s.credentialsPath} has expired and no refresh is available (client_id ${s.clientId?"set":"empty"}, refresh_token ${c?"set":"empty"})`);Er(s.baseURL);let l={grant_type:Fn,refresh_token:c,client_id:s.clientId},h=`${s.baseURL}${vr}`,b;try{b=await s.fetch(h,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":Le,"User-Agent":s.userAgent||`anthropic-sdk-typescript/${se} userOAuthProvider`},body:JSON.stringify(l)})}catch(S){throw new O(`User OAuth refresh failed to reach token endpoint: ${S}`)}let d=b.headers.get("Request-Id");if(!b.ok){let S=await b.text().catch(()=>"");throw new O(`User OAuth refresh failed (HTTP ${b.status}): ${z(S)}`,b.status,z(S),d)}let f=await Ar(b,d),p=Number(f.expires_in);if(!Number.isFinite(p))throw new O(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(z(f))}`,b.status,z(f),d);let y=le()+p,v=f.refresh_token||c;return await Ir(s.credentialsPath,{...n,version:Nr,type:"oauth_token",access_token:f.access_token,expires_at:y,refresh_token:v}),{token:f.access_token,expiresAt:y}}}function Cs(s,e){let t=s.authentication.credentials_path??null,r=(s.base_url||e.baseURL).replace(/\/+$/,""),n=bi(s,t,r,e),o={};return s.workspace_id&&s.authentication.type==="user_oauth"&&(o["anthropic-workspace-id"]=s.workspace_id),{provider:n,extraHeaders:o,baseURL:s.base_url||void 0}}async function Zn(s,e){let t=await Vn(e);if(!t)return null;let{config:r,fromFile:n}=t,o=r.authentication.credentials_path||!n?r:{...r,authentication:{...r.authentication,credentials_path:await zn(r,e)??void 0}};return Cs(o,s)}function bi(s,e,t,r){switch(s.authentication.type){case"oidc_federation":{let n=s.authentication,o=yi(n);if(!o)throw new O("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 O("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");if(!s.organization_id)throw new O("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");let a=Yn({identityTokenProvider:o,federationRuleId:n.federation_rule_id,organizationId:s.organization_id,serviceAccountId:n.service_account_id,workspaceId:s.workspace_id,baseURL:t,fetch:r.fetch,userAgent:r.userAgent});return e?wi(a,e,r.onCacheWriteError,r.onSafetyWarning):a}case"user_oauth":{if(!e)throw new O("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return Qn({credentialsPath:e,clientId:s.authentication.client_id,baseURL:t,fetch:r.fetch,userAgent:r.userAgent,onSafetyWarning:r.onSafetyWarning})}default:{let n=s.authentication.type;throw new O(`authentication.type "${n}" is not a known authentication type`)}}}function yi(s){if(s.identity_token){let r=s.identity_token.source;if(r!=="file")throw new O(`identity_token.source "${r}" is not supported by this SDK version (only "file")`);if(!s.identity_token.path)throw new O('identity_token.source "file" requires a non-empty path');return Ns(s.identity_token.path)}let e=A("ANTHROPIC_IDENTITY_TOKEN_FILE");if(e)return Ns(e);let t=A("ANTHROPIC_IDENTITY_TOKEN");return t?Gn(t):null}function wi(s,e,t,r){return async n=>{let o=await import("fs");await Rr(e,r);let a;try{let l=await o.promises.readFile(e,"utf-8");a=JSON.parse(l);let h=a?.access_token;if(h&&!n?.forceRefresh){let b=a?.expires_at;if(b==null||le()<b-lt)return{token:h,expiresAt:b??null}}}catch(l){l?.code!=="ENOENT"&&!(l instanceof SyntaxError)&&t?.(l)}let c=await s(n);try{await Ir(e,{...a??{},version:Nr,type:"oauth_token",access_token:c.token,expires_at:c.expiresAt})}catch(l){t?.(l)}return c}}var G,Y,me=class{constructor(){G.set(this,void 0),Y.set(this,void 0),g(this,G,new Uint8Array,"f"),g(this,Y,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ut(e):e;g(this,G,jn([i(this,G,"f"),t]),"f");let r=[],n;for(;(n=xi(i(this,G,"f"),i(this,Y,"f")))!=null;){if(n.carriage&&i(this,Y,"f")==null){g(this,Y,n.index,"f");continue}if(i(this,Y,"f")!=null&&(n.index!==i(this,Y,"f")+1||n.carriage)){r.push(Ps(i(this,G,"f").subarray(0,i(this,Y,"f")-1))),g(this,G,i(this,G,"f").subarray(i(this,Y,"f")),"f"),g(this,Y,null,"f");continue}let o=i(this,Y,"f")!==null?n.preceding-1:n.preceding,a=Ps(i(this,G,"f").subarray(0,o));r.push(a),g(this,G,i(this,G,"f").subarray(n.index),"f"),g(this,Y,null,"f")}return r}flush(){return i(this,G,"f").length?this.decode(`
4
+ import{c as wr,e as ri}from"./chunk-IZ7QOBSB.js";var po=wr(Z=>{"use strict";var Ui=Z&&Z.__extends||(function(){var s=function(e,t){return s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)n.hasOwnProperty(o)&&(r[o]=n[o])},s(e,t)};return function(e,t){s(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(Z,"__esModule",{value:!0});var H=256,Ws=(function(){function s(e){e===void 0&&(e="="),this._paddingCharacter=e}return s.prototype.encodedLength=function(e){return this._paddingCharacter?(e+2)/3*4|0:(e*8+5)/6|0},s.prototype.encode=function(e){for(var t="",r=0;r<e.length-2;r+=3){var n=e[r]<<16|e[r+1]<<8|e[r+2];t+=this._encodeByte(n>>>18&63),t+=this._encodeByte(n>>>12&63),t+=this._encodeByte(n>>>6&63),t+=this._encodeByte(n>>>0&63)}var o=e.length-r;if(o>0){var n=e[r]<<16|(o===2?e[r+1]<<8:0);t+=this._encodeByte(n>>>18&63),t+=this._encodeByte(n>>>12&63),o===2?t+=this._encodeByte(n>>>6&63):t+=this._paddingCharacter||"",t+=this._paddingCharacter||""}return t},s.prototype.maxDecodedLength=function(e){return this._paddingCharacter?e/4*3|0:(e*6+7)/8|0},s.prototype.decodedLength=function(e){return this.maxDecodedLength(e.length-this._getPaddingLength(e))},s.prototype.decode=function(e){if(e.length===0)return new Uint8Array(0);for(var t=this._getPaddingLength(e),r=e.length-t,n=new Uint8Array(this.maxDecodedLength(r)),o=0,a=0,c=0,l=0,h=0,b=0,d=0;a<r-4;a+=4)l=this._decodeChar(e.charCodeAt(a+0)),h=this._decodeChar(e.charCodeAt(a+1)),b=this._decodeChar(e.charCodeAt(a+2)),d=this._decodeChar(e.charCodeAt(a+3)),n[o++]=l<<2|h>>>4,n[o++]=h<<4|b>>>2,n[o++]=b<<6|d,c|=l&H,c|=h&H,c|=b&H,c|=d&H;if(a<r-1&&(l=this._decodeChar(e.charCodeAt(a)),h=this._decodeChar(e.charCodeAt(a+1)),n[o++]=l<<2|h>>>4,c|=l&H,c|=h&H),a<r-2&&(b=this._decodeChar(e.charCodeAt(a+2)),n[o++]=h<<4|b>>>2,c|=b&H),a<r-3&&(d=this._decodeChar(e.charCodeAt(a+3)),n[o++]=b<<6|d,c|=d&H),c!==0)throw new Error("Base64Coder: incorrect characters for decoding");return n},s.prototype._encodeByte=function(e){var t=e;return t+=65,t+=25-e>>>8&6,t+=51-e>>>8&-75,t+=61-e>>>8&-15,t+=62-e>>>8&3,String.fromCharCode(t)},s.prototype._decodeChar=function(e){var t=H;return t+=(42-e&e-44)>>>8&-H+e-43+62,t+=(46-e&e-48)>>>8&-H+e-47+63,t+=(47-e&e-58)>>>8&-H+e-48+52,t+=(64-e&e-91)>>>8&-H+e-65+0,t+=(96-e&e-123)>>>8&-H+e-97+26,t},s.prototype._getPaddingLength=function(e){var t=0;if(this._paddingCharacter){for(var r=e.length-1;r>=0&&e[r]===this._paddingCharacter;r--)t++;if(e.length<4||t>2)throw new Error("Base64Coder: incorrect padding")}return t},s})();Z.Coder=Ws;var Zt=new Ws;function ji(s){return Zt.encode(s)}Z.encode=ji;function Wi(s){return Zt.decode(s)}Z.decode=Wi;var ho=(function(s){Ui(e,s);function e(){return s!==null&&s.apply(this,arguments)||this}return e.prototype._encodeByte=function(t){var r=t;return r+=65,r+=25-t>>>8&6,r+=51-t>>>8&-75,r+=61-t>>>8&-13,r+=62-t>>>8&49,String.fromCharCode(r)},e.prototype._decodeChar=function(t){var r=H;return r+=(44-t&t-46)>>>8&-H+t-45+62,r+=(94-t&t-96)>>>8&-H+t-95+63,r+=(47-t&t-58)>>>8&-H+t-48+52,r+=(64-t&t-91)>>>8&-H+t-65+0,r+=(96-t&t-123)>>>8&-H+t-97+26,r},e})(Ws);Z.URLSafeCoder=ho;var fo=new ho;function qi(s){return fo.encode(s)}Z.encodeURLSafe=qi;function Ji(s){return fo.decode(s)}Z.decodeURLSafe=Ji;Z.encodedLength=function(s){return Zt.encodedLength(s)};Z.maxDecodedLength=function(s){return Zt.maxDecodedLength(s)};Z.decodedLength=function(s){return Zt.decodedLength(s)}});var go=wr((mo,Dr)=>{"use strict";(function(s,e){var t={};e(t);var r=t.default;for(var n in t)r[n]=t[n];typeof Dr=="object"&&typeof Dr.exports=="object"?Dr.exports=r:typeof define=="function"&&define.amd?define(function(){return r}):s.sha256=r})(mo,function(s){"use strict";s.__esModule=!0,s.digestLength=32,s.blockSize=64;var e=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function t(d,f,p,y,v){for(var S,k,w,I,R,P,V,M,L,N,$,te,$e;v>=64;){for(S=f[0],k=f[1],w=f[2],I=f[3],R=f[4],P=f[5],V=f[6],M=f[7],N=0;N<16;N++)$=y+N*4,d[N]=(p[$]&255)<<24|(p[$+1]&255)<<16|(p[$+2]&255)<<8|p[$+3]&255;for(N=16;N<64;N++)L=d[N-2],te=(L>>>17|L<<15)^(L>>>19|L<<13)^L>>>10,L=d[N-15],$e=(L>>>7|L<<25)^(L>>>18|L<<14)^L>>>3,d[N]=(te+d[N-7]|0)+($e+d[N-16]|0);for(N=0;N<64;N++)te=(((R>>>6|R<<26)^(R>>>11|R<<21)^(R>>>25|R<<7))+(R&P^~R&V)|0)+(M+(e[N]+d[N]|0)|0)|0,$e=((S>>>2|S<<30)^(S>>>13|S<<19)^(S>>>22|S<<10))+(S&k^S&w^k&w)|0,M=V,V=P,P=R,R=I+te|0,I=w,w=k,k=S,S=te+$e|0;f[0]+=S,f[1]+=k,f[2]+=w,f[3]+=I,f[4]+=R,f[5]+=P,f[6]+=V,f[7]+=M,y+=64,v-=64}return y}var r=(function(){function d(){this.digestLength=s.digestLength,this.blockSize=s.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return d.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},d.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()},d.prototype.update=function(f,p){if(p===void 0&&(p=f.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");var y=0;if(this.bytesHashed+=p,this.bufferLength>0){for(;this.bufferLength<64&&p>0;)this.buffer[this.bufferLength++]=f[y++],p--;this.bufferLength===64&&(t(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(p>=64&&(y=t(this.temp,this.state,f,y,p),p%=64);p>0;)this.buffer[this.bufferLength++]=f[y++],p--;return this},d.prototype.finish=function(f){if(!this.finished){var p=this.bytesHashed,y=this.bufferLength,v=p/536870912|0,S=p<<3,k=p%64<56?64:128;this.buffer[y]=128;for(var w=y+1;w<k-8;w++)this.buffer[w]=0;this.buffer[k-8]=v>>>24&255,this.buffer[k-7]=v>>>16&255,this.buffer[k-6]=v>>>8&255,this.buffer[k-5]=v>>>0&255,this.buffer[k-4]=S>>>24&255,this.buffer[k-3]=S>>>16&255,this.buffer[k-2]=S>>>8&255,this.buffer[k-1]=S>>>0&255,t(this.temp,this.state,this.buffer,0,k),this.finished=!0}for(var w=0;w<8;w++)f[w*4+0]=this.state[w]>>>24&255,f[w*4+1]=this.state[w]>>>16&255,f[w*4+2]=this.state[w]>>>8&255,f[w*4+3]=this.state[w]>>>0&255;return this},d.prototype.digest=function(){var f=new Uint8Array(this.digestLength);return this.finish(f),f},d.prototype._saveState=function(f){for(var p=0;p<this.state.length;p++)f[p]=this.state[p]},d.prototype._restoreState=function(f,p){for(var y=0;y<this.state.length;y++)this.state[y]=f[y];this.bytesHashed=p,this.finished=!1,this.bufferLength=0},d})();s.Hash=r;var n=(function(){function d(f){this.inner=new r,this.outer=new r,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var p=new Uint8Array(this.blockSize);if(f.length>this.blockSize)new r().update(f).finish(p).clean();else for(var y=0;y<f.length;y++)p[y]=f[y];for(var y=0;y<p.length;y++)p[y]^=54;this.inner.update(p);for(var y=0;y<p.length;y++)p[y]^=106;this.outer.update(p),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate);for(var y=0;y<p.length;y++)p[y]=0}return d.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},d.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()},d.prototype.update=function(f){return this.inner.update(f),this},d.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},d.prototype.digest=function(){var f=new Uint8Array(this.digestLength);return this.finish(f),f},d})();s.HMAC=n;function o(d){var f=new r().update(d),p=f.digest();return f.clean(),p}s.hash=o,s.default=o;function a(d,f){var p=new n(d).update(f),y=p.digest();return p.clean(),y}s.hmac=a;function c(d,f,p,y){var v=y[0];if(v===0)throw new Error("hkdf: cannot expand more");f.reset(),v>1&&f.update(d),p&&f.update(p),f.update(y),f.finish(d),y[0]++}var l=new Uint8Array(s.digestLength);function h(d,f,p,y){f===void 0&&(f=l),y===void 0&&(y=32);for(var v=new Uint8Array([1]),S=a(f,d),k=new n(S),w=new Uint8Array(k.digestLength),I=w.length,R=new Uint8Array(y),P=0;P<y;P++)I===w.length&&(c(w,k,p,v),I=0),R[P]=w[I++];return k.clean(),w.fill(0),v.fill(0),R}s.hkdf=h;function b(d,f,p,y){for(var v=new n(d),S=v.digestLength,k=new Uint8Array(4),w=new Uint8Array(S),I=new Uint8Array(S),R=new Uint8Array(y),P=0;P*S<y;P++){var V=P+1;k[0]=V>>>24&255,k[1]=V>>>16&255,k[2]=V>>>8&255,k[3]=V>>>0&255,v.reset(),v.update(f),v.update(k),v.finish(I);for(var M=0;M<S;M++)w[M]=I[M];for(var M=2;M<=p;M++){v.reset(),v.update(I).finish(I);for(var L=0;L<S;L++)w[L]^=I[L]}for(var M=0;M<S&&P*S+M<y;M++)R[P*S+M]=w[M]}for(var P=0;P<S;P++)w[P]=I[P]=0;for(var P=0;P<4;P++)k[P]=0;return v.clean(),R}s.pbkdf2=b})});var bo=wr(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.timingSafeEqual=Ki;function _o(s,e=""){if(!s)throw new Error(e)}function Ki(s,e){if(s.byteLength!==e.byteLength)return!1;s instanceof DataView||(s=new DataView(ArrayBuffer.isView(s)?s.buffer:s)),e instanceof DataView||(e=new DataView(ArrayBuffer.isView(e)?e.buffer:e)),_o(s instanceof DataView),_o(e instanceof DataView);let t=s.byteLength,r=0,n=-1;for(;++n<t;)r|=s.getUint8(n)^e.getUint8(n);return r===0}});var xo=wr(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.Webhook=_t.WebhookVerificationError=void 0;var yo=po(),Vi=go(),zi=bo(),wo=300,Js=class s extends Error{constructor(e){super(e),Object.setPrototypeOf(this,s.prototype),this.name="ExtendableError",this.stack=new Error(e).stack}},Se=class s extends Js{constructor(e){super(e),Object.setPrototypeOf(this,s.prototype),this.name="WebhookVerificationError"}};_t.WebhookVerificationError=Se;var Ur=class s{constructor(e,t){if(t?.format==="raw")e instanceof Uint8Array?this.key=e:this.key=Uint8Array.from(e,r=>r.charCodeAt(0));else{if(typeof e!="string")throw new Error("Expected secret to be of type string");e.startsWith(s.prefix)&&(e=e.substring(s.prefix.length)),this.key=yo.decode(e)}if(this.key.length===0)throw new Error("Secret can't be empty.")}verify(e,t,r){var n;let o=(n=r?.jsonParse)!==null&&n!==void 0?n:!0,a={};for(let v of Object.keys(t))a[v.toLowerCase()]=t[v];let c=a["webhook-id"],l=a["webhook-signature"],h=a["webhook-timestamp"];if(!l||!c||!h)throw new Se("Missing required headers");let b=this.verifyTimestamp(h),f=this.sign(c,b,e).split(",")[1],p=l.split(" "),y=new globalThis.TextEncoder;for(let v of p){let[S,k]=v.split(",");if(S==="v1"&&(0,zi.timingSafeEqual)(y.encode(k),y.encode(f))){let w=e.toString();return w===""?void 0:o?JSON.parse(w):void 0}}throw new Se("No matching signature found")}sign(e,t,r){if(typeof r!="string")if(r.constructor.name==="Buffer")r=r.toString();else throw new Error("Expected payload to be of type string or Buffer.");let n=new TextEncoder,o=Math.floor(t.getTime()/1e3),a=n.encode(`${e}.${o}.${r}`);return`v1,${yo.encode(Vi.hmac(this.key,a))}`}verifyTimestamp(e){let t=Math.floor(Date.now()/1e3),r=parseInt(e,10);if(Number.isNaN(r))throw new Se("Invalid Signature Headers");if(t-r>wo)throw new Se("Message timestamp too old");if(r>t+wo)throw new Se("Message timestamp too new");return new Date(r*1e3)}};_t.Webhook=Ur;Ur.prefix="whsec_"});function g(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t}function i(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)}function re(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}var Fe=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){let e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)};var _=class extends Error{},F=class s extends _{constructor(e,t,r,n,o){super(`${s.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.get("request-id"),this.error=t,this.type=o??null}static makeMessage(e,t,r){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new ue({message:r,cause:Fe(t)});let o=t,a=o?.error?.type;return e===400?new et(e,o,r,n,a):e===401?new tt(e,o,r,n,a):e===403?new rt(e,o,r,n,a):e===404?new st(e,o,r,n,a):e===409?new nt(e,o,r,n,a):e===422?new ot(e,o,r,n,a):e===429?new it(e,o,r,n,a):e>=500?new at(e,o,r,n,a):new s(e,o,r,n,a)}},W=class extends F{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ue=class extends F{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Ze=class extends ue{constructor({message:e}={}){super({message:e??"Request timed out."})}},Ut=class extends _{constructor(e,{cause:t}={}){super(e??"Retryable error."),t!==void 0&&(this.cause=t)}},et=class extends F{},tt=class extends F{},rt=class extends F{},st=class extends F{},nt=class extends F{},ot=class extends F{},it=class extends F{},at=class extends F{};var pe=class extends Error{constructor(e){let t=typeof e=="string"?e:e.map(r=>r.type==="text"?r.text:`[${r.type}]`).join(" ");super(t),this.name="ToolError",this.content=e}};function bs(){let s,e;return{promise:new Promise((r,n)=>{s=r,e=n}),resolve:s,reject:e}}var ct=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return ct=s.randomUUID.bind(s),s.randomUUID();let e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};var ni=/^[a-z][a-z0-9+.-]*:/i,mn=s=>ni.test(s),J=s=>(J=Array.isArray,J(s)),ys=J;function xr(s){return typeof s!="object"?{}:s??{}}function ws(s){if(!s)return!0;for(let e in s)return!1;return!0}function gn(s,e){return Object.prototype.hasOwnProperty.call(s,e)}var _n=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new _(`${s} must be an integer`);if(e<0)throw new _(`${s} must be a positive integer`);return e};var jt=s=>{try{return JSON.parse(s)}catch{return}};var ce=(s,e)=>new Promise(t=>{if(e?.aborted)return t();let r=()=>{clearTimeout(n),t()},n=setTimeout(()=>{e?.removeEventListener("abort",r),t()},s);e?.addEventListener("abort",r,{once:!0})});var se="0.104.2";var xn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function oi(){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 ii=()=>{let s=oi();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":yn(Deno.build.os),"X-Stainless-Arch":bn(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":se,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":yn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":bn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=ai();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ai(){if(typeof navigator>"u"||!navigator)return null;let s=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,o=r[2]||0,a=r[3]||0;return{browser:e,version:`${n}.${o}.${a}`}}}return null}var bn=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",yn=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),wn,Wt=()=>wn??(wn=ii());function Sn(){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 xs(...s){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...s)}function Sr(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return xs({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function qt(s){if(s[Symbol.asyncIterator])return s;let e=s.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function kn(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}let e=s.getReader(),t=e.cancel();e.releaseLock(),await t}var vn=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Ss="RFC3986",ks=s=>String(s),vs={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:ks},En="RFC1738";var kr=(s,e)=>(kr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),kr(s,e)),de=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var Es=1024,An=(s,e,t,r,n)=>{if(s.length===0)return s;let o=s;if(typeof s=="symbol"?o=Symbol.prototype.toString.call(s):typeof s!="string"&&(o=String(s)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let a="";for(let c=0;c<o.length;c+=Es){let l=o.length>=Es?o.slice(c,c+Es):o,h=[];for(let b=0;b<l.length;++b){let d=l.charCodeAt(b);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||n===En&&(d===40||d===41)){h[h.length]=l.charAt(b);continue}if(d<128){h[h.length]=de[d];continue}if(d<2048){h[h.length]=de[192|d>>6]+de[128|d&63];continue}if(d<55296||d>=57344){h[h.length]=de[224|d>>12]+de[128|d>>6&63]+de[128|d&63];continue}b+=1,d=65536+((d&1023)<<10|l.charCodeAt(b)&1023),h[h.length]=de[240|d>>18]+de[128|d>>12&63]+de[128|d>>6&63]+de[128|d&63]}a+=h.join("")}return a};function Rn(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function As(s,e){if(J(s)){let t=[];for(let r=0;r<s.length;r+=1)t.push(e(s[r]));return t}return e(s)}var Pn={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},Tn=function(s,e){Array.prototype.push.apply(s,J(e)?e:[e])},In,D={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:An,encodeValuesOnly:!1,format:Ss,formatter:ks,indices:!1,serializeDate(s){return(In??(In=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function ui(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var Rs={};function On(s,e,t,r,n,o,a,c,l,h,b,d,f,p,y,v,S,k){let w=s,I=k,R=0,P=!1;for(;(I=I.get(Rs))!==void 0&&!P;){let $=I.get(s);if(R+=1,typeof $<"u"){if($===R)throw new RangeError("Cyclic object value");P=!0}typeof I.get(Rs)>"u"&&(R=0)}if(typeof h=="function"?w=h(e,w):w instanceof Date?w=f?.(w):t==="comma"&&J(w)&&(w=As(w,function($){return $ instanceof Date?f?.($):$})),w===null){if(o)return l&&!v?l(e,D.encoder,S,"key",p):e;w=""}if(ui(w)||Rn(w)){if(l){let $=v?e:l(e,D.encoder,S,"key",p);return[y?.($)+"="+y?.(l(w,D.encoder,S,"value",p))]}return[y?.(e)+"="+y?.(String(w))]}let V=[];if(typeof w>"u")return V;let M;if(t==="comma"&&J(w))v&&l&&(w=As(w,l)),M=[{value:w.length>0?w.join(",")||null:void 0}];else if(J(h))M=h;else{let $=Object.keys(w);M=b?$.sort(b):$}let L=c?String(e).replace(/\./g,"%2E"):String(e),N=r&&J(w)&&w.length===1?L+"[]":L;if(n&&J(w)&&w.length===0)return N+"[]";for(let $=0;$<M.length;++$){let te=M[$],$e=typeof te=="object"&&typeof te.value<"u"?te.value:w[te];if(a&&$e===null)continue;let _s=d&&c?te.replace(/\./g,"%2E"):te,ti=J(w)?typeof t=="function"?t(N,_s):N:N+(d?"."+_s:"["+_s+"]");k.set(s,R);let pn=new WeakMap;pn.set(Rs,k),Tn(V,On($e,ti,t,r,n,o,a,c,t==="comma"&&v&&J(w)?null:l,h,b,d,f,p,y,v,S,pn))}return V}function di(s=D){if(typeof s.allowEmptyArrays<"u"&&typeof s.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys<"u"&&typeof s.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder<"u"&&typeof s.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=s.charset||D.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Ss;if(typeof s.format<"u"){if(!kr(vs,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=vs[t],n=D.filter;(typeof s.filter=="function"||J(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in Pn?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=D.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:D.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:D.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:D.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:D.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?D.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:D.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:D.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:D.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:D.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:D.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:D.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:D.strictNullHandling}}function Mn(s,e={}){let t=s,r=di(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):J(r.filter)&&(o=r.filter,n=o);let a=[];if(typeof t!="object"||t===null)return"";let c=Pn[r.arrayFormat],l=c==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let h=new WeakMap;for(let f=0;f<n.length;++f){let p=n[f];r.skipNulls&&t[p]===null||Tn(a,On(t[p],p,c,l,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,h))}let b=a.join(r.delimiter),d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),b.length>0?d+b:""}function Nn(s){return Mn(s,{arrayFormat:"brackets"})}var $n="urn:ietf:params:oauth:grant-type:jwt-bearer",Fn="refresh_token",vr="/v1/oauth/token",Le="oauth-2025-04-20",Ln="oidc-federation-2026-04-01",Hn=120,lt=30,Bn=5,Cn=1<<20;function Er(s){if(!s)return;let e;try{e=new URL(s)}catch(r){throw new O(`Invalid token endpoint base URL "${s}": ${r}`)}if(e.protocol==="https:")return;let t=e.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!(e.protocol==="http:"&&(t==="localhost"||t==="127.0.0.1"||t==="::1")))throw new O(`Refusing to send credential over non-https token endpoint "${s}"`)}async function Ar(s,e){let t=await pi(s),r;try{r=JSON.parse(t)}catch{throw new O(`Token endpoint returned non-JSON response (status ${s.status})`,s.status,z(t),e)}if(!r.access_token)throw new O(`Token endpoint response missing access_token: ${JSON.stringify(z(r))}`,s.status,z(r),e);if(r.token_type&&r.token_type.toLowerCase()!=="bearer")throw new O(`Token endpoint response: unsupported token_type "${r.token_type}" (want Bearer)`,s.status,z(r),e);return r}var Is=2e3,fi=new Set(["error","error_description","error_uri"]);function z(s){if(s==null)return s;if(typeof s=="string"){let e;try{e=JSON.parse(s)}catch{return s.length<=Is?s:s.slice(0,Is)+`... <${s.length-Is} more chars>`}return JSON.stringify(z(e))}if(typeof s=="object"&&!Array.isArray(s)){let e={};for(let[t,r]of Object.entries(s))fi.has(t)&&(e[t]=r);return e}return null}async function Rr(s,e=t=>console.warn(`anthropic-sdk: ${t}`)){if(typeof process>"u"||process.platform==="win32")return;let t=await import("fs"),r=s,n;try{r=await t.promises.realpath(s),n=await t.promises.stat(r)}catch{return}let o=n.mode&511;if(o&18)throw new O(`Credentials file at ${r} is group/world-writable (mode 0o${o.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${r}\`.`);if(o&36)throw new O(`Credentials file at ${r} is group/world-readable (mode 0o${o.toString(8)}); run \`chmod 600 ${r}\` before retrying.`);typeof process.getuid=="function"&&n.uid!==process.getuid()&&e(`credentials file at ${r} is owned by uid ${n.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function Ir(s,e){let t=await import("fs"),n=(await import("path")).dirname(s);await t.promises.mkdir(n,{recursive:!0,mode:448});let o=`${s}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{let a=await t.promises.open(o,"w",384);try{await a.writeFile(JSON.stringify(e,null,2)),await a.sync()}finally{await a.close()}await t.promises.rename(o,s)}catch(a){throw await t.promises.unlink(o).catch(()=>{}),a}try{let a=await t.promises.open(n,"r");try{await a.sync()}finally{await a.close()}}catch{}}async function pi(s){if(!s.body)return"";let e=s.body.getReader(),t=[],r=0;for(;;){let{done:o,value:a}=await e.read();if(o)break;if(r+a.length>Cn){let c=Cn-r;c>0&&t.push(a.subarray(0,c)),await e.cancel();break}t.push(a),r+=a.length}let n;if(t.length===1)n=t[0];else{n=new Uint8Array(t.reduce((a,c)=>a+c.length,0));let o=0;for(let a of t)n.set(a,o),o+=a.length}return new TextDecoder("utf-8").decode(n)}var O=class extends _{constructor(e,t=null,r=null,n=null){super(e),this.statusCode=t,this.body=r,this.requestId=n}};function le(){return Math.floor(Date.now()/1e3)}var Pr=class{constructor(e,t){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=e,this.onAdvisoryRefreshError=t}async getToken(){let e=this.nextForce;this.nextForce=!1;let t=this.cached;if(e||t==null)return(await this.refresh(e)).token;if(t.expiresAt==null)return t.token;let r=t.expiresAt-le();return r>Hn?t.token:r>lt?(this.backgroundRefresh(),t.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(e=!1){return this.pendingRefresh&&!e?this.pendingRefresh:this.doRefresh(e)}backgroundRefresh(){this.pendingRefresh||le()-this.lastAdvisoryError<Bn||this.doRefresh().catch(e=>{this.lastAdvisoryError=le(),this.onAdvisoryRefreshError?.(e)})}doRefresh(e=!1){return this.pendingRefresh=this.provider(e?{forceRefresh:!0}:void 0).then(t=>(this.cached=t,this.pendingRefresh=null,t),t=>{throw this.pendingRefresh=null,t}),this.pendingRefresh}};var A=s=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[s]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(s)?.trim()||void 0};function jn(s){let e=0;for(let n of s)e+=n.length;let t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var Dn;function ut(s){let e;return(Dn??(e=new globalThis.TextEncoder,Dn=e.encode.bind(e)))(s)}var Un;function Ps(s){let e;return(Un??(e=new globalThis.TextDecoder,Un=e.decode.bind(e)))(s)}var Kt="warn",Or={off:0,error:200,warn:300,info:400,debug:500},Mr=(s,e,t)=>{if(s){if(gn(Or,s))return s;t.warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(Or))}`)}};function Jt(){}function Tr(s,e,t){return!e||Or[s]>Or[t]?Jt:e[s].bind(e)}var mi={error:Jt,warn:Jt,info:Jt,debug:Jt},Wn=new WeakMap;function Os(s,e){let t=Wn.get(s);if(t&&t[0]===e)return t[1];let r={error:Tr("error",s,e),warn:Tr("warn",s,e),info:Tr("info",s,e),debug:Tr("debug",s,e)};return Wn.set(s,[e,r]),r}function T(s){let e=s.logger,t=s.logLevel??"off";return e?Os(e,t):mi}var qn,Ts;function Jn(){let s=A("ANTHROPIC_LOG");return(!Ts||s!==qn)&&(qn=s,Ts=Os(console,Mr(s,"process.env['ANTHROPIC_LOG']",Os(console,Kt))??Kt)),Ts}var he=s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s);var Nr="1.0",gi=/^[A-Za-z0-9_.-]+$/;function Kn(s){if(!s)throw new Error("profile name is empty");if(s==="."||s==="..")throw new Error(`profile name "${s}" is not allowed`);if(s.includes("/")||s.includes("\\"))throw new Error(`profile name "${s}" must not contain path separators`);if(!gi.test(s))throw new Error(`profile name "${s}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var Vn=async s=>{var e,t;let r=await Ms();if(r===null)return null;let n=s??await Xn();if(n===null)return null;Kn(n);let o=await import("fs"),c=(await import("path")).join(r,"configs",`${n}.json`),l;try{l=await o.promises.readFile(c,"utf-8")}catch(d){if(d?.code!=="ENOENT")throw new Error(`failed to read config file ${c}: ${d}`);l=null}if(l===null){let d=A("ANTHROPIC_ORGANIZATION_ID"),f=A("ANTHROPIC_IDENTITY_TOKEN_FILE"),p=A("ANTHROPIC_FEDERATION_RULE_ID");return p&&d?{fromFile:!1,config:{organization_id:d,workspace_id:A("ANTHROPIC_WORKSPACE_ID"),base_url:A("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:p,service_account_id:A("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:f?{source:"file",path:f}:void 0,scope:A("ANTHROPIC_SCOPE")}}}:null}let h;try{h=JSON.parse(l)}catch(d){throw new Error(`failed to parse config file ${c}: ${d}`)}if(!h.authentication)throw new Error(`config file ${c} is missing "authentication"`);let b=h.authentication.type;if(b!=="oidc_federation"&&b!=="user_oauth")throw new Error(`authentication.type "${b}" is not a known authentication type`);if(h.organization_id??(h.organization_id=A("ANTHROPIC_ORGANIZATION_ID")),h.workspace_id??(h.workspace_id=A("ANTHROPIC_WORKSPACE_ID")),h.base_url??(h.base_url=A("ANTHROPIC_BASE_URL")),(e=h.authentication).scope??(e.scope=A("ANTHROPIC_SCOPE")),h.authentication.type==="oidc_federation"){if(!h.authentication.identity_token){let d=A("ANTHROPIC_IDENTITY_TOKEN_FILE");d&&(h.authentication.identity_token={source:"file",path:d})}h.authentication.federation_rule_id||(h.authentication.federation_rule_id=A("ANTHROPIC_FEDERATION_RULE_ID")??""),(t=h.authentication).service_account_id??(t.service_account_id=A("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:h,fromFile:!0}};var zn=async(s,e)=>{if(s?.authentication.credentials_path)return s.authentication.credentials_path;let t=await Ms();if(!t)return null;let r=e??await Xn();return r?(Kn(r),(await import("path")).join(t,"credentials",`${r}.json`)):null},Ms=async()=>{if(!_i())return null;let s=await import("path"),e=A("ANTHROPIC_CONFIG_DIR");if(e)return e;if(Wt()["X-Stainless-OS"]==="Windows"){let o=A("APPDATA");if(o)return s.join(o,"Anthropic");let a=A("USERPROFILE");return a?s.join(a,"AppData","Roaming","Anthropic"):null}let r=A("XDG_CONFIG_HOME");if(r)return s.join(r,"anthropic");let n=A("HOME");return n?s.join(n,".config","anthropic"):null},_i=()=>{let s=Wt()["X-Stainless-Runtime"];return s==="node"||s==="deno"},Xn=async()=>{let s=await Ms();if(!s)return null;let e=A("ANTHROPIC_PROFILE");if(e)return e;let t=await import("fs"),n=(await import("path")).join(s,"active_config");try{return(await t.promises.readFile(n,"utf-8")).trim()||"default"}catch(o){if(o?.code!=="ENOENT")throw new Error(`failed to read ${n}: ${o}`);return"default"}};function Ns(s){if(!s)throw new _("Identity token file path is empty");return async()=>{let e=await import("fs"),t;try{t=await e.promises.readFile(s,"utf-8")}catch(n){throw new _(`Failed to read identity token file at ${s}: ${n}`)}let r=t.trim();if(!r)throw new _(`Identity token file at ${s} is empty`);return r}}function Gn(s){if(!s)throw new _("Identity token value is empty");return()=>s}function Yn(s){return async()=>{Er(s.baseURL);let e=await s.identityTokenProvider();if(e.length>16*1024)throw new O(`Identity token is ${Math.ceil(e.length/1024)} KiB, exceeds the 16 KiB assertion limit`);let t={grant_type:$n,assertion:e,federation_rule_id:s.federationRuleId,organization_id:s.organizationId};s.serviceAccountId&&(t.service_account_id=s.serviceAccountId),s.workspaceId&&(t.workspace_id=s.workspaceId);let r=`${s.baseURL}${vr}`,n;try{n=await s.fetch(r,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${Le},${Ln}`,"User-Agent":s.userAgent||`anthropic-sdk-typescript/${se} oidcFederationProvider`},body:JSON.stringify(t)})}catch(l){throw new O(`Failed to reach token endpoint ${r}: ${l}`)}let o=n.headers.get("Request-Id");if(!n.ok){let l=await n.text().catch(()=>""),h=z(l),b="";throw n.status===401&&(b=` Ensure your federation rule matches your identity token. ${s.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new O(`Token exchange failed with status ${n.status}${o?` (request-id ${o})`:""}: ${h}${b}`,n.status,h,o)}let a=await Ar(n,o),c=Number(a.expires_in);if(!Number.isFinite(c))throw new O(`Token endpoint response missing required fields: ${JSON.stringify(z(a))}`,n.status,z(a),o);return{token:a.access_token,expiresAt:le()+c}}}function Qn(s){return async e=>{let t=await import("fs");await Rr(s.credentialsPath,s.onSafetyWarning);let r;try{r=await t.promises.readFile(s.credentialsPath,"utf-8")}catch(S){throw new O(`Credentials file not found at ${s.credentialsPath}: ${S}`)}let n;try{n=JSON.parse(r)}catch(S){throw new O(`Credentials file at ${s.credentialsPath} is not valid JSON: ${S}`)}let o=n.access_token;if(!o)throw new O(`Credentials file at ${s.credentialsPath} must include 'access_token'`);let a=n.expires_at;if(!e?.forceRefresh&&(a==null||le()<a-lt))return{token:o,expiresAt:a??null};let c=n.refresh_token;if(!s.clientId||!c)throw new O(`Access token at ${s.credentialsPath} has expired and no refresh is available (client_id ${s.clientId?"set":"empty"}, refresh_token ${c?"set":"empty"})`);Er(s.baseURL);let l={grant_type:Fn,refresh_token:c,client_id:s.clientId},h=`${s.baseURL}${vr}`,b;try{b=await s.fetch(h,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":Le,"User-Agent":s.userAgent||`anthropic-sdk-typescript/${se} userOAuthProvider`},body:JSON.stringify(l)})}catch(S){throw new O(`User OAuth refresh failed to reach token endpoint: ${S}`)}let d=b.headers.get("Request-Id");if(!b.ok){let S=await b.text().catch(()=>"");throw new O(`User OAuth refresh failed (HTTP ${b.status}): ${z(S)}`,b.status,z(S),d)}let f=await Ar(b,d),p=Number(f.expires_in);if(!Number.isFinite(p))throw new O(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(z(f))}`,b.status,z(f),d);let y=le()+p,v=f.refresh_token||c;return await Ir(s.credentialsPath,{...n,version:Nr,type:"oauth_token",access_token:f.access_token,expires_at:y,refresh_token:v}),{token:f.access_token,expiresAt:y}}}function Cs(s,e){let t=s.authentication.credentials_path??null,r=(s.base_url||e.baseURL).replace(/\/+$/,""),n=bi(s,t,r,e),o={};return s.workspace_id&&s.authentication.type==="user_oauth"&&(o["anthropic-workspace-id"]=s.workspace_id),{provider:n,extraHeaders:o,baseURL:s.base_url||void 0}}async function Zn(s,e){let t=await Vn(e);if(!t)return null;let{config:r,fromFile:n}=t,o=r.authentication.credentials_path||!n?r:{...r,authentication:{...r.authentication,credentials_path:await zn(r,e)??void 0}};return Cs(o,s)}function bi(s,e,t,r){switch(s.authentication.type){case"oidc_federation":{let n=s.authentication,o=yi(n);if(!o)throw new O("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 O("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");if(!s.organization_id)throw new O("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");let a=Yn({identityTokenProvider:o,federationRuleId:n.federation_rule_id,organizationId:s.organization_id,serviceAccountId:n.service_account_id,workspaceId:s.workspace_id,baseURL:t,fetch:r.fetch,userAgent:r.userAgent});return e?wi(a,e,r.onCacheWriteError,r.onSafetyWarning):a}case"user_oauth":{if(!e)throw new O("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return Qn({credentialsPath:e,clientId:s.authentication.client_id,baseURL:t,fetch:r.fetch,userAgent:r.userAgent,onSafetyWarning:r.onSafetyWarning})}default:{let n=s.authentication.type;throw new O(`authentication.type "${n}" is not a known authentication type`)}}}function yi(s){if(s.identity_token){let r=s.identity_token.source;if(r!=="file")throw new O(`identity_token.source "${r}" is not supported by this SDK version (only "file")`);if(!s.identity_token.path)throw new O('identity_token.source "file" requires a non-empty path');return Ns(s.identity_token.path)}let e=A("ANTHROPIC_IDENTITY_TOKEN_FILE");if(e)return Ns(e);let t=A("ANTHROPIC_IDENTITY_TOKEN");return t?Gn(t):null}function wi(s,e,t,r){return async n=>{let o=await import("fs");await Rr(e,r);let a;try{let l=await o.promises.readFile(e,"utf-8");a=JSON.parse(l);let h=a?.access_token;if(h&&!n?.forceRefresh){let b=a?.expires_at;if(b==null||le()<b-lt)return{token:h,expiresAt:b??null}}}catch(l){l?.code!=="ENOENT"&&!(l instanceof SyntaxError)&&t?.(l)}let c=await s(n);try{await Ir(e,{...a??{},version:Nr,type:"oauth_token",access_token:c.token,expires_at:c.expiresAt})}catch(l){t?.(l)}return c}}var G,Y,me=class{constructor(){G.set(this,void 0),Y.set(this,void 0),g(this,G,new Uint8Array,"f"),g(this,Y,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ut(e):e;g(this,G,jn([i(this,G,"f"),t]),"f");let r=[],n;for(;(n=xi(i(this,G,"f"),i(this,Y,"f")))!=null;){if(n.carriage&&i(this,Y,"f")==null){g(this,Y,n.index,"f");continue}if(i(this,Y,"f")!=null&&(n.index!==i(this,Y,"f")+1||n.carriage)){r.push(Ps(i(this,G,"f").subarray(0,i(this,Y,"f")-1))),g(this,G,i(this,G,"f").subarray(i(this,Y,"f")),"f"),g(this,Y,null,"f");continue}let o=i(this,Y,"f")!==null?n.preceding-1:n.preceding,a=Ps(i(this,G,"f").subarray(0,o));r.push(a),g(this,G,i(this,G,"f").subarray(n.index),"f"),g(this,Y,null,"f")}return r}flush(){return i(this,G,"f").length?this.decode(`
5
5
  `):[]}};G=new WeakMap,Y=new WeakMap;me.NEWLINE_CHARS=new Set([`
6
6
  `,"\r"]);me.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function xi(s,e){for(let n=e??0;n<s.length;n++){if(s[n]===10)return{preceding:n,index:n+1,carriage:!1};if(s[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function eo(s){for(let r=0;r<s.length-1;r++){if(s[r]===10&&s[r+1]===10||s[r]===13&&s[r+1]===13)return r+2;if(s[r]===13&&s[r+1]===10&&r+3<s.length&&s[r+2]===13&&s[r+3]===10)return r+4}return-1}var Vt,Q=class s{constructor(e,t,r){this.iterator=e,Vt.set(this,void 0),this.controller=t,g(this,Vt,r,"f")}static rawEvents(e,t=new AbortController){return to(e,t)}static fromSSEResponse(e,t,r){let n=!1,o=r?T(r):console;async function*a(){if(n)throw new _("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let c=!1;try{for await(let l of to(e,t)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(h){throw o.error("Could not parse message into JSON:",l.data),o.error("From chunk:",l.raw),h}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop"||l.event==="message"||l.event==="user.message"||l.event==="user.interrupt"||l.event==="user.tool_confirmation"||l.event==="user.custom_tool_result"||l.event==="user.tool_result"||l.event==="agent.message"||l.event==="agent.thinking"||l.event==="agent.tool_use"||l.event==="agent.tool_result"||l.event==="agent.mcp_tool_use"||l.event==="agent.mcp_tool_result"||l.event==="agent.custom_tool_use"||l.event==="agent.thread_context_compacted"||l.event==="session.status_running"||l.event==="session.status_idle"||l.event==="session.status_rescheduled"||l.event==="session.status_terminated"||l.event==="session.error"||l.event==="session.deleted"||l.event==="session.updated"||l.event==="span.model_request_start"||l.event==="span.model_request_end"||l.event==="span.outcome_evaluation_start"||l.event==="span.outcome_evaluation_ongoing"||l.event==="span.outcome_evaluation_end"||l.event==="user.define_outcome"||l.event==="agent.thread_message_received"||l.event==="agent.thread_message_sent"||l.event==="agent.session_thread_message_received"||l.event==="agent.session_thread_message_sent"||l.event==="session.thread_created"||l.event==="session.thread_status_created"||l.event==="session.thread_status_running"||l.event==="session.thread_status_idle"||l.event==="session.thread_status_rescheduled"||l.event==="session.thread_status_terminated")try{yield JSON.parse(l.data)}catch(h){throw o.error("Could not parse message into JSON:",l.data),o.error("From chunk:",l.raw),h}if(l.event!=="ping"&&l.event==="error"){let h=jt(l.data)??l.data,b=h?.error?.type;throw new F(void 0,h,void 0,e.headers,b)}}c=!0}catch(l){if(re(l))return;throw l}finally{c||t.abort()}}return new s(a,t,r)}static fromReadableStream(e,t,r){let n=!1;async function*o(){let c=new me,l=qt(e);for await(let h of l)for(let b of c.decode(h))yield b;for(let h of c.flush())yield h}async function*a(){if(n)throw new _("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let c=!1;try{for await(let l of o())c||l&&(yield JSON.parse(l));c=!0}catch(l){if(re(l))return;throw l}finally{c||t.abort()}}return new s(a,t,r)}[(Vt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=o=>({next:()=>{if(o.length===0){let a=r.next();e.push(a),t.push(a)}return o.shift()}});return[new s(()=>n(e),this.controller,i(this,Vt,"f")),new s(()=>n(t),this.controller,i(this,Vt,"f"))]}toReadableStream(){let e=this,t;return xs({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:n,done:o}=await t.next();if(o)return r.close();let a=ut(JSON.stringify(n)+`
7
7
  `);r.enqueue(a)}catch(n){r.error(n)}},async cancel(){await t.return?.()}})}};async function*to(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new _("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 _("Attempted to iterate over a response with no body");let t=new $s,r=new me,n=qt(s.body);for await(let o of Si(n))for(let a of r.decode(o)){let c=t.decode(a);c&&(yield c)}for(let o of r.flush()){let a=t.decode(o);a&&(yield a)}}async function*Si(s){let e=new Uint8Array;for await(let t of s){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?ut(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let o;for(;(o=eo(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var $s=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
@@ -9,7 +9,7 @@ import{b as wr,d as ri}from"./chunk-X3UA5OZL.js";var po=wr(Z=>{"use strict";var
9
9
  ${o.map(f=>f.error).join(`
10
10
  `)}
11
11
  ${a}
12
- ${d}`)}return a},m=$i(lo);var ht=class extends x{retrieve(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/deployment_runs/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...n}=e??{};return this._client.getAPIList("/v1/deployment_runs?beta=true",E,{query:n,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}};var ft=class extends x{create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/deployments?beta=true",{body:n,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/deployments/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:n,...o}=t;return this._client.post(m`/v1/deployments/${e}?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...n}=e??{};return this._client.getAPIList("/v1/deployments?beta=true",E,{query:n,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}archive(e,t={},r){let{betas:n}=t??{};return this._client.post(m`/v1/deployments/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}pause(e,t={},r){let{betas:n}=t??{};return this._client.post(m`/v1/deployments/${e}/pause?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}run(e,t={},r){let{betas:n}=t??{};return this._client.post(m`/v1/deployments/${e}/run?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}unpause(e,t={},r){let{betas:n}=t??{};return this._client.post(m`/v1/deployments/${e}/unpause?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};var Qt=Symbol("anthropic.sdk.stainlessHelper");function Hr(s){return typeof s=="object"&&s!==null&&Qt in s}function js(s,e){let t=new Set;if(s)for(let r of s)Hr(r)&&t.add(r[Qt]);if(e){for(let r of e)if(Hr(r)&&t.add(r[Qt]),Array.isArray(r.content))for(let n of r.content)Hr(n)&&t.add(n[Qt])}return Array.from(t)}function Br(s,e){let t=js(s,e);return t.length===0?{}:{"x-stainless-helper":t.join(", ")}}function uo(s){return Hr(s)?{"x-stainless-helper":s[Qt]}:{}}var pt=class extends x{list(e={},t){let{betas:r,...n}=e??{};return this._client.getAPIList("/v1/files?beta=true",ne,{query:n,...t,headers:u([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},t?.headers])})}delete(e,t={},r){let{betas:n}=t??{};return this._client.delete(m`/v1/files/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])})}download(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/files/${e}/content?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/files/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])})}upload(e,t){let{betas:r,...n}=e;return this._client.post("/v1/files?beta=true",dt({body:n,...t,headers:u([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},uo(n.file),t?.headers])},this._client))}};var mt=class extends x{retrieve(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/models/${e}?beta=true`,{...r,headers:u([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}list(e={},t){let{betas:r,...n}=e??{};return this._client.getAPIList("/v1/models?beta=true",ne,{query:n,...t,headers:u([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}};var gt=class extends x{create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/user_profiles?beta=true",{body:n,...t,headers:u([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/user_profiles/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}update(e,t,r){let{betas:n,...o}=t;return this._client.post(m`/v1/user_profiles/${e}?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...n??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}list(e={},t){let{betas:r,...n}=e??{};return this._client.getAPIList("/v1/user_profiles?beta=true",E,{query:n,...t,headers:u([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},t?.headers])})}createEnrollmentURL(e,t={},r){let{betas:n}=t??{};return this._client.post(m`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}};var So=ri(xo(),1),bt=class extends x{unwrap(e,{headers:t,key:r}){if(t!==void 0){let n=r===void 0?this._client.webhookKey:r;if(n===null)throw new Error("Webhook key must not be null in order to unwrap");new So.Webhook(n).verify(e,t)}return JSON.parse(e)}};var yt=class extends x{list(e,t={},r){let{betas:n,...o}=t??{};return this._client.getAPIList(m`/v1/agents/${e}/versions?beta=true`,E,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};var De=class extends x{constructor(){super(...arguments),this.versions=new yt(this._client)}create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/agents?beta=true",{body:n,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:n,...o}=t??{};return this._client.get(m`/v1/agents/${e}?beta=true`,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:n,...o}=t;return this._client.post(m`/v1/agents/${e}?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...n}=e??{};return this._client.getAPIList("/v1/agents?beta=true",E,{query:n,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}archive(e,t={},r){let{betas:n}=t??{};return this._client.post(m`/v1/agents/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};De.Versions=yt;function Ue(s,e){if(!s)return()=>{};if(s.aborted)return e.abort(),()=>{};let t=()=>e.abort();return s.addEventListener("abort",t),()=>s.removeEventListener("abort",t)}function ke(s,e){return s instanceof F&&s.status===e}function ko(s){return s instanceof F&&typeof s.status=="number"&&s.status>=400&&s.status<500}function ve(s){return ko(s)&&!ke(s,408)&&!ke(s,409)&&!ke(s,429)}function vo(s,e,t){return Math.min(e*2**s,t)}function Ks(s,e){return s+Math.random()*(e-s)}function Eo(s){return s*(1-Math.random()*.25)}function jr(s,{authToken:e,helper:t}){if(!e)throw new _(`copyClientForHelper: expected a non-empty authToken but received ${JSON.stringify(e)}`);let r=s,n=r._options.defaultHeaders,o=r._authState?.extraHeaders,a=o?Object.fromEntries(Object.entries(o).filter(([l])=>{let h=l.toLowerCase();return h!=="authorization"&&h!=="x-api-key"})):void 0,c=u([a,n,{"x-stainless-helper":t}]);return s.withOptions({apiKey:null,authToken:e,baseURL:s.baseURL,credentials:void 0,defaultHeaders:c})}var wt,Wr,oe,qr,Jr,Kr,er,tr,xt,Qi=999,Zi=1e3,ea=6e4,Ee=class{constructor(e){wt.set(this,void 0),Wr.set(this,!1),oe.set(this,void 0),qr.set(this,void 0),Jr.set(this,void 0),Kr.set(this,void 0),er.set(this,void 0),tr.set(this,void 0),xt.set(this,void 0),this.client=e.client,this.environmentId=e.environmentId,this.environmentKey=e.environmentKey,this.workerId=e.workerId??ra(),g(this,wt,jr(e.client,{authToken:e.environmentKey,helper:"environments-work-poller"}),"f"),g(this,Jr,e.autoStop??!0,"f"),g(this,Kr,e.drain??!1,"f"),g(this,er,e.blockMs===void 0?Qi:e.blockMs,"f"),g(this,tr,e.reclaimOlderThanMs??null,"f"),g(this,xt,e.requestOptions,"f"),g(this,oe,new AbortController,"f"),g(this,qr,Ue(e.signal,i(this,oe,"f")),"f")}get signal(){return i(this,oe,"f").signal}abort(){i(this,oe,"f").abort()}async*[(wt=new WeakMap,Wr=new WeakMap,oe=new WeakMap,qr=new WeakMap,Jr=new WeakMap,Kr=new WeakMap,er=new WeakMap,tr=new WeakMap,xt=new WeakMap,Symbol.asyncIterator)](){if(i(this,Wr,"f"))throw new _("Cannot iterate over a consumed WorkPoller");g(this,Wr,!0,"f");let e=T(this.client);e.info("poller starting",{component:"work-poller",environment_id:this.environmentId});try{let t=0;for(;!i(this,oe,"f").signal.aborted;){let r;try{r=await i(this,wt,"f").beta.environments.work.poll(this.environmentId,{"Anthropic-Worker-ID":this.workerId,...i(this,er,"f")!==null?{block_ms:i(this,er,"f")}:{},...i(this,tr,"f")!==null?{reclaim_older_than_ms:i(this,tr,"f")}:{}},{headers:u([i(this,xt,"f")?.headers]),signal:i(this,oe,"f").signal})}catch(n){if(i(this,oe,"f").signal.aborted)return;if(ve(n))throw e.error("poll failed permanently, stopping poller",{error:String(n)}),n;let o=Eo(ta(t));e.warn("poll failed, backing off",{error:String(n),backoff_ms:o}),t++,await ce(o,i(this,oe,"f").signal);continue}if(t=0,r==null){if(i(this,Kr,"f"))return;await ce(Ks(1e3,3e3),i(this,oe,"f").signal);continue}e.info("claimed work",{component:"work-poller",environment_id:this.environmentId,work_id:r.id,work_type:r.data.type});try{await i(this,wt,"f").beta.environments.work.ack(r.id,{environment_id:r.environment_id},{headers:u([i(this,xt,"f")?.headers]),signal:i(this,oe,"f").signal})}catch(n){e.error("ack failed",{work_id:r.id,error:String(n)});continue}try{yield r}finally{if(i(this,Jr,"f"))try{await i(this,wt,"f").beta.environments.work.stop(r.id,{environment_id:r.environment_id},{headers:u([i(this,xt,"f")?.headers])})}catch(n){ke(n,409)||e.warn("stop failed",{work_id:r.id,error:String(n)})}}}}finally{i(this,qr,"f").call(this)}}};function ta(s){return vo(s,Zi,ea)}function ra(){let e=globalThis.process?.env?.HOSTNAME;return e?`${e}-${ct()}`:ct()}var St,Ae,kt,Vr=class{constructor(){St.set(this,[]),Ae.set(this,[]),kt.set(this,!1)}push(e){if(i(this,kt,"f"))return!1;let t=i(this,Ae,"f").shift();return t?t({done:!1,value:e}):i(this,St,"f").push(e),!0}close(){if(!i(this,kt,"f"))for(g(this,kt,!0,"f");i(this,Ae,"f").length>0;)i(this,Ae,"f").shift()({done:!0,value:void 0})}next(e){return i(this,St,"f").length>0?Promise.resolve({done:!1,value:i(this,St,"f").shift()}):i(this,kt,"f")||e?.aborted?Promise.resolve({done:!0,value:void 0}):new Promise(t=>{let r=o=>{e?.removeEventListener("abort",n),t(o)},n=()=>{let o=i(this,Ae,"f").indexOf(r);o>=0&&i(this,Ae,"f").splice(o,1),t({done:!0,value:void 0})};i(this,Ae,"f").push(r),e?.addEventListener("abort",n,{once:!0})})}tryShift(){return i(this,St,"f").shift()}};St=new WeakMap,Ae=new WeakMap,kt=new WeakMap;function Vs(s){return"name"in s?s.name:s.mcp_server_name}function sa(s){return s instanceof pe?s.content:`Error: ${s instanceof Error?s.message:String(s)}`}async function Ao(s,e,t){try{let r=s.parse?s.parse(e):e;return{content:await s.run(r,t),isError:!1}}catch(r){return{content:sa(r),isError:!0}}}var U,zr,q,Xr,sr,Yr,K,vt,fe,je,ge,nr,Et,Gr,Co,Ro,Io,Po,zs,rr,Xs,To,$o;var na="SessionToolRunner",Oo=500,oa=1e4,ia=12e4,aa=3e4,Mo=3,ca=6e4;function No(s){return s.type==="session.status_idle"&&s.stop_reason?.type==="end_turn"}var Re=class{constructor(e,t){U.add(this),zr.set(this,!1),q.set(this,void 0),Xr.set(this,void 0),sr.set(this,void 0),Yr.set(this,void 0),K.set(this,void 0),vt.set(this,new Set),fe.set(this,new Set),je.set(this,new Vr),ge.set(this,0),nr.set(this,null),Et.set(this,void 0),this.client=t.client,this.sessionId=e,this.tools=t.tools,this.maxIdleMs=t.maxIdleMs??ca,g(this,K,T(t.client),"f"),g(this,Yr,new Map(t.tools.map(r=>[Vs(r),r])),"f"),g(this,q,new AbortController,"f"),g(this,Xr,Ue(t.signal,i(this,q,"f")),"f"),g(this,sr,t.requestOptions,"f")}get signal(){return i(this,q,"f").signal}abort(){i(this,q,"f").abort()}async*[(zr=new WeakMap,q=new WeakMap,Xr=new WeakMap,sr=new WeakMap,Yr=new WeakMap,K=new WeakMap,vt=new WeakMap,fe=new WeakMap,je=new WeakMap,ge=new WeakMap,nr=new WeakMap,Et=new WeakMap,U=new WeakSet,Symbol.asyncIterator)](){if(i(this,zr,"f"))throw new _("Cannot iterate over a consumed SessionToolRunner");g(this,zr,!0,"f"),i(this,K,"f").info("session tool runner starting",{component:"session-tool-runner",session_id:this.sessionId});let e=i(this,U,"m",Co).call(this).catch(t=>{i(this,q,"f").signal.aborted||i(this,K,"f").error("stream loop failed",{error:String(t)}),i(this,q,"f").abort()});try{for(;;){let r=await i(this,je,"f").next(i(this,q,"f").signal);if(r.done)break;yield r.value}await e;let t;for(;(t=i(this,je,"f").tryShift())!==void 0;)yield t}finally{i(this,q,"f").abort(),i(this,U,"m",rr).call(this),await e;try{await i(this,U,"m",$o).call(this)}catch(t){i(this,K,"f").warn("drain failed",{error:String(t)})}i(this,je,"f").close();for(let t of this.tools)try{await t.close?.()}catch(r){i(this,K,"f").warn("tool.close failed",{tool:Vs(t),error:String(r)})}i(this,Xr,"f").call(this)}}};Gr=function(){return{...i(this,sr,"f"),headers:u([{"x-stainless-helper":na},i(this,sr,"f")?.headers]),signal:i(this,q,"f").signal}},Co=async function(){let e=i(this,q,"f"),t=Oo;for(;!e.signal.aborted;){try{let r=await this.client.beta.sessions.events.stream(this.sessionId,{},i(this,U,"m",Gr).call(this));await i(this,U,"m",Ro).call(this);for await(let n of r)if(t=Oo,await i(this,U,"m",Po).call(this,n))return}catch(r){if(e.signal.throwIfAborted(),ve(r))throw i(this,K,"f").error("permanent stream failure, shutting down",{error:String(r)}),e.abort(),r;i(this,K,"f").warn("stream disconnected, reconnecting",{error:String(r),backoff_ms:t})}e.signal.throwIfAborted(),await ce(t,e.signal),t=Math.min(t*2,oa)}},Ro=async function(){let e=i(this,q,"f"),t=[],r=!1;try{for await(let o of this.client.beta.sessions.events.list(this.sessionId,{limit:1e3},i(this,U,"m",Gr).call(this)))i(this,U,"m",Io).call(this,o,t),r=No(o)}catch(o){e.signal.throwIfAborted(),i(this,K,"f").warn("reconcile list failed",{error:String(o)});for(let a of t)i(this,vt,"f").delete(a.id);return}let n=t.filter(o=>!i(this,fe,"f").has(o.id));r&&n.length===0?i(this,U,"m",zs).call(this):i(this,U,"m",rr).call(this);for(let o of n)await i(this,U,"m",Xs).call(this,o)},Io=function(e,t){e.type==="agent.tool_use"||e.type==="agent.custom_tool_use"?(i(this,vt,"f").add(e.id),i(this,fe,"f").has(e.id)||t.push(e)):e.type==="user.tool_result"?i(this,fe,"f").add(e.tool_use_id):e.type==="user.custom_tool_result"&&i(this,fe,"f").add(e.custom_tool_use_id)},Po=async function(e){switch(No(e)?i(this,U,"m",zs).call(this):i(this,U,"m",rr).call(this),e.type){case"agent.tool_use":case"agent.custom_tool_use":return i(this,vt,"f").has(e.id)||(i(this,vt,"f").add(e.id),await i(this,U,"m",Xs).call(this,e)),!1;case"user.tool_result":return i(this,fe,"f").add(e.tool_use_id),!1;case"user.custom_tool_result":return i(this,fe,"f").add(e.custom_tool_use_id),!1;case"session.status_terminated":case"session.deleted":return i(this,K,"f").info("session terminated",{component:"session-tool-runner",session_id:this.sessionId}),i(this,q,"f").abort(),!0;default:return!1}},zs=function(){i(this,U,"m",rr).call(this),!(this.maxIdleMs<=0)&&g(this,Et,setTimeout(()=>{i(this,K,"f").info("session idle after end_turn; stopping",{component:"session-tool-runner",session_id:this.sessionId,max_idle_ms:this.maxIdleMs}),i(this,q,"f").abort()},this.maxIdleMs),"f")},rr=function(){i(this,Et,"f")!==void 0&&(clearTimeout(i(this,Et,"f")),g(this,Et,void 0,"f"))},Xs=async function(e){var t,r;if(!i(this,fe,"f").has(e.id)){i(this,K,"f").info("executing tool",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),g(this,ge,(t=i(this,ge,"f"),t++,t),"f");try{let n=i(this,Yr,"f").get(e.name);if(!n){i(this,K,"f").info("tool not owned by this runner; leaving the tool_use_id pending for its owner",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),i(this,je,"f").push({event:e,toolUseId:e.id,name:e.name,isError:!1,posted:!1});return}let o,a,c=new AbortController,l=Ue(i(this,q,"f").signal,c),h=setTimeout(()=>c.abort(),ia);try{let f=await Ao(n,e.input,{toolUse:e,toolUseBlock:e,signal:c.signal});o=f.content,a=f.isError}finally{clearTimeout(h),l()}let b=la(e,a,ua(o)),d=await i(this,U,"m",To).call(this,b,e.id);i(this,je,"f").push({event:e,result:b,toolUseId:e.id,name:e.name,isError:a,posted:d})}finally{g(this,ge,(r=i(this,ge,"f"),r--,r),"f"),i(this,ge,"f")===0&&i(this,nr,"f")?.call(this)}}},To=async function(e,t){let r=i(this,q,"f"),n;for(let o=0;o<Mo;o++){r.signal.throwIfAborted();try{return await this.client.beta.sessions.events.send(this.sessionId,{events:[e]},i(this,U,"m",Gr).call(this)),i(this,fe,"f").add(t),!0}catch(a){if(n=a,ve(a))break;o<Mo-1&&await ce((o+1)*1e3,r.signal)}}return i(this,K,"f").error("failed to send tool result",{tool_use_id:t,error:String(n)}),!1},$o=async function(){i(this,ge,"f")!==0&&(await Promise.race([new Promise(e=>g(this,nr,e,"f")),ce(aa)]),g(this,nr,null,"f"),i(this,ge,"f")>0&&i(this,K,"f").warn("drain timeout exceeded"))};function la(s,e,t){return s.type==="agent.custom_tool_use"?{type:"user.custom_tool_result",custom_tool_use_id:s.id,is_error:e,content:t}:{type:"user.tool_result",tool_use_id:s.id,is_error:e,content:t}}function ua(s){if(typeof s=="string")return[{type:"text",text:s||"(no output)"}];let e=s.map(t=>t.type==="text"?{type:"text",text:t.text||"(no output)"}:t.type==="image"||t.type==="document"?t:t.type==="search_result"?{type:"search_result",source:t.source,title:t.title,content:t.content.map(r=>({type:"text",text:r.text})),citations:{enabled:t.citations?.enabled??!1}}:{type:"text",text:JSON.stringify(t)});return e.length>0?e:[{type:"text",text:"(no output)"}]}var Qr,or,Gs,Fo=3e4,da="NO_HEARTBEAT",At=class{constructor(e){Qr.add(this),or.set(this,void 0),this.client=e.client,this.environmentId=e.environmentId,this.environmentKey=e.environmentKey,this.tools=e.tools,this.workdir=e.workdir??process.cwd(),this.unrestrictedPaths=e.unrestrictedPaths,this.maxFileBytes=e.maxFileBytes,this.maxIdleMs=e.maxIdleMs,this.workerId=e.workerId,this.requestOptions=e.requestOptions,g(this,or,e.signal,"f")}async run(e){let{environmentId:t,environmentKey:r}=this;if(t===void 0||r===void 0)throw new _("EnvironmentWorker.run: environmentId and environmentKey are required to poll for work");let n=e??i(this,or,"f"),o=new Ee({client:this.client,environmentId:t,environmentKey:r,...this.workerId!==void 0?{workerId:this.workerId}:{},...n?{signal:n}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},autoStop:!1});for await(let a of o)await i(this,Qr,"m",Gs).call(this,a,r,o.signal)}async handleItem(e){let t=e?.workId??A("ANTHROPIC_WORK_ID"),r=e?.environmentId??A("ANTHROPIC_ENVIRONMENT_ID"),n=e?.sessionId??A("ANTHROPIC_SESSION_ID"),o=e?.environmentKey??this.environmentKey??A("ANTHROPIC_ENVIRONMENT_KEY");if(!t)throw new _("handleItem: workId is required \u2014 pass it or set ANTHROPIC_WORK_ID");if(!r)throw new _("handleItem: environmentId is required \u2014 pass it or set ANTHROPIC_ENVIRONMENT_ID");if(!n)throw new _("handleItem: sessionId is required \u2014 pass it or set ANTHROPIC_SESSION_ID");if(!o)throw new _("handleItem: environmentKey is required \u2014 pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY");let a={id:t,environment_id:r,data:{type:"session",id:n}};await i(this,Qr,"m",Gs).call(this,a,o,e?.signal??i(this,or,"f"))}};or=new WeakMap,Qr=new WeakSet,Gs=async function(e,t,r){let n=T(this.client),o=jr(this.client,{authToken:t,helper:"environments-worker"}),a=e.data.id,c={workdir:this.workdir,client:this.client,sessionId:a,...this.unrestrictedPaths!==void 0?{unrestrictedPaths:this.unrestrictedPaths}:{},...this.maxFileBytes!==void 0?{maxFileBytes:this.maxFileBytes}:{}},l=await import("./node-4LTSRXL2.js"),h=async()=>{};try{h=await l.setupSkills(c)}catch(y){n.warn("skill setup failed",{session_id:a,work_id:e.id,error:String(y)})}let b=typeof this.tools=="function"?this.tools(c):this.tools??l.betaAgentToolset20260401(c),d=new AbortController,f=Ue(r,d),p=fa(o,e,d,n,this.requestOptions).catch(y=>{d.signal.aborted||n.error("heartbeat loop failed",{work_id:e.id,error:String(y)}),d.abort()});try{let y=new Re(a,{client:o,tools:b,...this.maxIdleMs!==void 0?{maxIdleMs:this.maxIdleMs}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},signal:d.signal});for await(let v of y);}finally{d.abort(),f(),await p,await h().catch(y=>{n.warn("skill cleanup failed",{session_id:a,work_id:e.id,error:String(y)})}),await ha(o,e,n,this.requestOptions)}};async function ha(s,e,t,r){try{await s.beta.environments.work.stop(e.id,{environment_id:e.environment_id,force:!0},{...r,headers:u([r?.headers])})}catch(n){ke(n,409)||t.error("force-stop on exit failed",{work_id:e.id,error:String(n)})}}async function fa(s,e,t,r,n){let o=Fo,a=da,c=async()=>{try{let l=await s.beta.environments.work.heartbeat(e.id,{environment_id:e.environment_id,expected_last_heartbeat:a},{...n,headers:u([n?.headers]),signal:t.signal});a=l.last_heartbeat,l.ttl_seconds>0&&(o=Math.max(1e3,Math.min(l.ttl_seconds*1e3/2,Fo))),(l.state==="stopping"||l.state==="stopped")&&(r.info("heartbeat signals shutdown",{work_id:e.id,state:l.state}),t.abort()),l.lease_extended||(r.warn("lease not extended, shutting down",{work_id:e.id}),t.abort())}catch(l){if(t.signal.throwIfAborted(),ve(l))throw r.error("permanent heartbeat failure",{work_id:e.id,error:String(l)}),t.abort(),l;r.warn("transient heartbeat failure",{work_id:e.id,error:String(l)})}};for(await c();!t.signal.aborted;)await ce(o,t.signal),t.signal.throwIfAborted(),await c()}var Ie=class extends x{retrieve(e,t,r){let{environment_id:n,betas:o}=t;return this._client.get(m`/v1/environments/${n}/work/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{environment_id:n,betas:o,...a}=t;return this._client.post(m`/v1/environments/${n}/work/${e}?beta=true`,{body:a,...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){let{betas:n,...o}=t??{};return this._client.getAPIList(m`/v1/environments/${e}/work?beta=true`,E,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}ack(e,t,r){let{environment_id:n,betas:o}=t;return this._client.post(m`/v1/environments/${n}/work/${e}/ack?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}heartbeat(e,t,r){let{environment_id:n,desired_ttl_seconds:o,expected_last_heartbeat:a,betas:c}=t;return this._client.post(m`/v1/environments/${n}/work/${e}/heartbeat?beta=true`,{query:{desired_ttl_seconds:o,expected_last_heartbeat:a},...r,headers:u([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}poll(e,t={},r){let{betas:n,"Anthropic-Worker-ID":o,...a}=t??{};return this._client.get(m`/v1/environments/${e}/work/poll?beta=true`,{query:a,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"Anthropic-Worker-ID":o}:void 0},r?.headers])})}stats(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/environments/${e}/work/stats?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}stop(e,t,r){let{environment_id:n,betas:o,...a}=t;return this._client.post(m`/v1/environments/${n}/work/${e}/stop?beta=true`,{body:a,...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}poller(e){return new Ee({...e,client:this._client})}worker(e){return new At({...e,client:this._client})}};Ie.WorkPoller=Ee;Ie.EnvironmentWorker=At;var We=class extends x{constructor(){super(...arguments),this.work=new Ie(this._client)}create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/environments?beta=true",{body:n,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/environments/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:n,...o}=t;return this._client.post(m`/v1/environments/${e}?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...n}=e??{};return this._client.getAPIList("/v1/environments?beta=true",E,{query:n,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}delete(e,t={},r){let{betas:n}=t??{};return this._client.delete(m`/v1/environments/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t={},r){let{betas:n}=t??{};return this._client.post(m`/v1/environments/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};We.Work=Ie;var Rt=class extends x{create(e,t,r){let{view:n,betas:o,...a}=t;return this._client.post(m`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:n},body:a,...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,t,r){let{memory_store_id:n,betas:o,...a}=t;return this._client.get(m`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:a,...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{memory_store_id:n,view:o,betas:a,...c}=t;return this._client.post(m`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:{view:o},body:c,...r,headers:u([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){let{betas:n,...o}=t??{};return this._client.getAPIList(m`/v1/memory_stores/${e}/memories?beta=true`,E,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,t,r){let{memory_store_id:n,expected_content_sha256:o,betas:a}=t;return this._client.delete(m`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:{expected_content_sha256:o},...r,headers:u([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};var It=class extends x{retrieve(e,t,r){let{memory_store_id:n,betas:o,...a}=t;return this._client.get(m`/v1/memory_stores/${n}/memory_versions/${e}?beta=true`,{query:a,...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){let{betas:n,...o}=t??{};return this._client.getAPIList(m`/v1/memory_stores/${e}/memory_versions?beta=true`,E,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}redact(e,t,r){let{memory_store_id:n,betas:o}=t;return this._client.post(m`/v1/memory_stores/${n}/memory_versions/${e}/redact?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};var Pe=class extends x{constructor(){super(...arguments),this.memories=new Rt(this._client),this.memoryVersions=new It(this._client)}create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/memory_stores?beta=true",{body:n,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/memory_stores/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:n,...o}=t;return this._client.post(m`/v1/memory_stores/${e}?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...n}=e??{};return this._client.getAPIList("/v1/memory_stores?beta=true",E,{query:n,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}delete(e,t={},r){let{betas:n}=t??{};return this._client.delete(m`/v1/memory_stores/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t={},r){let{betas:n}=t??{};return this._client.post(m`/v1/memory_stores/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};Pe.Memories=Rt;Pe.MemoryVersions=It;var Pt=class s{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new me;for await(let t of this.iterator)for(let r of e.decode(t))yield JSON.parse(r);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new _("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 _("Attempted to iterate over a response with no body");return new s(qt(e.body),t)}};var Tt=class extends x{create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/messages/batches?beta=true",{body:n,...t,headers:u([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/messages/batches/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}list(e={},t){let{betas:r,...n}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",ne,{query:n,...t,headers:u([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t?.headers])})}delete(e,t={},r){let{betas:n}=t??{};return this._client.delete(m`/v1/messages/batches/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}cancel(e,t={},r){let{betas:n}=t??{};return this._client.post(m`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}async results(e,t={},r){let n=await this.retrieve(e);if(!n.results_url)throw new _(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);let{betas:o}=t??{};return this._client.get(n.results_url,{...r,headers:u([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},r?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((a,c)=>Pt.fromResponse(c.response,c.controller))}};var Zr={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function Lo(s){return s?.output_format??s?.output_config?.format}function Ys(s,e,t){let r=Lo(e);return!e||!("parse"in(r??{}))?{...s,content:s.content.map(n=>{if(n.type==="text"){let o=Object.defineProperty({...n},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(o,"parsed",{get(){return t.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return n}),parsed_output:null}:Qs(s,e,t)}function Qs(s,e,t){let r=null,n=s.content.map(o=>{if(o.type==="text"){let a=wa(e,o.text);r===null&&(r=a);let c=Object.defineProperty({...o},"parsed_output",{value:a,enumerable:!1});return Object.defineProperty(c,"parsed",{get(){return t.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),a},enumerable:!1})}return o});return{...s,content:n,parsed_output:r}}function wa(s,e){let t=Lo(s);if(t?.type!=="json_schema")return null;try{return"parse"in t?t.parse(e):JSON.parse(e)}catch(r){throw new _(`Failed to parse structured output: ${r}`)}}var xa=s=>{let e=0,t=[];for(;e<s.length;){let r=s[e];if(r==="\\"){e++;continue}if(r==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(r==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(r==="["){t.push({type:"paren",value:"["}),e++;continue}if(r==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(r===":"){t.push({type:"separator",value:":"}),e++;continue}if(r===","){t.push({type:"delimiter",value:","}),e++;continue}if(r==='"'){let c="",l=!1;for(r=s[++e];r!=='"';){if(e===s.length){l=!0;break}if(r==="\\"){if(e++,e===s.length){l=!0;break}c+=r+s[e],r=s[++e]}else c+=r,r=s[++e]}r=s[++e],l||t.push({type:"string",value:c});continue}if(r&&/\s/.test(r)){e++;continue}let o=/[0-9]/;if(r&&o.test(r)||r==="-"||r==="."){let c="";for(r==="-"&&(c+=r,r=s[++e]);r&&(o.test(r)||r==="."||r==="e"||r==="E"||(r==="-"||r==="+")&&(c[c.length-1]==="e"||c[c.length-1]==="E"));)c+=r,r=s[++e];t.push({type:"number",value:c});continue}let a=/[a-z]/i;if(r&&a.test(r)){let c="";for(;r&&a.test(r)&&e!==s.length;)c+=r,r=s[++e];if(c=="true"||c=="false"||c==="null")t.push({type:"name",value:c});else{e++;continue}continue}e++}return t},Ot=s=>{if(s.length===0)return s;let e=s[s.length-1];switch(e.type){case"separator":return s=s.slice(0,s.length-1),Ot(s);break;case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-"||t==="+"||t==="e"||t==="E")return s=s.slice(0,s.length-1),Ot(s);case"string":let r=s[s.length-2];if(r?.type==="delimiter")return s=s.slice(0,s.length-1),Ot(s);if(r?.type==="brace"&&r.value==="{")return s=s.slice(0,s.length-1),Ot(s);break;case"delimiter":return s=s.slice(0,s.length-1),Ot(s);break}return s},Sa=s=>{let e=[];return s.map(t=>{t.type==="brace"&&(t.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),t.type==="paren"&&(t.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(t=>{t==="}"?s.push({type:"brace",value:"}"}):t==="]"&&s.push({type:"paren",value:"]"})}),s},ka=s=>{let e="";return s.map(t=>{t.type==="string"?e+='"'+t.value+'"':e+=t.value}),e},es=s=>JSON.parse(ka(Sa(Ot(xa(s)))));var ie,Te,Mt,ir,ts,ar,cr,rs,lr,_e,ur,ss,ns,qe,os,is,dr,Zs,Ho,as,en,tn,rn,Bo,Do="__json_buf";function Uo(s){return s.type==="tool_use"||s.type==="server_tool_use"||s.type==="mcp_tool_use"}var cs=class s{constructor(e,t){ie.add(this),this.messages=[],this.receivedMessages=[],Te.set(this,void 0),Mt.set(this,null),this.controller=new AbortController,ir.set(this,void 0),ts.set(this,()=>{}),ar.set(this,()=>{}),cr.set(this,void 0),rs.set(this,()=>{}),lr.set(this,()=>{}),_e.set(this,{}),ur.set(this,!1),ss.set(this,!1),ns.set(this,!1),qe.set(this,!1),os.set(this,void 0),is.set(this,void 0),dr.set(this,void 0),as.set(this,r=>{if(g(this,ss,!0,"f"),re(r)&&(r=new W),r instanceof W)return g(this,ns,!0,"f"),this._emit("abort",r);if(r instanceof _)return this._emit("error",r);if(r instanceof Error){let n=new _(r.message);return n.cause=r,this._emit("error",n)}return this._emit("error",new _(String(r)))}),g(this,ir,new Promise((r,n)=>{g(this,ts,r,"f"),g(this,ar,n,"f")}),"f"),g(this,cr,new Promise((r,n)=>{g(this,rs,r,"f"),g(this,lr,n,"f")}),"f"),i(this,ir,"f").catch(()=>{}),i(this,cr,"f").catch(()=>{}),g(this,Mt,e,"f"),g(this,dr,t?.logger??console,"f")}get response(){return i(this,os,"f")}get request_id(){return i(this,is,"f")}async withResponse(){g(this,qe,!0,"f");let e=await i(this,ir,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r,{logger:n}={}){let o=new s(t,{logger:n});for(let a of t.messages)o._addMessageParam(a);return g(o,Mt,{...t,stream:!0},"f"),o._run(()=>o._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),o}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},i(this,as,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){let n=r?.signal,o;n&&(n.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),n.addEventListener("abort",o));try{i(this,ie,"m",en).call(this);let{response:a,data:c}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(a);for await(let l of c)i(this,ie,"m",tn).call(this,l);if(c.controller.signal?.aborted)throw new W;i(this,ie,"m",rn).call(this)}finally{n&&o&&n.removeEventListener("abort",o)}}_connected(e){this.ended||(g(this,os,e,"f"),g(this,is,e?.headers.get("request-id"),"f"),i(this,ts,"f").call(this,e),this._emit("connect"))}get ended(){return i(this,ur,"f")}get errored(){return i(this,ss,"f")}get aborted(){return i(this,ns,"f")}abort(){this.controller.abort()}on(e,t){return(i(this,_e,"f")[e]||(i(this,_e,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=i(this,_e,"f")[e];if(!r)return this;let n=r.findIndex(o=>o.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(i(this,_e,"f")[e]||(i(this,_e,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{g(this,qe,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){g(this,qe,!0,"f"),await i(this,cr,"f")}get currentMessage(){return i(this,Te,"f")}async finalMessage(){return await this.done(),i(this,ie,"m",Zs).call(this)}async finalText(){return await this.done(),i(this,ie,"m",Ho).call(this)}_emit(e,...t){if(i(this,ur,"f"))return;e==="end"&&(g(this,ur,!0,"f"),i(this,rs,"f").call(this));let r=i(this,_e,"f")[e];if(r&&(i(this,_e,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!i(this,qe,"f")&&!r?.length&&Promise.reject(n),i(this,ar,"f").call(this,n),i(this,lr,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!i(this,qe,"f")&&!r?.length&&Promise.reject(n),i(this,ar,"f").call(this,n),i(this,lr,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",i(this,ie,"m",Zs).call(this))}async _fromReadableStream(e,t){let r=t?.signal,n;r&&(r.aborted&&this.controller.abort(),n=this.controller.abort.bind(this.controller),r.addEventListener("abort",n));try{i(this,ie,"m",en).call(this),this._connected(null);let o=Q.fromReadableStream(e,this.controller);for await(let a of o)i(this,ie,"m",tn).call(this,a);if(o.controller.signal?.aborted)throw new W;i(this,ie,"m",rn).call(this)}finally{r&&n&&r.removeEventListener("abort",n)}}[(Te=new WeakMap,Mt=new WeakMap,ir=new WeakMap,ts=new WeakMap,ar=new WeakMap,cr=new WeakMap,rs=new WeakMap,lr=new WeakMap,_e=new WeakMap,ur=new WeakMap,ss=new WeakMap,ns=new WeakMap,qe=new WeakMap,os=new WeakMap,is=new WeakMap,dr=new WeakMap,as=new WeakMap,ie=new WeakSet,Zs=function(){if(this.receivedMessages.length===0)throw new _("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Ho=function(){if(this.receivedMessages.length===0)throw new _("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(t.length===0)throw new _("stream ended without producing a content block with type=text");return t.join(" ")},en=function(){this.ended||g(this,Te,void 0,"f")},tn=function(t){if(this.ended)return;let r=i(this,ie,"m",Bo).call(this,t);switch(this._emit("streamEvent",t,r),t.type){case"content_block_delta":{let n=r.content.at(-1);switch(t.delta.type){case"text_delta":{n.type==="text"&&this._emit("text",t.delta.text,n.text||"");break}case"citations_delta":{n.type==="text"&&this._emit("citation",t.delta.citation,n.citations??[]);break}case"input_json_delta":{Uo(n)&&n.input&&this._emit("inputJson",t.delta.partial_json,n.input);break}case"thinking_delta":{n.type==="thinking"&&this._emit("thinking",t.delta.thinking,n.thinking);break}case"signature_delta":{n.type==="thinking"&&this._emit("signature",n.signature);break}case"compaction_delta":{n.type==="compaction"&&n.content&&this._emit("compaction",n.content);break}default:t.delta}break}case"message_stop":{this._addMessageParam(r),this._addMessage(Ys(r,i(this,Mt,"f"),{logger:i(this,dr,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{g(this,Te,r,"f");break}case"content_block_start":case"message_delta":break}},rn=function(){if(this.ended)throw new _("stream has ended, this shouldn't happen");let t=i(this,Te,"f");if(!t)throw new _("request ended without sending any chunks");return g(this,Te,void 0,"f"),Ys(t,i(this,Mt,"f"),{logger:i(this,dr,"f")})},Bo=function(t){let r=i(this,Te,"f");if(t.type==="message_start"){if(r)throw new _(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!r)throw new _(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return r;case"message_delta":return r.container=t.delta.container,r.stop_reason=t.delta.stop_reason,r.stop_sequence=t.delta.stop_sequence,t.delta.stop_details!=null&&(r.stop_details=t.delta.stop_details),r.usage.output_tokens=t.usage.output_tokens,r.context_management=t.context_management,t.usage.input_tokens!=null&&(r.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(r.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(r.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(r.usage.server_tool_use=t.usage.server_tool_use),t.usage.iterations!=null&&(r.usage.iterations=t.usage.iterations),r;case"content_block_start":return r.content.push(t.content_block),t.content_block.type==="fallback"&&(r.model=t.content_block.to.model),r;case"content_block_delta":{let n=r.content.at(t.index);switch(t.delta.type){case"text_delta":{n?.type==="text"&&(r.content[t.index]={...n,text:(n.text||"")+t.delta.text});break}case"citations_delta":{n?.type==="text"&&(r.content[t.index]={...n,citations:[...n.citations??[],t.delta.citation]});break}case"input_json_delta":{if(n&&Uo(n)){let o=n[Do]||"";o+=t.delta.partial_json;let a={...n};if(Object.defineProperty(a,Do,{value:o,enumerable:!1,writable:!0}),o)try{a.input=es(o)}catch(c){let l=new _(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${c}. JSON: ${o}`);i(this,as,"f").call(this,l)}r.content[t.index]=a}break}case"thinking_delta":{n?.type==="thinking"&&(r.content[t.index]={...n,thinking:n.thinking+t.delta.thinking});break}case"signature_delta":{n?.type==="thinking"&&(r.content[t.index]={...n,signature:t.delta.signature});break}case"compaction_delta":{n?.type==="compaction"&&(r.content[t.index]={...n,content:(n.content||"")+t.delta.content,encrypted_content:t.delta.encrypted_content});break}default:t.delta}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Q(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var jo=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
12
+ ${d}`)}return a},m=$i(lo);var ht=class extends x{retrieve(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/deployment_runs/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...n}=e??{};return this._client.getAPIList("/v1/deployment_runs?beta=true",E,{query:n,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}};var ft=class extends x{create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/deployments?beta=true",{body:n,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/deployments/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:n,...o}=t;return this._client.post(m`/v1/deployments/${e}?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...n}=e??{};return this._client.getAPIList("/v1/deployments?beta=true",E,{query:n,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}archive(e,t={},r){let{betas:n}=t??{};return this._client.post(m`/v1/deployments/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}pause(e,t={},r){let{betas:n}=t??{};return this._client.post(m`/v1/deployments/${e}/pause?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}run(e,t={},r){let{betas:n}=t??{};return this._client.post(m`/v1/deployments/${e}/run?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}unpause(e,t={},r){let{betas:n}=t??{};return this._client.post(m`/v1/deployments/${e}/unpause?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};var Qt=Symbol("anthropic.sdk.stainlessHelper");function Hr(s){return typeof s=="object"&&s!==null&&Qt in s}function js(s,e){let t=new Set;if(s)for(let r of s)Hr(r)&&t.add(r[Qt]);if(e){for(let r of e)if(Hr(r)&&t.add(r[Qt]),Array.isArray(r.content))for(let n of r.content)Hr(n)&&t.add(n[Qt])}return Array.from(t)}function Br(s,e){let t=js(s,e);return t.length===0?{}:{"x-stainless-helper":t.join(", ")}}function uo(s){return Hr(s)?{"x-stainless-helper":s[Qt]}:{}}var pt=class extends x{list(e={},t){let{betas:r,...n}=e??{};return this._client.getAPIList("/v1/files?beta=true",ne,{query:n,...t,headers:u([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},t?.headers])})}delete(e,t={},r){let{betas:n}=t??{};return this._client.delete(m`/v1/files/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])})}download(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/files/${e}/content?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/files/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])})}upload(e,t){let{betas:r,...n}=e;return this._client.post("/v1/files?beta=true",dt({body:n,...t,headers:u([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},uo(n.file),t?.headers])},this._client))}};var mt=class extends x{retrieve(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/models/${e}?beta=true`,{...r,headers:u([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}list(e={},t){let{betas:r,...n}=e??{};return this._client.getAPIList("/v1/models?beta=true",ne,{query:n,...t,headers:u([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}};var gt=class extends x{create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/user_profiles?beta=true",{body:n,...t,headers:u([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/user_profiles/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}update(e,t,r){let{betas:n,...o}=t;return this._client.post(m`/v1/user_profiles/${e}?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...n??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}list(e={},t){let{betas:r,...n}=e??{};return this._client.getAPIList("/v1/user_profiles?beta=true",E,{query:n,...t,headers:u([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},t?.headers])})}createEnrollmentURL(e,t={},r){let{betas:n}=t??{};return this._client.post(m`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}};var So=ri(xo(),1),bt=class extends x{unwrap(e,{headers:t,key:r}){if(t!==void 0){let n=r===void 0?this._client.webhookKey:r;if(n===null)throw new Error("Webhook key must not be null in order to unwrap");new So.Webhook(n).verify(e,t)}return JSON.parse(e)}};var yt=class extends x{list(e,t={},r){let{betas:n,...o}=t??{};return this._client.getAPIList(m`/v1/agents/${e}/versions?beta=true`,E,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};var De=class extends x{constructor(){super(...arguments),this.versions=new yt(this._client)}create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/agents?beta=true",{body:n,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:n,...o}=t??{};return this._client.get(m`/v1/agents/${e}?beta=true`,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:n,...o}=t;return this._client.post(m`/v1/agents/${e}?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...n}=e??{};return this._client.getAPIList("/v1/agents?beta=true",E,{query:n,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}archive(e,t={},r){let{betas:n}=t??{};return this._client.post(m`/v1/agents/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};De.Versions=yt;function Ue(s,e){if(!s)return()=>{};if(s.aborted)return e.abort(),()=>{};let t=()=>e.abort();return s.addEventListener("abort",t),()=>s.removeEventListener("abort",t)}function ke(s,e){return s instanceof F&&s.status===e}function ko(s){return s instanceof F&&typeof s.status=="number"&&s.status>=400&&s.status<500}function ve(s){return ko(s)&&!ke(s,408)&&!ke(s,409)&&!ke(s,429)}function vo(s,e,t){return Math.min(e*2**s,t)}function Ks(s,e){return s+Math.random()*(e-s)}function Eo(s){return s*(1-Math.random()*.25)}function jr(s,{authToken:e,helper:t}){if(!e)throw new _(`copyClientForHelper: expected a non-empty authToken but received ${JSON.stringify(e)}`);let r=s,n=r._options.defaultHeaders,o=r._authState?.extraHeaders,a=o?Object.fromEntries(Object.entries(o).filter(([l])=>{let h=l.toLowerCase();return h!=="authorization"&&h!=="x-api-key"})):void 0,c=u([a,n,{"x-stainless-helper":t}]);return s.withOptions({apiKey:null,authToken:e,baseURL:s.baseURL,credentials:void 0,defaultHeaders:c})}var wt,Wr,oe,qr,Jr,Kr,er,tr,xt,Qi=999,Zi=1e3,ea=6e4,Ee=class{constructor(e){wt.set(this,void 0),Wr.set(this,!1),oe.set(this,void 0),qr.set(this,void 0),Jr.set(this,void 0),Kr.set(this,void 0),er.set(this,void 0),tr.set(this,void 0),xt.set(this,void 0),this.client=e.client,this.environmentId=e.environmentId,this.environmentKey=e.environmentKey,this.workerId=e.workerId??ra(),g(this,wt,jr(e.client,{authToken:e.environmentKey,helper:"environments-work-poller"}),"f"),g(this,Jr,e.autoStop??!0,"f"),g(this,Kr,e.drain??!1,"f"),g(this,er,e.blockMs===void 0?Qi:e.blockMs,"f"),g(this,tr,e.reclaimOlderThanMs??null,"f"),g(this,xt,e.requestOptions,"f"),g(this,oe,new AbortController,"f"),g(this,qr,Ue(e.signal,i(this,oe,"f")),"f")}get signal(){return i(this,oe,"f").signal}abort(){i(this,oe,"f").abort()}async*[(wt=new WeakMap,Wr=new WeakMap,oe=new WeakMap,qr=new WeakMap,Jr=new WeakMap,Kr=new WeakMap,er=new WeakMap,tr=new WeakMap,xt=new WeakMap,Symbol.asyncIterator)](){if(i(this,Wr,"f"))throw new _("Cannot iterate over a consumed WorkPoller");g(this,Wr,!0,"f");let e=T(this.client);e.info("poller starting",{component:"work-poller",environment_id:this.environmentId});try{let t=0;for(;!i(this,oe,"f").signal.aborted;){let r;try{r=await i(this,wt,"f").beta.environments.work.poll(this.environmentId,{"Anthropic-Worker-ID":this.workerId,...i(this,er,"f")!==null?{block_ms:i(this,er,"f")}:{},...i(this,tr,"f")!==null?{reclaim_older_than_ms:i(this,tr,"f")}:{}},{headers:u([i(this,xt,"f")?.headers]),signal:i(this,oe,"f").signal})}catch(n){if(i(this,oe,"f").signal.aborted)return;if(ve(n))throw e.error("poll failed permanently, stopping poller",{error:String(n)}),n;let o=Eo(ta(t));e.warn("poll failed, backing off",{error:String(n),backoff_ms:o}),t++,await ce(o,i(this,oe,"f").signal);continue}if(t=0,r==null){if(i(this,Kr,"f"))return;await ce(Ks(1e3,3e3),i(this,oe,"f").signal);continue}e.info("claimed work",{component:"work-poller",environment_id:this.environmentId,work_id:r.id,work_type:r.data.type});try{await i(this,wt,"f").beta.environments.work.ack(r.id,{environment_id:r.environment_id},{headers:u([i(this,xt,"f")?.headers]),signal:i(this,oe,"f").signal})}catch(n){e.error("ack failed",{work_id:r.id,error:String(n)});continue}try{yield r}finally{if(i(this,Jr,"f"))try{await i(this,wt,"f").beta.environments.work.stop(r.id,{environment_id:r.environment_id},{headers:u([i(this,xt,"f")?.headers])})}catch(n){ke(n,409)||e.warn("stop failed",{work_id:r.id,error:String(n)})}}}}finally{i(this,qr,"f").call(this)}}};function ta(s){return vo(s,Zi,ea)}function ra(){let e=globalThis.process?.env?.HOSTNAME;return e?`${e}-${ct()}`:ct()}var St,Ae,kt,Vr=class{constructor(){St.set(this,[]),Ae.set(this,[]),kt.set(this,!1)}push(e){if(i(this,kt,"f"))return!1;let t=i(this,Ae,"f").shift();return t?t({done:!1,value:e}):i(this,St,"f").push(e),!0}close(){if(!i(this,kt,"f"))for(g(this,kt,!0,"f");i(this,Ae,"f").length>0;)i(this,Ae,"f").shift()({done:!0,value:void 0})}next(e){return i(this,St,"f").length>0?Promise.resolve({done:!1,value:i(this,St,"f").shift()}):i(this,kt,"f")||e?.aborted?Promise.resolve({done:!0,value:void 0}):new Promise(t=>{let r=o=>{e?.removeEventListener("abort",n),t(o)},n=()=>{let o=i(this,Ae,"f").indexOf(r);o>=0&&i(this,Ae,"f").splice(o,1),t({done:!0,value:void 0})};i(this,Ae,"f").push(r),e?.addEventListener("abort",n,{once:!0})})}tryShift(){return i(this,St,"f").shift()}};St=new WeakMap,Ae=new WeakMap,kt=new WeakMap;function Vs(s){return"name"in s?s.name:s.mcp_server_name}function sa(s){return s instanceof pe?s.content:`Error: ${s instanceof Error?s.message:String(s)}`}async function Ao(s,e,t){try{let r=s.parse?s.parse(e):e;return{content:await s.run(r,t),isError:!1}}catch(r){return{content:sa(r),isError:!0}}}var U,zr,q,Xr,sr,Yr,K,vt,fe,je,ge,nr,Et,Gr,Co,Ro,Io,Po,zs,rr,Xs,To,$o;var na="SessionToolRunner",Oo=500,oa=1e4,ia=12e4,aa=3e4,Mo=3,ca=6e4;function No(s){return s.type==="session.status_idle"&&s.stop_reason?.type==="end_turn"}var Re=class{constructor(e,t){U.add(this),zr.set(this,!1),q.set(this,void 0),Xr.set(this,void 0),sr.set(this,void 0),Yr.set(this,void 0),K.set(this,void 0),vt.set(this,new Set),fe.set(this,new Set),je.set(this,new Vr),ge.set(this,0),nr.set(this,null),Et.set(this,void 0),this.client=t.client,this.sessionId=e,this.tools=t.tools,this.maxIdleMs=t.maxIdleMs??ca,g(this,K,T(t.client),"f"),g(this,Yr,new Map(t.tools.map(r=>[Vs(r),r])),"f"),g(this,q,new AbortController,"f"),g(this,Xr,Ue(t.signal,i(this,q,"f")),"f"),g(this,sr,t.requestOptions,"f")}get signal(){return i(this,q,"f").signal}abort(){i(this,q,"f").abort()}async*[(zr=new WeakMap,q=new WeakMap,Xr=new WeakMap,sr=new WeakMap,Yr=new WeakMap,K=new WeakMap,vt=new WeakMap,fe=new WeakMap,je=new WeakMap,ge=new WeakMap,nr=new WeakMap,Et=new WeakMap,U=new WeakSet,Symbol.asyncIterator)](){if(i(this,zr,"f"))throw new _("Cannot iterate over a consumed SessionToolRunner");g(this,zr,!0,"f"),i(this,K,"f").info("session tool runner starting",{component:"session-tool-runner",session_id:this.sessionId});let e=i(this,U,"m",Co).call(this).catch(t=>{i(this,q,"f").signal.aborted||i(this,K,"f").error("stream loop failed",{error:String(t)}),i(this,q,"f").abort()});try{for(;;){let r=await i(this,je,"f").next(i(this,q,"f").signal);if(r.done)break;yield r.value}await e;let t;for(;(t=i(this,je,"f").tryShift())!==void 0;)yield t}finally{i(this,q,"f").abort(),i(this,U,"m",rr).call(this),await e;try{await i(this,U,"m",$o).call(this)}catch(t){i(this,K,"f").warn("drain failed",{error:String(t)})}i(this,je,"f").close();for(let t of this.tools)try{await t.close?.()}catch(r){i(this,K,"f").warn("tool.close failed",{tool:Vs(t),error:String(r)})}i(this,Xr,"f").call(this)}}};Gr=function(){return{...i(this,sr,"f"),headers:u([{"x-stainless-helper":na},i(this,sr,"f")?.headers]),signal:i(this,q,"f").signal}},Co=async function(){let e=i(this,q,"f"),t=Oo;for(;!e.signal.aborted;){try{let r=await this.client.beta.sessions.events.stream(this.sessionId,{},i(this,U,"m",Gr).call(this));await i(this,U,"m",Ro).call(this);for await(let n of r)if(t=Oo,await i(this,U,"m",Po).call(this,n))return}catch(r){if(e.signal.throwIfAborted(),ve(r))throw i(this,K,"f").error("permanent stream failure, shutting down",{error:String(r)}),e.abort(),r;i(this,K,"f").warn("stream disconnected, reconnecting",{error:String(r),backoff_ms:t})}e.signal.throwIfAborted(),await ce(t,e.signal),t=Math.min(t*2,oa)}},Ro=async function(){let e=i(this,q,"f"),t=[],r=!1;try{for await(let o of this.client.beta.sessions.events.list(this.sessionId,{limit:1e3},i(this,U,"m",Gr).call(this)))i(this,U,"m",Io).call(this,o,t),r=No(o)}catch(o){e.signal.throwIfAborted(),i(this,K,"f").warn("reconcile list failed",{error:String(o)});for(let a of t)i(this,vt,"f").delete(a.id);return}let n=t.filter(o=>!i(this,fe,"f").has(o.id));r&&n.length===0?i(this,U,"m",zs).call(this):i(this,U,"m",rr).call(this);for(let o of n)await i(this,U,"m",Xs).call(this,o)},Io=function(e,t){e.type==="agent.tool_use"||e.type==="agent.custom_tool_use"?(i(this,vt,"f").add(e.id),i(this,fe,"f").has(e.id)||t.push(e)):e.type==="user.tool_result"?i(this,fe,"f").add(e.tool_use_id):e.type==="user.custom_tool_result"&&i(this,fe,"f").add(e.custom_tool_use_id)},Po=async function(e){switch(No(e)?i(this,U,"m",zs).call(this):i(this,U,"m",rr).call(this),e.type){case"agent.tool_use":case"agent.custom_tool_use":return i(this,vt,"f").has(e.id)||(i(this,vt,"f").add(e.id),await i(this,U,"m",Xs).call(this,e)),!1;case"user.tool_result":return i(this,fe,"f").add(e.tool_use_id),!1;case"user.custom_tool_result":return i(this,fe,"f").add(e.custom_tool_use_id),!1;case"session.status_terminated":case"session.deleted":return i(this,K,"f").info("session terminated",{component:"session-tool-runner",session_id:this.sessionId}),i(this,q,"f").abort(),!0;default:return!1}},zs=function(){i(this,U,"m",rr).call(this),!(this.maxIdleMs<=0)&&g(this,Et,setTimeout(()=>{i(this,K,"f").info("session idle after end_turn; stopping",{component:"session-tool-runner",session_id:this.sessionId,max_idle_ms:this.maxIdleMs}),i(this,q,"f").abort()},this.maxIdleMs),"f")},rr=function(){i(this,Et,"f")!==void 0&&(clearTimeout(i(this,Et,"f")),g(this,Et,void 0,"f"))},Xs=async function(e){var t,r;if(!i(this,fe,"f").has(e.id)){i(this,K,"f").info("executing tool",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),g(this,ge,(t=i(this,ge,"f"),t++,t),"f");try{let n=i(this,Yr,"f").get(e.name);if(!n){i(this,K,"f").info("tool not owned by this runner; leaving the tool_use_id pending for its owner",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),i(this,je,"f").push({event:e,toolUseId:e.id,name:e.name,isError:!1,posted:!1});return}let o,a,c=new AbortController,l=Ue(i(this,q,"f").signal,c),h=setTimeout(()=>c.abort(),ia);try{let f=await Ao(n,e.input,{toolUse:e,toolUseBlock:e,signal:c.signal});o=f.content,a=f.isError}finally{clearTimeout(h),l()}let b=la(e,a,ua(o)),d=await i(this,U,"m",To).call(this,b,e.id);i(this,je,"f").push({event:e,result:b,toolUseId:e.id,name:e.name,isError:a,posted:d})}finally{g(this,ge,(r=i(this,ge,"f"),r--,r),"f"),i(this,ge,"f")===0&&i(this,nr,"f")?.call(this)}}},To=async function(e,t){let r=i(this,q,"f"),n;for(let o=0;o<Mo;o++){r.signal.throwIfAborted();try{return await this.client.beta.sessions.events.send(this.sessionId,{events:[e]},i(this,U,"m",Gr).call(this)),i(this,fe,"f").add(t),!0}catch(a){if(n=a,ve(a))break;o<Mo-1&&await ce((o+1)*1e3,r.signal)}}return i(this,K,"f").error("failed to send tool result",{tool_use_id:t,error:String(n)}),!1},$o=async function(){i(this,ge,"f")!==0&&(await Promise.race([new Promise(e=>g(this,nr,e,"f")),ce(aa)]),g(this,nr,null,"f"),i(this,ge,"f")>0&&i(this,K,"f").warn("drain timeout exceeded"))};function la(s,e,t){return s.type==="agent.custom_tool_use"?{type:"user.custom_tool_result",custom_tool_use_id:s.id,is_error:e,content:t}:{type:"user.tool_result",tool_use_id:s.id,is_error:e,content:t}}function ua(s){if(typeof s=="string")return[{type:"text",text:s||"(no output)"}];let e=s.map(t=>t.type==="text"?{type:"text",text:t.text||"(no output)"}:t.type==="image"||t.type==="document"?t:t.type==="search_result"?{type:"search_result",source:t.source,title:t.title,content:t.content.map(r=>({type:"text",text:r.text})),citations:{enabled:t.citations?.enabled??!1}}:{type:"text",text:JSON.stringify(t)});return e.length>0?e:[{type:"text",text:"(no output)"}]}var Qr,or,Gs,Fo=3e4,da="NO_HEARTBEAT",At=class{constructor(e){Qr.add(this),or.set(this,void 0),this.client=e.client,this.environmentId=e.environmentId,this.environmentKey=e.environmentKey,this.tools=e.tools,this.workdir=e.workdir??process.cwd(),this.unrestrictedPaths=e.unrestrictedPaths,this.maxFileBytes=e.maxFileBytes,this.maxIdleMs=e.maxIdleMs,this.workerId=e.workerId,this.requestOptions=e.requestOptions,g(this,or,e.signal,"f")}async run(e){let{environmentId:t,environmentKey:r}=this;if(t===void 0||r===void 0)throw new _("EnvironmentWorker.run: environmentId and environmentKey are required to poll for work");let n=e??i(this,or,"f"),o=new Ee({client:this.client,environmentId:t,environmentKey:r,...this.workerId!==void 0?{workerId:this.workerId}:{},...n?{signal:n}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},autoStop:!1});for await(let a of o)await i(this,Qr,"m",Gs).call(this,a,r,o.signal)}async handleItem(e){let t=e?.workId??A("ANTHROPIC_WORK_ID"),r=e?.environmentId??A("ANTHROPIC_ENVIRONMENT_ID"),n=e?.sessionId??A("ANTHROPIC_SESSION_ID"),o=e?.environmentKey??this.environmentKey??A("ANTHROPIC_ENVIRONMENT_KEY");if(!t)throw new _("handleItem: workId is required \u2014 pass it or set ANTHROPIC_WORK_ID");if(!r)throw new _("handleItem: environmentId is required \u2014 pass it or set ANTHROPIC_ENVIRONMENT_ID");if(!n)throw new _("handleItem: sessionId is required \u2014 pass it or set ANTHROPIC_SESSION_ID");if(!o)throw new _("handleItem: environmentKey is required \u2014 pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY");let a={id:t,environment_id:r,data:{type:"session",id:n}};await i(this,Qr,"m",Gs).call(this,a,o,e?.signal??i(this,or,"f"))}};or=new WeakMap,Qr=new WeakSet,Gs=async function(e,t,r){let n=T(this.client),o=jr(this.client,{authToken:t,helper:"environments-worker"}),a=e.data.id,c={workdir:this.workdir,client:this.client,sessionId:a,...this.unrestrictedPaths!==void 0?{unrestrictedPaths:this.unrestrictedPaths}:{},...this.maxFileBytes!==void 0?{maxFileBytes:this.maxFileBytes}:{}},l=await import("./node-A6KBFKOV.js"),h=async()=>{};try{h=await l.setupSkills(c)}catch(y){n.warn("skill setup failed",{session_id:a,work_id:e.id,error:String(y)})}let b=typeof this.tools=="function"?this.tools(c):this.tools??l.betaAgentToolset20260401(c),d=new AbortController,f=Ue(r,d),p=fa(o,e,d,n,this.requestOptions).catch(y=>{d.signal.aborted||n.error("heartbeat loop failed",{work_id:e.id,error:String(y)}),d.abort()});try{let y=new Re(a,{client:o,tools:b,...this.maxIdleMs!==void 0?{maxIdleMs:this.maxIdleMs}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},signal:d.signal});for await(let v of y);}finally{d.abort(),f(),await p,await h().catch(y=>{n.warn("skill cleanup failed",{session_id:a,work_id:e.id,error:String(y)})}),await ha(o,e,n,this.requestOptions)}};async function ha(s,e,t,r){try{await s.beta.environments.work.stop(e.id,{environment_id:e.environment_id,force:!0},{...r,headers:u([r?.headers])})}catch(n){ke(n,409)||t.error("force-stop on exit failed",{work_id:e.id,error:String(n)})}}async function fa(s,e,t,r,n){let o=Fo,a=da,c=async()=>{try{let l=await s.beta.environments.work.heartbeat(e.id,{environment_id:e.environment_id,expected_last_heartbeat:a},{...n,headers:u([n?.headers]),signal:t.signal});a=l.last_heartbeat,l.ttl_seconds>0&&(o=Math.max(1e3,Math.min(l.ttl_seconds*1e3/2,Fo))),(l.state==="stopping"||l.state==="stopped")&&(r.info("heartbeat signals shutdown",{work_id:e.id,state:l.state}),t.abort()),l.lease_extended||(r.warn("lease not extended, shutting down",{work_id:e.id}),t.abort())}catch(l){if(t.signal.throwIfAborted(),ve(l))throw r.error("permanent heartbeat failure",{work_id:e.id,error:String(l)}),t.abort(),l;r.warn("transient heartbeat failure",{work_id:e.id,error:String(l)})}};for(await c();!t.signal.aborted;)await ce(o,t.signal),t.signal.throwIfAborted(),await c()}var Ie=class extends x{retrieve(e,t,r){let{environment_id:n,betas:o}=t;return this._client.get(m`/v1/environments/${n}/work/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{environment_id:n,betas:o,...a}=t;return this._client.post(m`/v1/environments/${n}/work/${e}?beta=true`,{body:a,...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){let{betas:n,...o}=t??{};return this._client.getAPIList(m`/v1/environments/${e}/work?beta=true`,E,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}ack(e,t,r){let{environment_id:n,betas:o}=t;return this._client.post(m`/v1/environments/${n}/work/${e}/ack?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}heartbeat(e,t,r){let{environment_id:n,desired_ttl_seconds:o,expected_last_heartbeat:a,betas:c}=t;return this._client.post(m`/v1/environments/${n}/work/${e}/heartbeat?beta=true`,{query:{desired_ttl_seconds:o,expected_last_heartbeat:a},...r,headers:u([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}poll(e,t={},r){let{betas:n,"Anthropic-Worker-ID":o,...a}=t??{};return this._client.get(m`/v1/environments/${e}/work/poll?beta=true`,{query:a,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString(),...o!=null?{"Anthropic-Worker-ID":o}:void 0},r?.headers])})}stats(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/environments/${e}/work/stats?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}stop(e,t,r){let{environment_id:n,betas:o,...a}=t;return this._client.post(m`/v1/environments/${n}/work/${e}/stop?beta=true`,{body:a,...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}poller(e){return new Ee({...e,client:this._client})}worker(e){return new At({...e,client:this._client})}};Ie.WorkPoller=Ee;Ie.EnvironmentWorker=At;var We=class extends x{constructor(){super(...arguments),this.work=new Ie(this._client)}create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/environments?beta=true",{body:n,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/environments/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:n,...o}=t;return this._client.post(m`/v1/environments/${e}?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...n}=e??{};return this._client.getAPIList("/v1/environments?beta=true",E,{query:n,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}delete(e,t={},r){let{betas:n}=t??{};return this._client.delete(m`/v1/environments/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t={},r){let{betas:n}=t??{};return this._client.post(m`/v1/environments/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};We.Work=Ie;var Rt=class extends x{create(e,t,r){let{view:n,betas:o,...a}=t;return this._client.post(m`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:n},body:a,...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,t,r){let{memory_store_id:n,betas:o,...a}=t;return this._client.get(m`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:a,...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{memory_store_id:n,view:o,betas:a,...c}=t;return this._client.post(m`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:{view:o},body:c,...r,headers:u([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){let{betas:n,...o}=t??{};return this._client.getAPIList(m`/v1/memory_stores/${e}/memories?beta=true`,E,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,t,r){let{memory_store_id:n,expected_content_sha256:o,betas:a}=t;return this._client.delete(m`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:{expected_content_sha256:o},...r,headers:u([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};var It=class extends x{retrieve(e,t,r){let{memory_store_id:n,betas:o,...a}=t;return this._client.get(m`/v1/memory_stores/${n}/memory_versions/${e}?beta=true`,{query:a,...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){let{betas:n,...o}=t??{};return this._client.getAPIList(m`/v1/memory_stores/${e}/memory_versions?beta=true`,E,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}redact(e,t,r){let{memory_store_id:n,betas:o}=t;return this._client.post(m`/v1/memory_stores/${n}/memory_versions/${e}/redact?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};var Pe=class extends x{constructor(){super(...arguments),this.memories=new Rt(this._client),this.memoryVersions=new It(this._client)}create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/memory_stores?beta=true",{body:n,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/memory_stores/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:n,...o}=t;return this._client.post(m`/v1/memory_stores/${e}?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...n}=e??{};return this._client.getAPIList("/v1/memory_stores?beta=true",E,{query:n,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}delete(e,t={},r){let{betas:n}=t??{};return this._client.delete(m`/v1/memory_stores/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t={},r){let{betas:n}=t??{};return this._client.post(m`/v1/memory_stores/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};Pe.Memories=Rt;Pe.MemoryVersions=It;var Pt=class s{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new me;for await(let t of this.iterator)for(let r of e.decode(t))yield JSON.parse(r);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new _("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 _("Attempted to iterate over a response with no body");return new s(qt(e.body),t)}};var Tt=class extends x{create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/messages/batches?beta=true",{body:n,...t,headers:u([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/messages/batches/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}list(e={},t){let{betas:r,...n}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",ne,{query:n,...t,headers:u([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t?.headers])})}delete(e,t={},r){let{betas:n}=t??{};return this._client.delete(m`/v1/messages/batches/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}cancel(e,t={},r){let{betas:n}=t??{};return this._client.post(m`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}async results(e,t={},r){let n=await this.retrieve(e);if(!n.results_url)throw new _(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);let{betas:o}=t??{};return this._client.get(n.results_url,{...r,headers:u([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},r?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((a,c)=>Pt.fromResponse(c.response,c.controller))}};var Zr={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function Lo(s){return s?.output_format??s?.output_config?.format}function Ys(s,e,t){let r=Lo(e);return!e||!("parse"in(r??{}))?{...s,content:s.content.map(n=>{if(n.type==="text"){let o=Object.defineProperty({...n},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(o,"parsed",{get(){return t.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return n}),parsed_output:null}:Qs(s,e,t)}function Qs(s,e,t){let r=null,n=s.content.map(o=>{if(o.type==="text"){let a=wa(e,o.text);r===null&&(r=a);let c=Object.defineProperty({...o},"parsed_output",{value:a,enumerable:!1});return Object.defineProperty(c,"parsed",{get(){return t.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),a},enumerable:!1})}return o});return{...s,content:n,parsed_output:r}}function wa(s,e){let t=Lo(s);if(t?.type!=="json_schema")return null;try{return"parse"in t?t.parse(e):JSON.parse(e)}catch(r){throw new _(`Failed to parse structured output: ${r}`)}}var xa=s=>{let e=0,t=[];for(;e<s.length;){let r=s[e];if(r==="\\"){e++;continue}if(r==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(r==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(r==="["){t.push({type:"paren",value:"["}),e++;continue}if(r==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(r===":"){t.push({type:"separator",value:":"}),e++;continue}if(r===","){t.push({type:"delimiter",value:","}),e++;continue}if(r==='"'){let c="",l=!1;for(r=s[++e];r!=='"';){if(e===s.length){l=!0;break}if(r==="\\"){if(e++,e===s.length){l=!0;break}c+=r+s[e],r=s[++e]}else c+=r,r=s[++e]}r=s[++e],l||t.push({type:"string",value:c});continue}if(r&&/\s/.test(r)){e++;continue}let o=/[0-9]/;if(r&&o.test(r)||r==="-"||r==="."){let c="";for(r==="-"&&(c+=r,r=s[++e]);r&&(o.test(r)||r==="."||r==="e"||r==="E"||(r==="-"||r==="+")&&(c[c.length-1]==="e"||c[c.length-1]==="E"));)c+=r,r=s[++e];t.push({type:"number",value:c});continue}let a=/[a-z]/i;if(r&&a.test(r)){let c="";for(;r&&a.test(r)&&e!==s.length;)c+=r,r=s[++e];if(c=="true"||c=="false"||c==="null")t.push({type:"name",value:c});else{e++;continue}continue}e++}return t},Ot=s=>{if(s.length===0)return s;let e=s[s.length-1];switch(e.type){case"separator":return s=s.slice(0,s.length-1),Ot(s);break;case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-"||t==="+"||t==="e"||t==="E")return s=s.slice(0,s.length-1),Ot(s);case"string":let r=s[s.length-2];if(r?.type==="delimiter")return s=s.slice(0,s.length-1),Ot(s);if(r?.type==="brace"&&r.value==="{")return s=s.slice(0,s.length-1),Ot(s);break;case"delimiter":return s=s.slice(0,s.length-1),Ot(s);break}return s},Sa=s=>{let e=[];return s.map(t=>{t.type==="brace"&&(t.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),t.type==="paren"&&(t.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(t=>{t==="}"?s.push({type:"brace",value:"}"}):t==="]"&&s.push({type:"paren",value:"]"})}),s},ka=s=>{let e="";return s.map(t=>{t.type==="string"?e+='"'+t.value+'"':e+=t.value}),e},es=s=>JSON.parse(ka(Sa(Ot(xa(s)))));var ie,Te,Mt,ir,ts,ar,cr,rs,lr,_e,ur,ss,ns,qe,os,is,dr,Zs,Ho,as,en,tn,rn,Bo,Do="__json_buf";function Uo(s){return s.type==="tool_use"||s.type==="server_tool_use"||s.type==="mcp_tool_use"}var cs=class s{constructor(e,t){ie.add(this),this.messages=[],this.receivedMessages=[],Te.set(this,void 0),Mt.set(this,null),this.controller=new AbortController,ir.set(this,void 0),ts.set(this,()=>{}),ar.set(this,()=>{}),cr.set(this,void 0),rs.set(this,()=>{}),lr.set(this,()=>{}),_e.set(this,{}),ur.set(this,!1),ss.set(this,!1),ns.set(this,!1),qe.set(this,!1),os.set(this,void 0),is.set(this,void 0),dr.set(this,void 0),as.set(this,r=>{if(g(this,ss,!0,"f"),re(r)&&(r=new W),r instanceof W)return g(this,ns,!0,"f"),this._emit("abort",r);if(r instanceof _)return this._emit("error",r);if(r instanceof Error){let n=new _(r.message);return n.cause=r,this._emit("error",n)}return this._emit("error",new _(String(r)))}),g(this,ir,new Promise((r,n)=>{g(this,ts,r,"f"),g(this,ar,n,"f")}),"f"),g(this,cr,new Promise((r,n)=>{g(this,rs,r,"f"),g(this,lr,n,"f")}),"f"),i(this,ir,"f").catch(()=>{}),i(this,cr,"f").catch(()=>{}),g(this,Mt,e,"f"),g(this,dr,t?.logger??console,"f")}get response(){return i(this,os,"f")}get request_id(){return i(this,is,"f")}async withResponse(){g(this,qe,!0,"f");let e=await i(this,ir,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r,{logger:n}={}){let o=new s(t,{logger:n});for(let a of t.messages)o._addMessageParam(a);return g(o,Mt,{...t,stream:!0},"f"),o._run(()=>o._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),o}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},i(this,as,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){let n=r?.signal,o;n&&(n.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),n.addEventListener("abort",o));try{i(this,ie,"m",en).call(this);let{response:a,data:c}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(a);for await(let l of c)i(this,ie,"m",tn).call(this,l);if(c.controller.signal?.aborted)throw new W;i(this,ie,"m",rn).call(this)}finally{n&&o&&n.removeEventListener("abort",o)}}_connected(e){this.ended||(g(this,os,e,"f"),g(this,is,e?.headers.get("request-id"),"f"),i(this,ts,"f").call(this,e),this._emit("connect"))}get ended(){return i(this,ur,"f")}get errored(){return i(this,ss,"f")}get aborted(){return i(this,ns,"f")}abort(){this.controller.abort()}on(e,t){return(i(this,_e,"f")[e]||(i(this,_e,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=i(this,_e,"f")[e];if(!r)return this;let n=r.findIndex(o=>o.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(i(this,_e,"f")[e]||(i(this,_e,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{g(this,qe,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){g(this,qe,!0,"f"),await i(this,cr,"f")}get currentMessage(){return i(this,Te,"f")}async finalMessage(){return await this.done(),i(this,ie,"m",Zs).call(this)}async finalText(){return await this.done(),i(this,ie,"m",Ho).call(this)}_emit(e,...t){if(i(this,ur,"f"))return;e==="end"&&(g(this,ur,!0,"f"),i(this,rs,"f").call(this));let r=i(this,_e,"f")[e];if(r&&(i(this,_e,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!i(this,qe,"f")&&!r?.length&&Promise.reject(n),i(this,ar,"f").call(this,n),i(this,lr,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!i(this,qe,"f")&&!r?.length&&Promise.reject(n),i(this,ar,"f").call(this,n),i(this,lr,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",i(this,ie,"m",Zs).call(this))}async _fromReadableStream(e,t){let r=t?.signal,n;r&&(r.aborted&&this.controller.abort(),n=this.controller.abort.bind(this.controller),r.addEventListener("abort",n));try{i(this,ie,"m",en).call(this),this._connected(null);let o=Q.fromReadableStream(e,this.controller);for await(let a of o)i(this,ie,"m",tn).call(this,a);if(o.controller.signal?.aborted)throw new W;i(this,ie,"m",rn).call(this)}finally{r&&n&&r.removeEventListener("abort",n)}}[(Te=new WeakMap,Mt=new WeakMap,ir=new WeakMap,ts=new WeakMap,ar=new WeakMap,cr=new WeakMap,rs=new WeakMap,lr=new WeakMap,_e=new WeakMap,ur=new WeakMap,ss=new WeakMap,ns=new WeakMap,qe=new WeakMap,os=new WeakMap,is=new WeakMap,dr=new WeakMap,as=new WeakMap,ie=new WeakSet,Zs=function(){if(this.receivedMessages.length===0)throw new _("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Ho=function(){if(this.receivedMessages.length===0)throw new _("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(t.length===0)throw new _("stream ended without producing a content block with type=text");return t.join(" ")},en=function(){this.ended||g(this,Te,void 0,"f")},tn=function(t){if(this.ended)return;let r=i(this,ie,"m",Bo).call(this,t);switch(this._emit("streamEvent",t,r),t.type){case"content_block_delta":{let n=r.content.at(-1);switch(t.delta.type){case"text_delta":{n.type==="text"&&this._emit("text",t.delta.text,n.text||"");break}case"citations_delta":{n.type==="text"&&this._emit("citation",t.delta.citation,n.citations??[]);break}case"input_json_delta":{Uo(n)&&n.input&&this._emit("inputJson",t.delta.partial_json,n.input);break}case"thinking_delta":{n.type==="thinking"&&this._emit("thinking",t.delta.thinking,n.thinking);break}case"signature_delta":{n.type==="thinking"&&this._emit("signature",n.signature);break}case"compaction_delta":{n.type==="compaction"&&n.content&&this._emit("compaction",n.content);break}default:t.delta}break}case"message_stop":{this._addMessageParam(r),this._addMessage(Ys(r,i(this,Mt,"f"),{logger:i(this,dr,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{g(this,Te,r,"f");break}case"content_block_start":case"message_delta":break}},rn=function(){if(this.ended)throw new _("stream has ended, this shouldn't happen");let t=i(this,Te,"f");if(!t)throw new _("request ended without sending any chunks");return g(this,Te,void 0,"f"),Ys(t,i(this,Mt,"f"),{logger:i(this,dr,"f")})},Bo=function(t){let r=i(this,Te,"f");if(t.type==="message_start"){if(r)throw new _(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!r)throw new _(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return r;case"message_delta":return r.container=t.delta.container,r.stop_reason=t.delta.stop_reason,r.stop_sequence=t.delta.stop_sequence,t.delta.stop_details!=null&&(r.stop_details=t.delta.stop_details),r.usage.output_tokens=t.usage.output_tokens,r.context_management=t.context_management,t.usage.input_tokens!=null&&(r.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(r.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(r.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(r.usage.server_tool_use=t.usage.server_tool_use),t.usage.iterations!=null&&(r.usage.iterations=t.usage.iterations),r;case"content_block_start":return r.content.push(t.content_block),t.content_block.type==="fallback"&&(r.model=t.content_block.to.model),r;case"content_block_delta":{let n=r.content.at(t.index);switch(t.delta.type){case"text_delta":{n?.type==="text"&&(r.content[t.index]={...n,text:(n.text||"")+t.delta.text});break}case"citations_delta":{n?.type==="text"&&(r.content[t.index]={...n,citations:[...n.citations??[],t.delta.citation]});break}case"input_json_delta":{if(n&&Uo(n)){let o=n[Do]||"";o+=t.delta.partial_json;let a={...n};if(Object.defineProperty(a,Do,{value:o,enumerable:!1,writable:!0}),o)try{a.input=es(o)}catch(c){let l=new _(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${c}. JSON: ${o}`);i(this,as,"f").call(this,l)}r.content[t.index]=a}break}case"thinking_delta":{n?.type==="thinking"&&(r.content[t.index]={...n,thinking:n.thinking+t.delta.thinking});break}case"signature_delta":{n?.type==="thinking"&&(r.content[t.index]={...n,signature:t.delta.signature});break}case"compaction_delta":{n?.type==="compaction"&&(r.content[t.index]={...n,content:(n.content||"")+t.delta.content,encrypted_content:t.delta.encrypted_content});break}default:t.delta}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Q(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var jo=`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:
13
13
  1. Task Overview
14
14
  The user's core request and success criteria
15
15
  Any clarifications or constraints they specified
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __swiftyCreateRequire } from "node:module";
3
+ const require = __swiftyCreateRequire(import.meta.url);
4
+ import{a as k,f as P}from"./chunk-NAAAN2TD.js";import{D as t,b as _,c as y}from"./chunk-NCZR3AGA.js";import{existsSync as L,readFileSync as O}from"fs";import{homedir as G}from"os";import{join as N}from"path";function h(e){return!!e._zod}function p(e,n){return h(e)?_(e,n):e.safeParse(n)}async function je(e,n){return h(e)?await y(e,n):await e.safeParseAsync(n)}function Le(e){if(!e)return;let n;if(h(e)?n=e._zod?.def?.shape:n=e.shape,!!n){if(typeof n=="function")try{return n()}catch{return}return n}}function Y(e){return e.length===0?"object root":e.reduce((n,o,r)=>r===0?String(o):typeof o=="number"?`${n}[${o}]`:`${n}.${o}`,"")}function b(e){if(e&&typeof e=="object"){if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0)return e.issues.map(n=>n.path?.length?`${n.message} at ${Y(n.path)}`:n.message).join(`
5
+ `);if("message"in e&&typeof e.message=="string")return e.message;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function Oe(e){if(h(e)){let a=e._zod?.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}let o=e._def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}let r=e.value;if(r!==void 0)return r}var m=P({module:"config"}),I={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY","openai-compat":"OPENAI_API_KEY"};function W(e){return S.has(e)}var S=new Set(Object.keys(I)),f=class extends Error{constructor(n){super(n),this.name="ConfigError"}};function Z(){return N(G(),".swifty","config.yaml")}var v=["off","minimal","low","medium","high","xhigh","max"],d=t.enum(["none","minimal","low","medium","high","xhigh","max"]),X=t.enum(["low","medium","high","xhigh","max"]),q=t.strictObject({off:t.literal("none").nullable().optional(),minimal:d.nullable().optional(),low:d.nullable().optional(),medium:d.nullable().optional(),high:d.nullable().optional(),xhigh:d.nullable().optional(),max:d.nullable().optional()}),$=t.looseObject({name:t.string(),protocol:t.enum(["anthropic","openai","openai-compat"]),base_url:t.string(),model:t.string(),api_key:t.string().optional(),thinking:t.enum(v).optional(),reasoning:t.boolean().optional(),thinking_level_map:q.optional(),thinking_mode:t.enum(["budget","adaptive"]).optional(),context_window:t.coerce.number().optional(),max_output_tokens:t.coerce.number().optional()}),Q="high",E=1e6,C=128e3,ee={minimal:1024,low:2048,medium:8192,high:16384,xhigh:32768,max:65536},ne=1024,oe=1024;function Ve(e){return v.some(n=>n===e)}function te(e){return se(e,e.thinking??Q)}function Fe(e){return e==="off"?0:ee[e]}function z(e,n){if(n?.reasoning===!1)return null;if(e==="off")return"none";let o=n?.thinking_level_map?.[e];if(o!==void 0)return o;if(n?.protocol==="anthropic"&&n.thinking_mode==="adaptive"){if(e==="minimal")return"low";if(e==="xhigh")return"high"}return e}function re(e,n){let o=X.safeParse(z(e,n));return o.success?o.data:null}function ie(e){return e.reasoning===!1||e.protocol==="anthropic"&&e.thinking_mode!=="adaptive"&&U(e)<ne+oe?["off"]:v.filter(n=>{if(n==="off")return!0;if(e.protocol==="anthropic"&&e.thinking_mode==="adaptive")return re(n,e)!==null;let o=z(n,e);return o!==null&&o!=="none"})}function se(e,n){let o=ie(e),r="off";for(let i of v)if(o.includes(i)&&(r=i),i===n)break;return r}function T(e){return{...e,thinking:te(e),context_window:R(e),max_output_tokens:U(e)}}function R(e){return Number.isSafeInteger(e.context_window)&&(e.context_window??0)>0?e.context_window??E:E}function U(e){let n=e.max_output_tokens,o=Number.isSafeInteger(n)&&(n??0)>0?n??C:C;return Math.min(o,R(e))}function Be(e){if(e.api_key)return e.api_key;let n=W(e.protocol)?I[e.protocol]:"";return n?process.env[n]??"":""}var K=t.object({name:t.string(),command:t.string().optional(),args:t.array(t.string()).optional(),url:t.string().optional(),transport:t.string().optional(),headers:t.record(t.string(),t.string()).optional(),env:t.record(t.string(),t.string()).optional()}),D=t.object({id:t.string().optional(),event:t.string(),condition:t.string().optional(),action:t.object({type:t.string(),command:t.string().optional(),url:t.string().optional(),method:t.string().optional(),prompt:t.string().optional()}),reject:t.boolean().optional(),once:t.boolean().optional(),async:t.boolean().optional(),on_error:t.string().optional()}),V=t.object({enabled:t.boolean().optional(),auto_allow:t.boolean().optional(),network_enabled:t.boolean().optional()}),ae=t.looseObject({providers:t.array($),permission_mode:t.string().optional(),mcp_servers:t.array(K).default([]),hooks:t.array(D).default([]),sandbox:V.optional(),enable_coordinator_mode:t.boolean().optional(),enable_fork:t.boolean().optional()});function He(e){return e.enable_fork!==!1}function ce(e){return typeof e=="object"&&e!==null}function A(e){let n=O(e,"utf-8"),o=k.load(n);if(!ce(o))return m.error({path:e},"invalid yaml"),{providers:[],mcp_servers:[],hooks:[]};let r=p(ae,o);if(r.success){let c=r.data;return{...c,providers:c.providers.map(T)}}m.error({error:r.error},"config error");let i=[],a,l=[],s=[],u,x=!1,w=!0;if("providers"in o){let c=p(t.array($),o.providers);if(c.success)i=c.data.map(T);else throw new f(`Invalid provider configuration in ${e}: ${b(c.error)}`)}if("permission_mode"in o&&typeof o.permission_mode=="string"&&(a=o.permission_mode),"mcp_servers"in o){let c=p(t.array(K),o.mcp_servers);if(c.success)l=c.data;else throw new f(`Invalid MCP server configuration in ${e}: ${b(c.error)}`)}if("hooks"in o){let c=p(t.array(D),o.hooks);c.success&&(s=c.data)}if("sandbox"in o){let c=p(V,o.sandbox);c.success&&(u=c.data)}return"enable_coordinator_mode"in o&&(x=!!o.enable_coordinator_mode),"enable_fork"in o&&(w=!!o.enable_fork),{providers:i,permission_mode:a,mcp_servers:l,hooks:s,sandbox:u,enable_coordinator_mode:x,enable_fork:w}}function M(e){if(e.providers.length===0)throw new f("At least one provider MUST be configured.");let n=["name","protocol","base_url","model"],o=new Map;for(let r=0;r<e.providers.length;r++){let i=e.providers[r],a={name:i.name,protocol:i.protocol,base_url:i.base_url,model:i.model},l=n.filter(u=>!a[u].trim());if(l.length>0)throw new f(`Provider #${String(r+1)}: missing fields: ${l.join(", ")}`);if(!S.has(i.protocol))throw new f(`Provider #${String(r+1)}: invalid protocol '${i.protocol}', MUST be one of: ${Array.from(S).join(", ")}`);let s=o.get(i.base_url);if(s!==void 0)throw new f(`Provider #${String(r+1)}: duplicate base_url '${i.base_url}' (already used by provider #${String(s+1)}).`);o.set(i.base_url,r)}}function j(e){let n=new Map;for(let o=0;o<e.mcp_servers.length;o++){let r=e.mcp_servers[o],i=`MCP server #${String(o+1)}`;if(!r.name.trim())throw new f(`${i}: name must not be empty.`);let a=n.get(r.name);if(a!==void 0)throw new f(`${i}: duplicate name '${r.name}' (already used by MCP server #${String(a+1)}).`);n.set(r.name,o);let l=!!r.command?.trim(),s=!!r.url?.trim();if(l===s)throw new f(`${i} '${r.name}': configure exactly one of command or url.`);if(l&&r.transport&&r.transport!=="stdio")throw new f(`${i} '${r.name}': command servers must use stdio.`);if(s&&r.transport&&!["http","sse"].includes(r.transport))throw new f(`${i} '${r.name}': URL transport must be http or sse.`)}}var le=".mcp.json",fe=t.looseObject({command:t.string().optional(),args:t.array(t.string()).optional(),env:t.record(t.string(),t.string()).optional(),type:t.enum(["stdio","sse","http"]).optional(),url:t.string().optional(),headers:t.record(t.string(),t.string()).optional()}),ue=t.looseObject({mcpServers:t.record(t.string(),t.unknown()).default({})});function pe(e,n){let o=n.type??(n.command!==void 0?"stdio":"http");return o==="stdio"?!n.command||n.url!==void 0?null:{name:e,command:n.command,args:n.args,env:n.env}:!n.url||n.command!==void 0?null:{name:e,url:n.url,transport:o,headers:n.headers}}function de(e){let n=N(e,le);if(!L(n))return[];let o;try{o=JSON.parse(O(n,"utf-8"))}catch(a){return m.error({err:a,path:n},"invalid .mcp.json"),[]}let r=p(ue,o);if(!r.success)return m.error({error:r.error,path:n},"invalid .mcp.json"),[];let i=[];for(let[a,l]of Object.entries(r.data.mcpServers)){let s=p(fe,l);if(!a.trim()||!s.success){m.warn({name:a,path:n,error:s.success?void 0:s.error},"skipping invalid .mcp.json server entry");continue}let u=pe(a,s.data);u?i.push(u):m.warn({name:a,path:n},"skipping invalid .mcp.json server entry")}return i}function Je(e,n){let o=de(n);if(o.length===0)return e;let r=new Set(e.mcp_servers.map(i=>i.name));return{...e,mcp_servers:[...e.mcp_servers,...o.filter(i=>!r.has(i.name))]}}function Ye(e,n={}){if(e){let i=A(e);return j(i),(!n.allowEmptyProviders||i.providers.length>0)&&M(i),i}let o=Z();if(!L(o)){if(n.allowEmptyProviders)return{providers:[],mcp_servers:[],hooks:[]};throw new f(`No config file found, expected ${o}.`)}let r=A(o);return j(r),(!n.allowEmptyProviders||r.providers.length>0)&&M(r),r}var g=class extends Error{constructor(n){super(n),this.name="LLMError"}},F=class extends g{constructor(n){super(n),this.name="AuthenticationError"}},B=class extends g{retryAfter;constructor(n,o){super(n),this.name="RateLimitError",this.retryAfter=o}},H=class extends g{constructor(n){super(n),this.name="NetworkError"}},J=class extends g{constructor(n){super(n),this.name="ContextTooLongError"}};var me="Tool execution was interrupted. The tool may or may not have completed; verify before relying on its effects.",Ze="The user rejected this tool use. Nothing was changed (for file edits, the new content was NOT written).";function Xe(e){let n=[];for(let o=0;o<e.length;o++){let r=e[o];if(r.role==="assistant"&&r.toolUses?.length){n.push(r);let i=new Set(r.toolUses.map(s=>s.toolUseId)),a=[],l=[];for(;o+1<e.length;){let s=e[o+1];if(s.role!=="user"||!s.toolResults?.length||s.toolUses?.length)break;o++,l.push(s);for(let u of s.toolResults)i.delete(u.toolUseId)&&a.push(u)}for(let s of i)a.push({toolUseId:s,content:me,isError:!0});n.push({...l[0]??{role:"user",content:""},toolResults:a});for(let s of l.slice(1))(s.content.length>0||s.thinkingBlocks?.length)&&n.push({...s,toolResults:[]});continue}if((r.toolResults?.length??0)>0){if(r.content.length===0&&!r.toolUses?.length&&!r.thinkingBlocks?.length)continue;n.push({...r,toolResults:[]})}else n.push(r)}return n}export{p as a,je as b,Le as c,Oe as d,Z as e,v as f,$ as g,Q as h,E as i,C as j,oe as k,Ve as l,te as m,Fe as n,z as o,re as p,ie as q,se as r,R as s,U as t,Be as u,He as v,Je as w,Ye as x,g as y,F as z,B as A,H as B,J as C,Ze as D,Xe as E};