@swifty.js/swifty 0.0.1-canary
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/anthropic-IS6JB2DP.js +4 -0
- package/dist/builtin/commit/SKILL.md +41 -0
- package/dist/builtin/fullstack-interview/SKILL.md +105 -0
- package/dist/builtin/teach-me/SKILL.md +399 -0
- package/dist/builtin/teach-me/references/pedagogy.md +244 -0
- package/dist/builtin/test/SKILL.md +42 -0
- package/dist/chunk-DNCLVUXL.js +10 -0
- package/dist/chunk-H7VXSMJR.js +44 -0
- package/dist/chunk-NCPOPA4A.js +4 -0
- package/dist/chunk-X3UA5OZL.js +4 -0
- package/dist/chunk-XWWKIJ5J.js +121 -0
- package/dist/cleanup-4R3534Z3.js +4 -0
- package/dist/devtools-X2EGZM6L.js +7 -0
- package/dist/glob_addon.node +0 -0
- package/dist/main.js +1455 -0
- package/dist/node-OES65R33.js +15 -0
- package/dist/openai-4CKFFKCY.js +27 -0
- package/dist/release-JP26O6LN.js +4 -0
- package/dist/release.wasm +0 -0
- package/docs/ch1.md +25 -0
- package/docs/ch10.md +122 -0
- package/docs/ch11.md +163 -0
- package/docs/ch12.md +288 -0
- package/docs/ch13.md +320 -0
- package/docs/ch14.md +146 -0
- package/docs/ch15.md +62 -0
- package/docs/ch2.md +273 -0
- package/docs/ch3.md +206 -0
- package/docs/ch4.md +125 -0
- package/docs/ch5.md +165 -0
- package/docs/ch6.md +201 -0
- package/docs/ch7.md +448 -0
- package/docs/ch8.md +218 -0
- package/docs/ch9.md +351 -0
- package/docs/index.css +23 -0
- package/docs/index.md +21 -0
- package/docs/swifty.mdx +7 -0
- package/package.json +116 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
|
+
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
+
import{b as wr,d as ri}from"./chunk-X3UA5OZL.js";var fo=wr(Dr=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});Dr.timingSafeEqual=void 0;function ho(s,e=""){if(!s)throw new Error(e)}function Ui(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)),ho(s instanceof DataView),ho(e instanceof DataView);let t=s.byteLength,r=0,n=-1;for(;++n<t;)r|=s.getUint8(n)^e.getUint8(n);return r===0}Dr.timingSafeEqual=Ui});var go=wr(Z=>{"use strict";var ji=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,qs=(function(){function s(e){e===void 0&&(e="="),this._paddingCharacter=e}return s.prototype.encodedLength=function(e){return this._paddingCharacter?(e+2)/3*4|0:(e*8+5)/6|0},s.prototype.encode=function(e){for(var t="",r=0;r<e.length-2;r+=3){var n=e[r]<<16|e[r+1]<<8|e[r+2];t+=this._encodeByte(n>>>18&63),t+=this._encodeByte(n>>>12&63),t+=this._encodeByte(n>>>6&63),t+=this._encodeByte(n>>>0&63)}var 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=qs;var Zt=new qs;function Wi(s){return Zt.encode(s)}Z.encode=Wi;function qi(s){return Zt.decode(s)}Z.decode=qi;var po=(function(s){ji(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})(qs);Z.URLSafeCoder=po;var mo=new po;function Ji(s){return mo.encode(s)}Z.encodeURLSafe=Ji;function Ki(s){return mo.decode(s)}Z.decodeURLSafe=Ki;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 bo=wr((_o,Ur)=>{"use strict";(function(s,e){var t={};e(t);var r=t.default;for(var n in t)r[n]=t[n];typeof Ur=="object"&&typeof Ur.exports=="object"?Ur.exports=r:typeof define=="function"&&define.amd?define(function(){return r}):s.sha256=r})(_o,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,A){for(var S,k,w,I,R,P,V,M,L,N,$,te,$e;A>=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,A-=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,A=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]=A>>>24&255,this.buffer[k-7]=A>>>16&255,this.buffer[k-6]=A>>>8&255,this.buffer[k-5]=A>>>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 A=y[0];if(A===0)throw new Error("hkdf: cannot expand more");f.reset(),A>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 A=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,A),I=0),R[P]=w[I++];return k.clean(),w.fill(0),A.fill(0),R}s.hkdf=h;function b(d,f,p,y){for(var A=new n(d),S=A.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,A.reset(),A.update(f),A.update(k),A.finish(I);for(var M=0;M<S;M++)w[M]=I[M];for(var M=2;M<=p;M++){A.reset(),A.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 A.clean(),R}s.pbkdf2=b})});var xo=wr(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.Webhook=_t.WebhookVerificationError=void 0;var Vi=fo(),yo=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 jr=class s{constructor(e,t){if(!e)throw new Error("Secret can't be empty.");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)}}verify(e,t){let r={};for(let f of Object.keys(t))r[f.toLowerCase()]=t[f];let n=r["webhook-id"],o=r["webhook-signature"],a=r["webhook-timestamp"];if(!o||!n||!a)throw new Se("Missing required headers");let c=this.verifyTimestamp(a),h=this.sign(n,c,e).split(",")[1],b=o.split(" "),d=new globalThis.TextEncoder;for(let f of b){let[p,y]=f.split(",");if(p==="v1"&&(0,Vi.timingSafeEqual)(d.encode(y),d.encode(h)))return JSON.parse(e.toString())}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(zi.hmac(this.key,a))}`}verifyTimestamp(e){let t=Math.floor(Date.now()/1e3),r=parseInt(e,10);if(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=jr;jr.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 ys(){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)),ws=J;function xr(s){return typeof s!="object"?{}:s??{}}function xs(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 Ss(...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 Ss({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 ks="RFC3986",vs=s=>String(s),Es={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:vs},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 As=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+=As){let l=o.length>=As?o.slice(c,c+As):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 Rs(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:ks,formatter:vs,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 Is={};function On(s,e,t,r,n,o,a,c,l,h,b,d,f,p,y,A,S,k){let w=s,I=k,R=0,P=!1;for(;(I=I.get(Is))!==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(Is)>"u"&&(R=0)}if(typeof h=="function"?w=h(e,w):w instanceof Date?w=f?.(w):t==="comma"&&J(w)&&(w=Rs(w,function($){return $ instanceof Date?f?.($):$})),w===null){if(o)return l&&!A?l(e,D.encoder,S,"key",p):e;w=""}if(ui(w)||Rn(w)){if(l){let $=A?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))A&&l&&(w=Rs(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 bs=d&&c?te.replace(/\./g,"%2E"):te,ti=J(w)?typeof t=="function"?t(N,bs):N:N+(d?"."+bs:"["+bs+"]");k.set(s,R);let pn=new WeakMap;pn.set(Is,k),Tn(V,On($e,ti,t,r,n,o,a,c,t==="comma"&&A&&J(w)?null:l,h,b,d,f,p,y,A,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=ks;if(typeof s.format<"u"){if(!kr(Es,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=Es[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 Ps=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<=Ps?s:s.slice(0,Ps)+`... <${s.length-Ps} 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 E=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 Ts(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 Ms(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?Ms(e,t):mi}var qn,Os;function Jn(){let s=E("ANTHROPIC_LOG");return(!Os||s!==qn)&&(qn=s,Os=Ms(console,Mr(s,"process.env['ANTHROPIC_LOG']",Ms(console,Kt))??Kt)),Os}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 Ns();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=E("ANTHROPIC_ORGANIZATION_ID"),f=E("ANTHROPIC_IDENTITY_TOKEN_FILE"),p=E("ANTHROPIC_FEDERATION_RULE_ID");return p&&d?{fromFile:!1,config:{organization_id:d,workspace_id:E("ANTHROPIC_WORKSPACE_ID"),base_url:E("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:p,service_account_id:E("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:f?{source:"file",path:f}:void 0,scope:E("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=E("ANTHROPIC_ORGANIZATION_ID")),h.workspace_id??(h.workspace_id=E("ANTHROPIC_WORKSPACE_ID")),h.base_url??(h.base_url=E("ANTHROPIC_BASE_URL")),(e=h.authentication).scope??(e.scope=E("ANTHROPIC_SCOPE")),h.authentication.type==="oidc_federation"){if(!h.authentication.identity_token){let d=E("ANTHROPIC_IDENTITY_TOKEN_FILE");d&&(h.authentication.identity_token={source:"file",path:d})}h.authentication.federation_rule_id||(h.authentication.federation_rule_id=E("ANTHROPIC_FEDERATION_RULE_ID")??""),(t=h.authentication).service_account_id??(t.service_account_id=E("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 Ns();if(!t)return null;let r=e??await Xn();return r?(Kn(r),(await import("path")).join(t,"credentials",`${r}.json`)):null},Ns=async()=>{if(!_i())return null;let s=await import("path"),e=E("ANTHROPIC_CONFIG_DIR");if(e)return e;if(Wt()["X-Stainless-OS"]==="Windows"){let o=E("APPDATA");if(o)return s.join(o,"Anthropic");let a=E("USERPROFILE");return a?s.join(a,"AppData","Roaming","Anthropic"):null}let r=E("XDG_CONFIG_HOME");if(r)return s.join(r,"anthropic");let n=E("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 Ns();if(!s)return null;let e=E("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 Cs(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,A=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:A}),{token:f.access_token,expiresAt:y}}}function $s(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 $s(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 Cs(s.identity_token.path)}let e=E("ANTHROPIC_IDENTITY_TOKEN_FILE");if(e)return Cs(e);let t=E("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(Ts(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=Ts(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
|
+
`):[]}};G=new WeakMap,Y=new WeakMap;me.NEWLINE_CHARS=new Set([`
|
|
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 Ss({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
|
+
`);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 Fs,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 Fs=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(`
|
|
8
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=ki(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function ki(s,e){let t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}async function Cr(s,e){let{response:t,requestLogID:r,retryOfRequestLogID:n,startTime:o}=e,a=await(async()=>{if(e.options.stream)return T(s).debug("response",t.status,t.url,t.headers,t.body),Q.fromSSEResponse(t,e.controller);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let l=t.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;let f=await t.json();return zt(f,t)}return await t.text()})();return T(s).debug(`[${r}] response parsed`,he({retryOfRequestLogID:n,url:t.url,status:t.status,body:a,durationMs:Date.now()-o})),a}function zt(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var so=new WeakSet;function Ls(s){return typeof s=="object"&&s!==null&&so.has(s)}function no(s){let e=new Set;for(;typeof s=="object"&&s!==null&&!e.has(s);){if(e.add(s),Ls(s)||re(s)||s instanceof ue||s instanceof Ut)return!0;s=s.cause}return!1}function Hs(s,e,t,r){return async(n,o={})=>{if(e.length===0)return s.call(void 0,n,o);let a=o.headers instanceof Headers?o.headers:new Headers(o.headers),c=await Ei(s,e,t,r)({...o,headers:a,url:typeof n=="string"?n:n instanceof URL?n.href:n.url});if(c.bodyUsed||c.body?.locked)throw new _("middleware consumed the response body; use response.clone() to inspect it, or return new Response(body, response) to consume and replace it");return c}}function vi(s,e){let t=new WeakMap;return{options:s,logger:e?T(e):Jn(),parse(r){if(s?.stream&&r.ok)return ro(r,s);let n=t.get(r);return n||(n=ro(r,s),t.set(r,n)),n}}}async function ro(s,e){if(s.bodyUsed||s.body?.locked)throw new _("cannot ctx.parse() a response whose body was already consumed; call ctx.parse() instead of reading the body, or read via response.clone()");if(e?.stream&&s.ok)return Q.fromSSEResponse(s.clone(),new AbortController);if(s.status===204)return null;if(e?.__binaryResponse)return s;let r=s.headers.get("content-type")?.split(";")[0]?.trim();return r?.includes("application/json")||r?.endsWith("+json")?s.headers.get("content-length")==="0"?void 0:zt(await s.clone().json(),s):await s.clone().text()}function Ei(s,e,t,r){let n=async({url:a,...c})=>{try{return await s.call(void 0,a,c)}catch(l){let h=Fe(l);throw so.add(h),h}},o=vi(t,r);for(let a=e.length-1;a>=0;a--){let c=e[a],l=n;n=async h=>c(h,l,o)}return n}var Xt,He=class s extends Promise{constructor(e,t,r=Cr){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=r,Xt.set(this,void 0),g(this,Xt,e,"f")}_thenUnwrap(e){return new s(i(this,Xt,"f"),this.responsePromise,async(t,r)=>zt(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(i(this,Xt,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Xt=new WeakMap;var $r,Fr=class{constructor(e,t,r,n){$r.set(this,void 0),g(this,$r,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new _("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await i(this,$r,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[($r=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Gt=class extends He{constructor(e,t,r){super(e,t,async(n,o)=>new r(n,o.response,await Cr(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},ne=class extends Fr{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let t=this.first_id;return t?{...this.options,query:{...xr(this.options.query),before_id:t}}:null}let e=this.last_id;return e?{...this.options,query:{...xr(this.options.query),after_id:e}}:null}};var v=class extends Fr{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.next_page=r.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...xr(this.options.query),page:e}}:null}};var Ds=()=>{if(typeof File>"u"){let{process:s}=globalThis,e=typeof s?.versions?.node=="string"&&parseInt(s.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Be(s,e,t){return Ds(),new File(s,e??"unknown_file",t)}function Yt(s,e){let t=typeof s=="object"&&s!==null&&("name"in s&&s.name&&String(s.name)||"url"in s&&s.url&&String(s.url)||"filename"in s&&s.filename&&String(s.filename)||"path"in s&&s.path&&String(s.path))||"";return e?t.split(/[\\/]/).pop()||void 0:t}var Us=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function";var dt=async(s,e,t=!0)=>({...s,body:await Ii(s.body,e,t)}),oo=new WeakMap;function Ri(s){let e=typeof s=="function"?s:s.fetch,t=oo.get(e);if(t)return t;let r=(async()=>{try{let n="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new n(o).text()}catch{return!0}})();return oo.set(e,r),r}var Ii=async(s,e,t=!0)=>{if(!await Ri(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(s||{}).map(([n,o])=>Bs(r,n,o,t))),r},Pi=s=>s instanceof Blob&&"name"in s;var Bs=async(s,e,t,r)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")s.append(e,String(t));else if(t instanceof Response){let n={},o=t.headers.get("Content-Type");o&&(n={type:o}),s.append(e,Be([await t.blob()],Yt(t,r),n))}else if(Us(t))s.append(e,Be([await new Response(Sr(t)).blob()],Yt(t,r)));else if(Pi(t))s.append(e,Be([t],Yt(t,r),{type:t.type}));else if(Array.isArray(t))await Promise.all(t.map(n=>Bs(s,e+"[]",n,r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,o])=>Bs(s,`${e}[${n}]`,o,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var io=s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function",Ti=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&io(s),Oi=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function Lr(s,e,t){if(Ds(),s=await s,e||(e=Yt(s,!0)),Ti(s))return s instanceof File&&e==null&&t==null?s:Be([await s.arrayBuffer()],e??s.name,{type:s.type,lastModified:s.lastModified,...t});if(Oi(s)){let n=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),Be(await js(n),e,t)}let r=await js(s);if(!t?.type){let n=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(t={...t,type:n})}return Be(r,e,t)}async function js(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(io(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(Us(s))for await(let t of s)e.push(...await js(t));else{let t=s?.constructor?.name;throw new Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${Mi(s)}`)}return e}function Mi(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}var x=class{constructor(e){this._client=e}};var ao=Symbol.for("brand.privateNullableHeaders");function*Ci(s){if(!s)return;if(ao in s){let{values:r,nulls:n}=s;yield*r.entries();for(let o of n)yield[o,null];return}let e=!1,t;s instanceof Headers?t=s.entries():ws(s)?t=s:(e=!0,t=Object.entries(s??{}));for(let r of t){let n=r[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let o=ws(r[1])?r[1]:[r[1]],a=!1;for(let c of o)c!==void 0&&(e&&!a&&(a=!0,yield[n,null]),yield[n,c])}}var u=s=>{let e=new Headers,t=new Set;for(let r of s){let n=new Set;for(let[o,a]of Ci(r)){let c=o.toLowerCase();n.has(c)||(e.delete(o),n.add(c)),a===null?(e.delete(o),t.add(c)):(e.append(o,a),t.delete(c))}}return{[ao]:!0,values:e,nulls:t}};function lo(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var co=Object.freeze(Object.create(null)),$i=(s=lo)=>function(t,...r){if(t.length===1)return t[0];let n=!1,o=[],a=t.reduce((b,d,f)=>{/[?#]/.test(d)&&(n=!0);let p=r[f],y=(n?encodeURIComponent:s)(""+p);return f!==r.length&&(p==null||typeof p=="object"&&p.toString===Object.getPrototypeOf(Object.getPrototypeOf(p.hasOwnProperty??co)??co)?.toString)&&(y=p+"",o.push({start:b.length+d.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(p).slice(8,-1)} is not a valid path parameter`})),b+d+(f===r.length?"":y)},""),c=a.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,h;for(;(h=l.exec(c))!==null;)o.push({start:h.index,length:h[0].length,error:`Value "${h[0]}" can't be safely passed as a path parameter`});if(o.sort((b,d)=>b.start-d.start),o.length>0){let b=0,d=o.reduce((f,p)=>{let y=" ".repeat(p.start-b),A="^".repeat(p.length);return b=p.start+p.length,f+y+A},"");throw new _(`Path parameters result in path with invalid segments:
|
|
9
|
+
${o.map(f=>f.error).join(`
|
|
10
|
+
`)}
|
|
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",v,{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",v,{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 Ws(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=Ws(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",v,{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`,v,{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",v,{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 Wr(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,qr,oe,Jr,Kr,Vr,er,tr,xt,Qi=999,Zi=1e3,ea=6e4,Ee=class{constructor(e){wt.set(this,void 0),qr.set(this,!1),oe.set(this,void 0),Jr.set(this,void 0),Kr.set(this,void 0),Vr.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,Wr(e.client,{authToken:e.environmentKey,helper:"environments-work-poller"}),"f"),g(this,Kr,e.autoStop??!0,"f"),g(this,Vr,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,Jr,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,qr=new WeakMap,oe=new WeakMap,Jr=new WeakMap,Kr=new WeakMap,Vr=new WeakMap,er=new WeakMap,tr=new WeakMap,xt=new WeakMap,Symbol.asyncIterator)](){if(i(this,qr,"f"))throw new _("Cannot iterate over a consumed WorkPoller");g(this,qr,!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,Vr,"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,Kr,"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,Jr,"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,zr=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,Xr,q,Gr,sr,Qr,K,vt,fe,je,ge,nr,Et,Yr,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),Xr.set(this,!1),q.set(this,void 0),Gr.set(this,void 0),sr.set(this,void 0),Qr.set(this,void 0),K.set(this,void 0),vt.set(this,new Set),fe.set(this,new Set),je.set(this,new zr),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,Qr,new Map(t.tools.map(r=>[Vs(r),r])),"f"),g(this,q,new AbortController,"f"),g(this,Gr,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*[(Xr=new WeakMap,q=new WeakMap,Gr=new WeakMap,sr=new WeakMap,Qr=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,Xr,"f"))throw new _("Cannot iterate over a consumed SessionToolRunner");g(this,Xr,!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,Gr,"f").call(this)}}};Yr=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",Yr).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",Yr).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,Qr,"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",Yr).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 Zr,or,Gs,Fo=3e4,da="NO_HEARTBEAT",At=class{constructor(e){Zr.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,Zr,"m",Gs).call(this,a,r,o.signal)}async handleItem(e){let t=e?.workId??E("ANTHROPIC_WORK_ID"),r=e?.environmentId??E("ANTHROPIC_ENVIRONMENT_ID"),n=e?.sessionId??E("ANTHROPIC_SESSION_ID"),o=e?.environmentKey??this.environmentKey??E("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,Zr,"m",Gs).call(this,a,o,e?.signal??i(this,or,"f"))}};or=new WeakMap,Zr=new WeakSet,Gs=async function(e,t,r){let n=T(this.client),o=Wr(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-OES65R33.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 A 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`,v,{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",v,{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`,v,{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`,v,{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",v,{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 es={"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},ts=s=>JSON.parse(ka(Sa(Ot(xa(s)))));var ie,Te,Mt,ir,rs,ar,cr,ss,lr,_e,ur,ns,os,qe,is,as,dr,Zs,Ho,cs,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 ls=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),rs.set(this,()=>{}),ar.set(this,()=>{}),cr.set(this,void 0),ss.set(this,()=>{}),lr.set(this,()=>{}),_e.set(this,{}),ur.set(this,!1),ns.set(this,!1),os.set(this,!1),qe.set(this,!1),is.set(this,void 0),as.set(this,void 0),dr.set(this,void 0),cs.set(this,r=>{if(g(this,ns,!0,"f"),re(r)&&(r=new W),r instanceof W)return g(this,os,!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,rs,r,"f"),g(this,ar,n,"f")}),"f"),g(this,cr,new Promise((r,n)=>{g(this,ss,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,is,"f")}get request_id(){return i(this,as,"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,cs,"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,is,e,"f"),g(this,as,e?.headers.get("request-id"),"f"),i(this,rs,"f").call(this,e),this._emit("connect"))}get ended(){return i(this,ur,"f")}get errored(){return i(this,ns,"f")}get aborted(){return i(this,os,"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,ss,"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,rs=new WeakMap,ar=new WeakMap,cr=new WeakMap,ss=new WeakMap,lr=new WeakMap,_e=new WeakMap,ur=new WeakMap,ns=new WeakMap,os=new WeakMap,qe=new WeakMap,is=new WeakMap,as=new WeakMap,dr=new WeakMap,cs=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=ts(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,cs,"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
|
+
1. Task Overview
|
|
14
|
+
The user's core request and success criteria
|
|
15
|
+
Any clarifications or constraints they specified
|
|
16
|
+
2. Current State
|
|
17
|
+
What has been completed so far
|
|
18
|
+
Files created, modified, or analyzed (with paths if relevant)
|
|
19
|
+
Key outputs or artifacts produced
|
|
20
|
+
3. Important Discoveries
|
|
21
|
+
Technical constraints or requirements uncovered
|
|
22
|
+
Decisions made and their rationale
|
|
23
|
+
Errors encountered and how they were resolved
|
|
24
|
+
What approaches were tried that didn't work (and why)
|
|
25
|
+
4. Next Steps
|
|
26
|
+
Specific actions needed to complete the task
|
|
27
|
+
Any blockers or open questions to resolve
|
|
28
|
+
Priority order if multiple steps remain
|
|
29
|
+
5. Context to Preserve
|
|
30
|
+
User preferences or style requirements
|
|
31
|
+
Domain-specific details that aren't obvious
|
|
32
|
+
Any promises made to the user
|
|
33
|
+
Be concise but complete\u2014err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
|
|
34
|
+
Wrap your summary in <summary></summary> tags.`;var hr,Nt,Je,j,X,ee,be,Oe,fr,Wo,sn,Ct=class{constructor(e,t,r){hr.add(this),this.client=e,Nt.set(this,!1),Je.set(this,!1),j.set(this,void 0),X.set(this,void 0),ee.set(this,void 0),be.set(this,void 0),Oe.set(this,void 0),fr.set(this,0),g(this,j,{params:{...t,messages:structuredClone(t.messages)}},"f");let o=["BetaToolRunner",...Ws(t.tools,t.messages)].join(", ");g(this,X,{...r,headers:u([{"x-stainless-helper":o},r?.headers])},"f"),g(this,Oe,ys(),"f"),t.compactionControl?.enabled&&console.warn('Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction')}async*[(Nt=new WeakMap,Je=new WeakMap,j=new WeakMap,X=new WeakMap,ee=new WeakMap,be=new WeakMap,Oe=new WeakMap,fr=new WeakMap,hr=new WeakSet,Wo=async function(){let t=i(this,j,"f").params.compactionControl;if(!t||!t.enabled)return!1;let r=0;if(i(this,ee,"f")!==void 0)try{let h=await i(this,ee,"f");r=h.usage.input_tokens+(h.usage.cache_creation_input_tokens??0)+(h.usage.cache_read_input_tokens??0)+h.usage.output_tokens}catch{return!1}let n=t.contextTokenThreshold??1e5;if(r<n)return!1;let o=t.model??i(this,j,"f").params.model,a=t.summaryPrompt??jo,c=i(this,j,"f").params.messages;if(c[c.length-1].role==="assistant"){let h=c[c.length-1];if(Array.isArray(h.content)){let b=h.content.filter(d=>d.type!=="tool_use");b.length===0?c.pop():h.content=b}}let l=await this.client.beta.messages.create({model:o,messages:[...c,{role:"user",content:[{type:"text",text:a}]}],max_tokens:i(this,j,"f").params.max_tokens},{signal:i(this,X,"f").signal,headers:u([i(this,X,"f").headers,{"x-stainless-helper":"compaction"}])});if(l.content[0]?.type!=="text")throw new _("Expected text response for compaction");return i(this,j,"f").params.messages=[{role:"user",content:l.content}],!0},Symbol.asyncIterator)](){var e;if(i(this,Nt,"f"))throw new _("Cannot iterate over a consumed stream");g(this,Nt,!0,"f"),g(this,Je,!0,"f"),g(this,be,void 0,"f");try{for(;;){let t;try{if(i(this,j,"f").params.max_iterations&&i(this,fr,"f")>=i(this,j,"f").params.max_iterations)break;g(this,Je,!1,"f"),g(this,be,void 0,"f"),g(this,fr,(e=i(this,fr,"f"),e++,e),"f"),g(this,ee,void 0,"f");let{max_iterations:r,compactionControl:n,...o}=i(this,j,"f").params;if(o.stream?(t=this.client.beta.messages.stream({...o},i(this,X,"f")),g(this,ee,t.finalMessage(),"f"),i(this,ee,"f").catch(()=>{}),yield t):(g(this,ee,this.client.beta.messages.create({...o,stream:!1},i(this,X,"f")),"f"),yield i(this,ee,"f")),!await i(this,hr,"m",Wo).call(this)){if(!i(this,Je,"f")){let l=await i(this,ee,"f");if(i(this,j,"f").params.messages.push({role:l.role,content:l.content}),l.stop_reason==="refusal")break}let c=await i(this,hr,"m",sn).call(this,i(this,j,"f").params.messages.at(-1));if(c)i(this,j,"f").params.messages.push(c);else if(!i(this,Je,"f"))break}}finally{t&&t.abort()}}if(!i(this,ee,"f"))throw new _("ToolRunner concluded without a message from the server");i(this,Oe,"f").resolve(await i(this,ee,"f"))}catch(t){throw g(this,Nt,!1,"f"),i(this,Oe,"f").promise.catch(()=>{}),i(this,Oe,"f").reject(t),g(this,Oe,ys(),"f"),t}}setMessagesParams(e){typeof e=="function"?i(this,j,"f").params=e(i(this,j,"f").params):i(this,j,"f").params=e,g(this,Je,!0,"f"),g(this,be,void 0,"f")}setRequestOptions(e){typeof e=="function"?g(this,X,e(i(this,X,"f")),"f"):g(this,X,{...i(this,X,"f"),...e},"f")}async generateToolResponse(e=i(this,X,"f").signal){let t=await i(this,ee,"f")??this.params.messages.at(-1);return t?i(this,hr,"m",sn).call(this,t,e):null}done(){return i(this,Oe,"f").promise}async runUntilDone(){if(!i(this,Nt,"f"))for await(let e of this);return this.done()}get params(){return i(this,j,"f").params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}};sn=async function(e,t=i(this,X,"f").signal){return i(this,be,"f")!==void 0?i(this,be,"f"):(g(this,be,Ea(i(this,j,"f").params,e,{...i(this,X,"f"),signal:t}),"f"),i(this,be,"f"))};async function Ea(s,e=s.messages.at(-1),t){if(!e||e.role!=="assistant"||!e.content||typeof e.content=="string")return null;let r=e.content.filter(o=>o.type==="tool_use");return r.length===0?null:{role:"user",content:await Promise.all(r.map(async o=>{let a=s.tools.find(c=>("name"in c?c.name:c.mcp_server_name)===o.name);if(!a||!("run"in a))return{type:"tool_result",tool_use_id:o.id,content:`Error: Tool '${o.name}' not found`,is_error:!0};try{let c=o.input;"parse"in a&&a.parse&&(c=a.parse(c));let l=await a.run(c,{toolUse:o,toolUseBlock:o,signal:t?.signal});return{type:"tool_result",tool_use_id:o.id,content:l}}catch(c){return{type:"tool_result",tool_use_id:o.id,content:c instanceof pe?c.content:`Error: ${c instanceof Error?c.message:String(c)}`,is_error:!0}}}))}}var qo={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026","claude-3-5-haiku-latest":"February 19th, 2026","claude-3-5-haiku-20241022":"February 19th, 2026","claude-opus-4-0":"June 15th, 2026","claude-opus-4-20250514":"June 15th, 2026","claude-sonnet-4-0":"June 15th, 2026","claude-sonnet-4-20250514":"June 15th, 2026","claude-opus-4-1":"August 5th, 2026","claude-opus-4-1-20250805":"August 5th, 2026","claude-mythos-preview":"June 30th, 2026"},Aa=["claude-mythos-preview","claude-opus-4-6"],ye=class extends x{constructor(){super(...arguments),this.batches=new Tt(this._client)}create(e,t){let r=Jo(e),{betas:n,...o}=r;o.model in qo&&console.warn(`The model '${o.model}' is deprecated and will reach end-of-life on ${qo[o.model]}
|
|
35
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),Aa.includes(o.model)&&o.thinking&&o.thinking.type==="enabled"&&console.warn(`Using Claude with ${o.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let a=this._client._options.timeout;if(!o.stream&&a==null){let l=es[o.model]??void 0;a=this._client.calculateNonstreamingTimeout(o.max_tokens,l)}let c=Br(o.tools,o.messages);return this._client.post("/v1/messages?beta=true",{body:o,timeout:a??6e5,...t,headers:u([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},c,t?.headers]),stream:r.stream??!1})}parse(e,t){return t={...t,headers:u([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},t?.headers])},this.create(e,t).then(r=>Qs(r,e,{logger:this._client.logger??console}))}stream(e,t){return ls.createMessage(this,e,t)}countTokens(e,t){let r=Jo(e),{betas:n,...o}=r;return this._client.post("/v1/messages/count_tokens?beta=true",{body:o,...t,headers:u([{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString()},t?.headers])})}toolRunner(e,t){return new Ct(this._client,e,t)}};function Jo(s){if(!s.output_format)return s;if(s.output_config?.format)throw new _("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:e,...t}=s;return{...t,output_config:{...s.output_config,format:e}}}ye.Batches=Tt;ye.BetaToolRunner=Ct;ye.ToolError=pe;var Ke=class extends x{list(e,t={},r){let{betas:n,...o}=t??{};return this._client.getAPIList(m`/v1/sessions/${e}/events?beta=true`,v,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}send(e,t,r){let{betas:n,...o}=t;return this._client.post(m`/v1/sessions/${e}/events?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}stream(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/sessions/${e}/events/stream?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers]),stream:!0})}toolRunner(e,t){return new Re(e,{...t,client:this._client})}};Ke.SessionToolRunner=Re;var $t=class extends x{retrieve(e,t,r){let{session_id:n,betas:o}=t;return this._client.get(m`/v1/sessions/${n}/resources/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{session_id:n,betas:o,...a}=t;return this._client.post(m`/v1/sessions/${n}/resources/${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/sessions/${e}/resources?beta=true`,v,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,t,r){let{session_id:n,betas:o}=t;return this._client.delete(m`/v1/sessions/${n}/resources/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}add(e,t,r){let{betas:n,...o}=t;return this._client.post(m`/v1/sessions/${e}/resources?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};var Ft=class extends x{list(e,t,r){let{session_id:n,betas:o,...a}=t;return this._client.getAPIList(m`/v1/sessions/${n}/threads/${e}/events?beta=true`,v,{query:a,...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}stream(e,t,r){let{session_id:n,betas:o}=t;return this._client.get(m`/v1/sessions/${n}/threads/${e}/stream?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers]),stream:!0})}};var Ve=class extends x{constructor(){super(...arguments),this.events=new Ft(this._client)}retrieve(e,t,r){let{session_id:n,betas:o}=t;return this._client.get(m`/v1/sessions/${n}/threads/${e}?beta=true`,{...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/sessions/${e}/threads?beta=true`,v,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t,r){let{session_id:n,betas:o}=t;return this._client.post(m`/v1/sessions/${n}/threads/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};Ve.Events=Ft;var we=class extends x{constructor(){super(...arguments),this.events=new Ke(this._client),this.resources=new $t(this._client),this.threads=new Ve(this._client)}create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/sessions?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/sessions/${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/sessions/${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/sessions?beta=true",v,{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/sessions/${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/sessions/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};we.Events=Ke;we.Resources=$t;we.Threads=Ve;var Lt=class extends x{create(e,t={},r){let{betas:n,...o}=t??{};return this._client.post(m`/v1/skills/${e}/versions?beta=true`,dt({body:o,...r,headers:u([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},r?.headers])},this._client,!1))}retrieve(e,t,r){let{skill_id:n,betas:o}=t;return this._client.get(m`/v1/skills/${n}/versions/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},r?.headers])})}list(e,t={},r){let{betas:n,...o}=t??{};return this._client.getAPIList(m`/v1/skills/${e}/versions?beta=true`,v,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},r?.headers])})}delete(e,t,r){let{skill_id:n,betas:o}=t;return this._client.delete(m`/v1/skills/${n}/versions/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},r?.headers])})}download(e,t,r){let{skill_id:n,betas:o}=t;return this._client.get(m`/v1/skills/${n}/versions/${e}/content?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString(),Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}};var ze=class extends x{constructor(){super(...arguments),this.versions=new Lt(this._client)}create(e={},t){let{betas:r,...n}=e??{};return this._client.post("/v1/skills?beta=true",dt({body:n,...t,headers:u([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},t?.headers])},this._client,!1))}retrieve(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/skills/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},r?.headers])})}list(e={},t){let{betas:r,...n}=e??{};return this._client.getAPIList("/v1/skills?beta=true",v,{query:n,...t,headers:u([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},t?.headers])})}delete(e,t={},r){let{betas:n}=t??{};return this._client.delete(m`/v1/skills/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},r?.headers])})}};ze.Versions=Lt;var Ht=class extends x{create(e,t,r){let{betas:n,...o}=t;return this._client.post(m`/v1/vaults/${e}/credentials?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,t,r){let{vault_id:n,betas:o}=t;return this._client.get(m`/v1/vaults/${n}/credentials/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{vault_id:n,betas:o,...a}=t;return this._client.post(m`/v1/vaults/${n}/credentials/${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/vaults/${e}/credentials?beta=true`,v,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,t,r){let{vault_id:n,betas:o}=t;return this._client.delete(m`/v1/vaults/${n}/credentials/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t,r){let{vault_id:n,betas:o}=t;return this._client.post(m`/v1/vaults/${n}/credentials/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}mcpOAuthValidate(e,t,r){let{vault_id:n,betas:o}=t;return this._client.post(m`/v1/vaults/${n}/credentials/${e}/mcp_oauth_validate?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};var Xe=class extends x{constructor(){super(...arguments),this.credentials=new Ht(this._client)}create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/vaults?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/vaults/${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/vaults/${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/vaults?beta=true",v,{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/vaults/${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/vaults/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};Xe.Credentials=Ht;var B=class extends x{constructor(){super(...arguments),this.models=new mt(this._client),this.messages=new ye(this._client),this.agents=new De(this._client),this.environments=new We(this._client),this.sessions=new we(this._client),this.deployments=new ft(this._client),this.deploymentRuns=new ht(this._client),this.vaults=new Xe(this._client),this.memoryStores=new Pe(this._client),this.files=new pt(this._client),this.skills=new ze(this._client),this.webhooks=new bt(this._client),this.userProfiles=new gt(this._client)}};B.Models=mt;B.Messages=ye;B.Agents=De;B.Environments=We;B.Sessions=we;B.Deployments=ft;B.DeploymentRuns=ht;B.Vaults=Xe;B.MemoryStores=Pe;B.Files=pt;B.Skills=ze;B.Webhooks=bt;B.UserProfiles=gt;var Ge=class extends x{create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/complete",{body:n,timeout:this._client._options.timeout??6e5,...t,headers:u([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}};function Ko(s){return s?.output_config?.format}function nn(s,e,t){let r=Ko(e);return!e||!("parse"in(r??{}))?{...s,content:s.content.map(n=>n.type==="text"?Object.defineProperty({...n},"parsed_output",{value:null,enumerable:!1}):n),parsed_output:null}:on(s,e,t)}function on(s,e,t){let r=null,n=s.content.map(o=>{if(o.type==="text"){let a=La(e,o.text);return r===null&&(r=a),Object.defineProperty({...o},"parsed_output",{value:a,enumerable:!1})}return o});return{...s,content:n,parsed_output:r}}function La(s,e){let t=Ko(s);if(t?.type!=="json_schema")return null;try{return"parse"in t?t.parse(e):JSON.parse(e)}catch(r){throw new _(`Failed to parse structured output: ${r}`)}}var ae,Me,Bt,pr,us,mr,gr,ds,_r,xe,br,hs,fs,Ye,ps,ms,yr,an,Vo,cn,ln,un,dn,zo,Xo="__json_buf";function Go(s){return s.type==="tool_use"||s.type==="server_tool_use"}var gs=class s{constructor(e,t){ae.add(this),this.messages=[],this.receivedMessages=[],Me.set(this,void 0),Bt.set(this,null),this.controller=new AbortController,pr.set(this,void 0),us.set(this,()=>{}),mr.set(this,()=>{}),gr.set(this,void 0),ds.set(this,()=>{}),_r.set(this,()=>{}),xe.set(this,{}),br.set(this,!1),hs.set(this,!1),fs.set(this,!1),Ye.set(this,!1),ps.set(this,void 0),ms.set(this,void 0),yr.set(this,void 0),cn.set(this,r=>{if(g(this,hs,!0,"f"),re(r)&&(r=new W),r instanceof W)return g(this,fs,!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,pr,new Promise((r,n)=>{g(this,us,r,"f"),g(this,mr,n,"f")}),"f"),g(this,gr,new Promise((r,n)=>{g(this,ds,r,"f"),g(this,_r,n,"f")}),"f"),i(this,pr,"f").catch(()=>{}),i(this,gr,"f").catch(()=>{}),g(this,Bt,e,"f"),g(this,yr,t?.logger??console,"f")}get response(){return i(this,ps,"f")}get request_id(){return i(this,ms,"f")}async withResponse(){g(this,Ye,!0,"f");let e=await i(this,pr,"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,Bt,{...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,cn,"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,ae,"m",ln).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,ae,"m",un).call(this,l);if(c.controller.signal?.aborted)throw new W;i(this,ae,"m",dn).call(this)}finally{n&&o&&n.removeEventListener("abort",o)}}_connected(e){this.ended||(g(this,ps,e,"f"),g(this,ms,e?.headers.get("request-id"),"f"),i(this,us,"f").call(this,e),this._emit("connect"))}get ended(){return i(this,br,"f")}get errored(){return i(this,hs,"f")}get aborted(){return i(this,fs,"f")}abort(){this.controller.abort()}on(e,t){return(i(this,xe,"f")[e]||(i(this,xe,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=i(this,xe,"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,xe,"f")[e]||(i(this,xe,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{g(this,Ye,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){g(this,Ye,!0,"f"),await i(this,gr,"f")}get currentMessage(){return i(this,Me,"f")}async finalMessage(){return await this.done(),i(this,ae,"m",an).call(this)}async finalText(){return await this.done(),i(this,ae,"m",Vo).call(this)}_emit(e,...t){if(i(this,br,"f"))return;e==="end"&&(g(this,br,!0,"f"),i(this,ds,"f").call(this));let r=i(this,xe,"f")[e];if(r&&(i(this,xe,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!i(this,Ye,"f")&&!r?.length&&Promise.reject(n),i(this,mr,"f").call(this,n),i(this,_r,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!i(this,Ye,"f")&&!r?.length&&Promise.reject(n),i(this,mr,"f").call(this,n),i(this,_r,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",i(this,ae,"m",an).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,ae,"m",ln).call(this),this._connected(null);let o=Q.fromReadableStream(e,this.controller);for await(let a of o)i(this,ae,"m",un).call(this,a);if(o.controller.signal?.aborted)throw new W;i(this,ae,"m",dn).call(this)}finally{r&&n&&r.removeEventListener("abort",n)}}[(Me=new WeakMap,Bt=new WeakMap,pr=new WeakMap,us=new WeakMap,mr=new WeakMap,gr=new WeakMap,ds=new WeakMap,_r=new WeakMap,xe=new WeakMap,br=new WeakMap,hs=new WeakMap,fs=new WeakMap,Ye=new WeakMap,ps=new WeakMap,ms=new WeakMap,yr=new WeakMap,cn=new WeakMap,ae=new WeakSet,an=function(){if(this.receivedMessages.length===0)throw new _("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Vo=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(" ")},ln=function(){this.ended||g(this,Me,void 0,"f")},un=function(t){if(this.ended)return;let r=i(this,ae,"m",zo).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":{Go(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}default:t.delta}break}case"message_stop":{this._addMessageParam(r),this._addMessage(nn(r,i(this,Bt,"f"),{logger:i(this,yr,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{g(this,Me,r,"f");break}case"content_block_start":case"message_delta":break}},dn=function(){if(this.ended)throw new _("stream has ended, this shouldn't happen");let t=i(this,Me,"f");if(!t)throw new _("request ended without sending any chunks");return g(this,Me,void 0,"f"),nn(t,i(this,Bt,"f"),{logger:i(this,yr,"f")})},zo=function(t){let r=i(this,Me,"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.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,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),r;case"content_block_start":return r.content.push({...t.content_block}),r;case"content_block_delta":{let n=r.content.at(t.index);switch(t.delta.type){case"text_delta":{n?.type==="text"&&(r.content[t.index]={...n,text:(n.text||"")+t.delta.text});break}case"citations_delta":{n?.type==="text"&&(r.content[t.index]={...n,citations:[...n.citations??[],t.delta.citation]});break}case"input_json_delta":{if(n&&Go(n)){let o=n[Xo]||"";o+=t.delta.partial_json;let a={...n};Object.defineProperty(a,Xo,{value:o,enumerable:!1,writable:!0}),o&&(a.input=ts(o)),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}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 Dt=class extends x{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(m`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",ne,{query:e,...t})}delete(e,t){return this._client.delete(m`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(m`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let r=await this.retrieve(e);if(!r.results_url)throw new _(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...t,headers:u([{Accept:"application/binary"},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((n,o)=>Pt.fromResponse(o.response,o.controller))}};var Ne=class extends x{constructor(){super(...arguments),this.batches=new Dt(this._client)}create(e,t){e.model in Yo&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Yo[e.model]}
|
|
36
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),Ba.includes(e.model)&&e.thinking&&e.thinking.type==="enabled"&&console.warn(`Using Claude with ${e.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let r=this._client._options.timeout;if(!e.stream&&r==null){let o=es[e.model]??void 0;r=this._client.calculateNonstreamingTimeout(e.max_tokens,o)}let n=Br(e.tools,e.messages);return this._client.post("/v1/messages",{body:e,timeout:r??6e5,...t,headers:u([n,t?.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then(r=>on(r,e,{logger:this._client.logger??console}))}stream(e,t){return gs.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}},Yo={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026","claude-3-5-haiku-latest":"February 19th, 2026","claude-3-5-haiku-20241022":"February 19th, 2026","claude-opus-4-0":"June 15th, 2026","claude-opus-4-20250514":"June 15th, 2026","claude-sonnet-4-0":"June 15th, 2026","claude-sonnet-4-20250514":"June 15th, 2026","claude-opus-4-1":"August 5th, 2026","claude-opus-4-1-20250805":"August 5th, 2026","claude-mythos-preview":"June 30th, 2026"},Ba=["claude-mythos-preview","claude-opus-4-6"];Ne.Batches=Dt;var Qe=class extends x{retrieve(e,t={},r){let{betas:n}=t??{};return this._client.get(m`/v1/models/${e}`,{...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",ne,{query:n,...t,headers:u([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}};var hn,fn,_s,Qo,Zo="\\n\\nHuman:",ei="\\n\\nAssistant:",C=class{get credentials(){return this._authState.provider}constructor({baseURL:e=E("ANTHROPIC_BASE_URL"),apiKey:t,authToken:r,webhookKey:n=E("ANTHROPIC_WEBHOOK_SIGNING_KEY")??null,...o}={}){if(hn.add(this),this._requestAuthFlags=new WeakMap,_s.set(this,void 0),t===void 0&&(t=o.profile!=null?null:E("ANTHROPIC_API_KEY")??null),r===void 0&&(r=o.profile!=null?null:E("ANTHROPIC_AUTH_TOKEN")??null),o.profile!=null&&(o.credentials!=null||o.config!=null))throw new TypeError("Pass at most one of `profile`, `credentials`, or `config`.");let a={apiKey:t,authToken:r,webhookKey:n,...o,baseURL:e||"https://api.anthropic.com"};if(!a.dangerouslyAllowBrowser&&xn())throw new _(`It looks like you're running in a browser-like environment.
|
|
37
|
+
|
|
38
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
39
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
40
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
41
|
+
|
|
42
|
+
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
43
|
+
`);this.baseURL=a.baseURL,this._baseURLIsExplicit=o.__baseURLIsExplicit??!!e,this.timeout=a.timeout??fn.DEFAULT_TIMEOUT,this.logger=a.logger??console,this.logLevel=Kt,this.logLevel=Mr(a.logLevel,"ClientOptions.logLevel",T(this))??Mr(E("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",T(this))??Kt,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??Sn(),g(this,_s,vn,"f"),this.middleware=[...a.middleware??[]];let c=E("ANTHROPIC_CUSTOM_HEADERS");if(c){let h={};for(let b of c.split(`
|
|
44
|
+
`)){let d=b.indexOf(":");d>=0&&(h[b.substring(0,d).trim()]=b.substring(d+1).trim())}a.defaultHeaders={...h,...a.defaultHeaders}}let l=o.__auth;if(delete a.__auth,delete a.__baseURLIsExplicit,this._options=a,this.apiKey=typeof t=="string"?t:null,this.authToken=r,this.webhookKey=n,l)this._authState=l,!this._baseURLIsExplicit&&l.baseURL&&(this.baseURL=l.baseURL);else if(this._authState={provider:null,tokenCache:null,resolution:null,error:null,extraHeaders:{}},this.apiKey==null&&this.authToken==null){let h=a.credentials??null;if(h)this._authState.provider=h,this._authState.tokenCache=this._makeTokenCache(h);else if(a.config!=null){let b=$s(a.config,this._credentialResolverOptions());this._authState.provider=b.provider,this._authState.tokenCache=this._makeTokenCache(b.provider),this._authState.extraHeaders=b.extraHeaders,this._applyCredentialBaseURL(b.baseURL)}else a.profile!=null?this._authState.resolution=this._resolveDefaultCredentials(a.profile):this._authState.resolution=this._resolveDefaultCredentials()}}_applyCredentialBaseURL(e){if(!e)return;let t=e.replace(/\/+$/,"");this._authState.baseURL=t,this._baseURLIsExplicit||(this.baseURL=t)}_credentialResolverOptions(){return{baseURL:this.baseURL,fetch:this._credentialsFetch(),userAgent:this.getUserAgent(),onCacheWriteError:e=>{T(this).debug("credential cache write failed (best-effort)",e)},onSafetyWarning:e=>{T(this).warn(e)}}}_credentialsFetch(){return Hs(this.fetch,this.middleware,void 0,this)}_makeTokenCache(e){return new Pr(e,t=>{T(this).debug("advisory token refresh failed; serving cached token",t)})}withOptions(e){let t="credentials"in e||"config"in e||"profile"in e,r="apiKey"in e||"authToken"in e||t,n={...this._options,...this._baseURLIsExplicit?{baseURL:this.baseURL}:{},maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,middleware:this.middleware,apiKey:this.apiKey,authToken:this.authToken,webhookKey:this.webhookKey,credentials:this.credentials,...t?{credentials:void 0,config:void 0,profile:void 0}:{},...e,__auth:r?void 0:this._authState,__baseURLIsExplicit:"baseURL"in e?!0:this._baseURLIsExplicit};return new this.constructor(n)}async _resolveDefaultCredentials(e){try{let t=await Zn(this._credentialResolverOptions(),e);if(t)this._authState.provider=t.provider,this._authState.tokenCache=this._makeTokenCache(t.provider),this._authState.extraHeaders=t.extraHeaders,this._applyCredentialBaseURL(t.baseURL);else if(e!=null)throw new _(`Profile "${e}" could not be resolved (no <config_dir>/configs/${e}.json found).`)}catch(t){this._authState.error=t}finally{this._authState.resolution=null}}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.get("x-api-key")||e.get("authorization"))){if(this._authState.error)throw this._authState.error;if(!(this._authState.tokenCache||this._authState.resolution)&&!(this.apiKey&&e.get("x-api-key"))&&!t.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!t.has("authorization"))throw new Error('Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}}_authFlags(e){let t=this._requestAuthFlags.get(e);return t||(t={usedTokenCache:!1,didRefreshFor401:!1},this._requestAuthFlags.set(e,t)),t}async authHeaders(e){if(this._authState.resolution&&await this._authState.resolution,!this._authState.error){if(this._authState.tokenCache&&this.apiKey==null){let t=await this._authState.tokenCache.getToken();return this._authFlags(e).usedTokenCache=!0,u([{Authorization:`Bearer ${t}`}])}return u([await this.apiKeyAuth(e),await this.bearerAuth(e)])}}async apiKeyAuth(e){if(this.apiKey!=null)return u([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return u([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Nn(e)}getUserAgent(){return`${this.constructor.name}/JS ${se}`}defaultIdempotencyKey(){return`stainless-node-retry-${ct()}`}makeStatusError(e,t,r,n){return F.generate(e,t,r,n)}buildURL(e,t,r){let n=!i(this,hn,"m",Qo).call(this)&&r||this.baseURL,o=mn(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),c=Object.fromEntries(o.searchParams);return(!xs(a)||!xs(c))&&(t={...c,...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new _("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){if(this._authState.tokenCache&&this.apiKey==null){let n=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[a,c]of Object.entries(this._authState.extraHeaders))n.has(a)||n.set(a,c);n.get("anthropic-beta")?.split(",").map(a=>a.trim())?.includes(Le)||n.append("anthropic-beta",Le),e.headers=n}}backendMiddleware(){return[]}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new He(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let n=await e,o=n.maxRetries??this.maxRetries;t==null&&(t=o,this._requestAuthFlags.delete(n)),await this.prepareOptions(n);let{req:a,url:c,timeout:l}=await this.buildRequest(n,{retryCount:o-t}),h="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),b=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(n.signal?.aborted)throw new W;let f=new AbortController,p=await this.fetchWithTimeout(c,a,l,f,n,{requestLogID:h,retryOfRequestLogID:r}).catch(Fe),y=Date.now();if(p instanceof globalThis.Error){let k=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new W;let w=re(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):"")),I=this.middleware.length>0||!!n.middleware?.length||this.backendMiddleware().length>0;if(I&&!w&&!no(p))throw T(this).info(`[${h}] middleware error (not retryable)`),T(this).debug(`[${h}] middleware error (not retryable)`,he({retryOfRequestLogID:r,url:c,durationMs:y-d,message:p.message})),p;if(t)return T(this).info(`[${h}] connection ${w?"timed out":"failed"} - ${k}`),T(this).debug(`[${h}] connection ${w?"timed out":"failed"} (${k})`,he({retryOfRequestLogID:r,url:c,durationMs:y-d,message:p.message})),this.retryRequest(n,t,r??h);throw T(this).info(`[${h}] connection ${w?"timed out":"failed"} - error; no more retries left`),T(this).debug(`[${h}] connection ${w?"timed out":"failed"} (error; no more retries left)`,he({retryOfRequestLogID:r,url:c,durationMs:y-d,message:p.message})),w?new Ze:I&&!Ls(p)?p:new ue({cause:p})}let A=[...p.headers.entries()].filter(([k])=>k==="request-id").map(([k,w])=>", "+k+": "+JSON.stringify(w)).join(""),S=`[${h}${b}${A}] ${a.method} ${c} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${y-d}ms`;if(!p.ok){let k=await this.shouldRetry(p,n);if(t&&k){let M=`retrying, ${t} attempts remaining`;return await kn(p.body),T(this).info(`${S} - ${M}`),T(this).debug(`[${h}] response error (${M})`,he({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,durationMs:y-d})),this.retryRequest(n,t,r??h,p.headers)}let w=k?"error; no more retries left":"error; not retryable";T(this).info(`${S} - ${w}`);let I=await p.text().catch(M=>Fe(M).message),R=jt(I),P=R?void 0:I;throw T(this).debug(`[${h}] response error (${w})`,he({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,message:P,durationMs:Date.now()-d})),this.makeStatusError(p.status,R,P,p.headers)}return T(this).info(S),T(this).debug(`[${h}] response start`,he({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,durationMs:y-d})),{response:p,options:n,controller:f,requestLogID:h,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new Gt(this,r,e)}async fetchWithTimeout(e,t,r,n,o,a){let{signal:c,method:l,...h}=t||{},b=this._makeAbort(n);c&&c.addEventListener("abort",b,{once:!0});let d=globalThis.ReadableStream&&h.body instanceof globalThis.ReadableStream||typeof h.body=="object"&&h.body!==null&&Symbol.asyncIterator in h.body,f={signal:n.signal,...d?{duplex:"half"}:{},method:"GET",...h};l&&(f.method=l.toUpperCase());let p=this.fetch,y=async(I,R)=>{let P=setTimeout(b,r);try{return await p.call(void 0,I,R)}finally{clearTimeout(P)}},A=o===void 0?y:(async(I,R={})=>{let P=typeof I=="string"?I:I instanceof URL?I.href:I.url;return R.headers=R.headers instanceof Headers?R.headers:new Headers(R.headers),await this.prepareRequest(R,{url:P,options:o}),a&&T(this).debug(`[${a.requestLogID}] sending request`,he({retryOfRequestLogID:a.retryOfRequestLogID,method:R.method,url:P,options:o,headers:R.headers})),y(I,R)}),S=o?.middleware,k=this.backendMiddleware(),w=S?.length||k.length?[...this.middleware,...S??[],...k]:this.middleware;return await Hs(A,w,o,this)(e,f)}async shouldRetry(e,t){let r=this._authFlags(t);if(e.status===401&&this._authState.tokenCache&&r.usedTokenCache&&!r.didRefreshFor401)return r.didRefreshFor401=!0,this._authState.tokenCache.invalidate(),!0;let n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r,n){let o,a=n?.get("retry-after-ms");if(a){let l=parseFloat(a);Number.isNaN(l)||(o=l)}let c=n?.get("retry-after");if(c&&!o){let l=parseFloat(c);Number.isNaN(l)?o=Date.parse(c)-Date.now():o=l*1e3}if(o===void 0){let l=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,l)}return await ce(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,a=Math.min(.5*Math.pow(2,o),8),c=1-Math.random()*.25;return a*c*1e3}calculateNonstreamingTimeout(e,t){if(36e5*e/128e3>6e5||t!=null&&e>t)throw new _("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:n,path:o,query:a,defaultBaseURL:c}=r;this._authState.resolution&&await this._authState.resolution,!this._baseURLIsExplicit&&this._authState.baseURL&&this.baseURL!==this._authState.baseURL&&(this.baseURL=this._authState.baseURL);let l=this.buildURL(o,a,c);"timeout"in r&&_n("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:h,body:b}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:n,bodyHeaders:h,retryCount:t});return{req:{method:n,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&b instanceof globalThis.ReadableStream&&{duplex:"half"},...b&&{body:b},...this.fetchOptions??{},...r.fetchOptions??{}},url:l,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let a=u([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Wt(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=u([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Sr(e)}:typeof e=="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:i(this,_s,"f").call(this,{body:e,headers:r})}};fn=C,_s=new WeakMap,hn=new WeakSet,Qo=function(){return this.baseURL!=="https://api.anthropic.com"};C.Anthropic=fn;C.HUMAN_PROMPT=Zo;C.AI_PROMPT=ei;C.DEFAULT_TIMEOUT=6e5;C.AnthropicError=_;C.APIError=F;C.APIConnectionError=ue;C.APIConnectionTimeoutError=Ze;C.APIUserAbortError=W;C.NotFoundError=st;C.ConflictError=nt;C.RateLimitError=it;C.BadRequestError=et;C.AuthenticationError=tt;C.InternalServerError=at;C.PermissionDeniedError=rt;C.UnprocessableEntityError=ot;C.toFile=Lr;var Ce=class extends C{constructor(){super(...arguments),this.completions=new Ge(this),this.messages=new Ne(this),this.models=new Qe(this),this.beta=new B(this)}};Ce.Completions=Ge;Ce.Messages=Ne;Ce.Models=Qe;Ce.Beta=B;var Vp=new TextEncoder;export{g as a,i as b,_ as c,T as d,pe as e,ys as f,Ce as g};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
|
+
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
+
import{readdirSync as f,statSync as m,unlinkSync as u,existsSync as a}from"fs";import{join as o}from"path";var y=30,g=y*24*60*60*1e3;function c(n){if(!a(n))return 0;let t;try{t=f(n).filter(s=>s.endsWith(".jsonl"))}catch{return 0}let e=Date.now(),r=0;for(let s of t){let i=o(n,s);try{let l=m(i);e-l.mtimeMs>g&&(u(i),r++)}catch{}}return r}function d(n){let t=0;t+=c(o(n,".swifty","logs"));let e=o(n,".swifty","teams");if(!a(e))return t;let r;try{r=f(e)}catch{return t}for(let s of r)t+=c(o(e,s,"logs"));return t}export{d as a};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
|
+
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
+
var g=Object.create;var e=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var i=Object.getOwnPropertyNames;var j=Object.getPrototypeOf,k=Object.prototype.hasOwnProperty;var m=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var n=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports),o=(a,b)=>{for(var c in b)e(a,c,{get:b[c],enumerable:!0})},l=(a,b,c,f)=>{if(b&&typeof b=="object"||typeof b=="function")for(let d of i(b))!k.call(a,d)&&d!==c&&e(a,d,{get:()=>b[d],enumerable:!(f=h(b,d))||f.enumerable});return a};var p=(a,b,c)=>(c=a!=null?g(j(a)):{},l(b||!a||!a.__esModule?e(c,"default",{value:a,enumerable:!0}):c,a));export{m as a,n as b,o as c,p as d};
|