vole-agent 0.1.7 → 0.1.8
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/web/server.js +20 -20
- package/package.json +1 -1
package/dist/web/server.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import { createRequire } from "module"; const require = createRequire(import.meta.url);
|
|
2
|
-
var Dc=Object.create;var ko=Object.defineProperty;var Uc=Object.getOwnPropertyDescriptor;var qc=Object.getOwnPropertyNames;var Fc=Object.getPrototypeOf,Hc=Object.prototype.hasOwnProperty;var C=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var J=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Wc=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of qc(e))!Hc.call(t,n)&&n!==r&&ko(t,n,{get:()=>e[n],enumerable:!(s=Uc(e,n))||s.enumerable});return t};var Se=(t,e,r)=>(r=t!=null?Dc(Fc(t)):{},Wc(e||!t||!t.__esModule?ko(r,"default",{value:t,enumerable:!0}):r,t));var de=J((Qh,Ho)=>{"use strict";var qo=["nodebuffer","arraybuffer","fragments"],Fo=typeof Blob<"u";Fo&&qo.push("blob");Ho.exports={BINARY_TYPES:qo,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Fo,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var zt=J((Zh,Mr)=>{"use strict";var{EMPTY_BUFFER:vl}=de(),tn=Buffer[Symbol.species];function El(t,e){if(t.length===0)return vl;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),s=0;for(let n=0;n<t.length;n++){let o=t[n];r.set(o,s),s+=o.length}return s<e?new tn(r.buffer,r.byteOffset,s):r}function Wo(t,e,r,s,n){for(let o=0;o<n;o++)r[s+o]=t[o]^e[o&3]}function Vo(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function kl(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function rn(t){if(rn.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new tn(t):ArrayBuffer.isView(t)?e=new tn(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),rn.readOnly=!1),e}Mr.exports={concat:El,mask:Wo,toArrayBuffer:kl,toBuffer:rn,unmask:Vo};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=C("bufferutil");Mr.exports.mask=function(e,r,s,n,o){o<48?Wo(e,r,s,n,o):t.mask(e,r,s,n,o)},Mr.exports.unmask=function(e,r){e.length<32?Vo(e,r):t.unmask(e,r)}}catch{}});var zo=J((ep,Ko)=>{"use strict";var Go=Symbol("kDone"),sn=Symbol("kRun"),nn=class{constructor(e){this[Go]=()=>{this.pending--,this[sn]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[sn]()}[sn](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Go])}}};Ko.exports=nn});var at=J((tp,Qo)=>{"use strict";var Jt=C("zlib"),Jo=zt(),Rl=zo(),{kStatusCode:Yo}=de(),Pl=Buffer[Symbol.species],Tl=Buffer.from([0,0,255,255]),Nr=Symbol("permessage-deflate"),fe=Symbol("total-length"),ot=Symbol("callback"),ve=Symbol("buffers"),it=Symbol("error"),Cr,on=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Cr){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Cr=new Rl(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[ot];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,s=e.find(n=>!(r.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>n.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!n.client_max_window_bits));if(!s)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(s.server_no_context_takeover=!0),r.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(s.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?s.client_max_window_bits=r.clientMaxWindowBits:(s.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(s=>{let n=r[s];if(n.length>1)throw new Error(`Parameter "${s}" must have only a single value`);if(n=n[0],s==="client_max_window_bits"){if(n!==!0){let o=+n;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${s}": ${n}`);n=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${s}": ${n}`)}else if(s==="server_max_window_bits"){let o=+n;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${s}": ${n}`);n=o}else if(s==="client_no_context_takeover"||s==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${s}": ${n}`)}else throw new Error(`Unknown parameter "${s}"`);r[s]=n})}),e}decompress(e,r,s){Cr.add(n=>{this._decompress(e,r,(o,i)=>{n(),s(o,i)})})}compress(e,r,s){Cr.add(n=>{this._compress(e,r,(o,i)=>{n(),s(o,i)})})}_decompress(e,r,s){let n=this._isServer?"client":"server";if(!this._inflate){let o=`${n}_max_window_bits`,i=typeof this.params[o]!="number"?Jt.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=Jt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[Nr]=this,this._inflate[fe]=0,this._inflate[ve]=[],this._inflate.on("error",Ol),this._inflate.on("data",Xo)}this._inflate[ot]=s,this._inflate.write(e),r&&this._inflate.write(Tl),this._inflate.flush(()=>{let o=this._inflate[it];if(o){this._inflate.close(),this._inflate=null,s(o);return}let i=Jo.concat(this._inflate[ve],this._inflate[fe]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[fe]=0,this._inflate[ve]=[],r&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),s(null,i)})}_compress(e,r,s){let n=this._isServer?"server":"client";if(!this._deflate){let o=`${n}_max_window_bits`,i=typeof this.params[o]!="number"?Jt.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=Jt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[fe]=0,this._deflate[ve]=[],this._deflate.on("data",Al)}this._deflate[ot]=s,this._deflate.write(e),this._deflate.flush(Jt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=Jo.concat(this._deflate[ve],this._deflate[fe]);r&&(o=new Pl(o.buffer,o.byteOffset,o.length-4)),this._deflate[ot]=null,this._deflate[fe]=0,this._deflate[ve]=[],r&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),s(null,o)})}};Qo.exports=on;function Al(t){this[ve].push(t),this[fe]+=t.length}function Xo(t){if(this[fe]+=t.length,this[Nr]._maxPayload<1||this[fe]<=this[Nr]._maxPayload){this[ve].push(t);return}this[it]=new RangeError("Max payload size exceeded"),this[it].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[it][Yo]=1009,this.removeListener("data",Xo),this.reset()}function Ol(t){if(this[Nr]._inflate=null,this[it]){this[ot](this[it]);return}t[Yo]=1007,this[ot](t)}});var ct=J((rp,Lr)=>{"use strict";var{isUtf8:Zo}=C("buffer"),{hasBlob:Il}=de(),Ml=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Cl(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function an(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function Nl(t){return Il&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Lr.exports={isBlob:Nl,isValidStatusCode:Cl,isValidUTF8:an,tokenChars:Ml};if(Zo)Lr.exports.isValidUTF8=function(t){return t.length<24?an(t):Zo(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=C("utf-8-validate");Lr.exports.isValidUTF8=function(e){return e.length<32?an(e):t(e)}}catch{}});var fn=J((sp,ii)=>{"use strict";var{Writable:Ll}=C("stream"),ei=at(),{BINARY_TYPES:$l,EMPTY_BUFFER:ti,kStatusCode:jl,kWebSocket:Bl}=de(),{concat:cn,toArrayBuffer:Dl,unmask:Ul}=zt(),{isValidStatusCode:ql,isValidUTF8:ri}=ct(),$r=Buffer[Symbol.species],te=0,si=1,ni=2,oi=3,ln=4,un=5,jr=6,dn=class extends Ll{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||$l[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Bl]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=te}_write(e,r,s){if(this._opcode===8&&this._state==te)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let s=this._buffers[0];return this._buffers[0]=new $r(s.buffer,s.byteOffset+e,s.length-e),new $r(s.buffer,s.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let s=this._buffers[0],n=r.length-e;e>=s.length?r.set(this._buffers.shift(),n):(r.set(new Uint8Array(s.buffer,s.byteOffset,e),n),this._buffers[0]=new $r(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case te:this.getInfo(e);break;case si:this.getPayloadLength16(e);break;case ni:this.getPayloadLength64(e);break;case oi:this.getMask();break;case ln:this.getData(e);break;case un:case jr:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(n);return}let s=(r[0]&64)===64;if(s&&!this._extensions[ei.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(s){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(n);return}if(s){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(n);return}this._payloadLength===126?this._state=si:this._payloadLength===127?this._state=ni:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),s=r.readUInt32BE(0);if(s>Math.pow(2,21)-1){let n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(n);return}this._payloadLength=s*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=oi:this._state=ln}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ln}getData(e){let r=ti;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Ul(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=un,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[ei.extensionName].decompress(e,this._fin,(n,o)=>{if(n)return r(n);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(i);return}this._fragments.push(o)}this.dataMessage(r),this._state===te&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=te;return}let r=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let n;this._binaryType==="nodebuffer"?n=cn(s,r):this._binaryType==="arraybuffer"?n=Dl(cn(s,r)):this._binaryType==="blob"?n=new Blob(s):n=s,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=te):(this._state=jr,setImmediate(()=>{this.emit("message",n,!0),this._state=te,this.startLoop(e)}))}else{let n=cn(s,r);if(!this._skipUTF8Validation&&!ri(n)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===un||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=te):(this._state=jr,setImmediate(()=>{this.emit("message",n,!1),this._state=te,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,ti),this.end();else{let s=e.readUInt16BE(0);if(!ql(s)){let o=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(o);return}let n=new $r(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!ri(n)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(o);return}this._loop=!1,this.emit("conclude",s,n),this.end()}this._state=te;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=te):(this._state=jr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=te,this.startLoop(r)}))}createError(e,r,s,n,o){this._loop=!1,this._errored=!0;let i=new e(s?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(i,this.createError),i.code=o,i[jl]=n,i}};ii.exports=dn});var mn=J((op,li)=>{"use strict";var{Duplex:np}=C("stream"),{randomFillSync:Fl}=C("crypto"),ai=at(),{EMPTY_BUFFER:Hl,kWebSocket:Wl,NOOP:Vl}=de(),{isBlob:lt,isValidStatusCode:Gl}=ct(),{mask:ci,toBuffer:$e}=zt(),re=Symbol("kByteLength"),Kl=Buffer.alloc(4),Br=8*1024,je,ut=Br,ae=0,zl=1,Jl=2,hn=class t{constructor(e,r,s){this._extensions=r||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ae,this.onerror=Vl,this[Wl]=void 0}static frame(e,r){let s,n=!1,o=2,i=!1;r.mask&&(s=r.maskBuffer||Kl,r.generateMask?r.generateMask(s):(ut===Br&&(je===void 0&&(je=Buffer.alloc(Br)),Fl(je,0,Br),ut=0),s[0]=je[ut++],s[1]=je[ut++],s[2]=je[ut++],s[3]=je[ut++]),i=(s[0]|s[1]|s[2]|s[3])===0,o=6);let a;typeof e=="string"?(!r.mask||i)&&r[re]!==void 0?a=r[re]:(e=Buffer.from(e),a=e.length):(a=e.length,n=r.mask&&r.readOnly&&!i);let c=a;a>=65536?(o+=8,c=127):a>125&&(o+=2,c=126);let l=Buffer.allocUnsafe(n?a+o:o);return l[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),r.mask?(l[1]|=128,l[o-4]=s[0],l[o-3]=s[1],l[o-2]=s[2],l[o-1]=s[3],i?[l,e]:n?(ci(e,s,l,o,a),[l]):(ci(e,s,e,0,a),[l,e])):[l,e]}close(e,r,s,n){let o;if(e===void 0)o=Hl;else{if(typeof e!="number"||!Gl(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");o=Buffer.allocUnsafe(2+a),o.writeUInt16BE(e,0),typeof r=="string"?o.write(r,2):o.set(r,2)}}let i={[re]:o.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ae?this.enqueue([this.dispatch,o,!1,i,n]):this.sendFrame(t.frame(o,i),n)}ping(e,r,s){let n,o;if(typeof e=="string"?(n=Buffer.byteLength(e),o=!1):lt(e)?(n=e.size,o=!1):(e=$e(e),n=e.length,o=$e.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[re]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};lt(e)?this._state!==ae?this.enqueue([this.getBlobData,e,!1,i,s]):this.getBlobData(e,!1,i,s):this._state!==ae?this.enqueue([this.dispatch,e,!1,i,s]):this.sendFrame(t.frame(e,i),s)}pong(e,r,s){let n,o;if(typeof e=="string"?(n=Buffer.byteLength(e),o=!1):lt(e)?(n=e.size,o=!1):(e=$e(e),n=e.length,o=$e.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[re]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};lt(e)?this._state!==ae?this.enqueue([this.getBlobData,e,!1,i,s]):this.getBlobData(e,!1,i,s):this._state!==ae?this.enqueue([this.dispatch,e,!1,i,s]):this.sendFrame(t.frame(e,i),s)}send(e,r,s){let n=this._extensions[ai.extensionName],o=r.binary?2:1,i=r.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):lt(e)?(a=e.size,c=!1):(e=$e(e),a=e.length,c=$e.readOnly),this._firstFragment?(this._firstFragment=!1,i&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=a>=n._threshold),this._compress=i):(i=!1,o=0),r.fin&&(this._firstFragment=!0);let l={[re]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:i};lt(e)?this._state!==ae?this.enqueue([this.getBlobData,e,this._compress,l,s]):this.getBlobData(e,this._compress,l,s):this._state!==ae?this.enqueue([this.dispatch,e,this._compress,l,s]):this.dispatch(e,this._compress,l,s)}getBlobData(e,r,s,n){this._bufferedBytes+=s[re],this._state=Jl,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(pn,this,a,n);return}this._bufferedBytes-=s[re];let i=$e(o);r?this.dispatch(i,r,s,n):(this._state=ae,this.sendFrame(t.frame(i,s),n),this.dequeue())}).catch(o=>{process.nextTick(Yl,this,o,n)})}dispatch(e,r,s,n){if(!r){this.sendFrame(t.frame(e,s),n);return}let o=this._extensions[ai.extensionName];this._bufferedBytes+=s[re],this._state=zl,o.compress(e,s.fin,(i,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");pn(this,c,n);return}this._bufferedBytes-=s[re],this._state=ae,s.readOnly=!1,this.sendFrame(t.frame(a,s),n),this.dequeue()})}dequeue(){for(;this._state===ae&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][re],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][re],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};li.exports=hn;function pn(t,e,r){typeof r=="function"&&r(e);for(let s=0;s<t._queue.length;s++){let n=t._queue[s],o=n[n.length-1];typeof o=="function"&&o(e)}}function Yl(t,e,r){pn(t,e,r),t.onerror(e)}});var _i=J((ip,yi)=>{"use strict";var{kForOnEventAttribute:Yt,kListener:gn}=de(),ui=Symbol("kCode"),di=Symbol("kData"),fi=Symbol("kError"),hi=Symbol("kMessage"),pi=Symbol("kReason"),dt=Symbol("kTarget"),mi=Symbol("kType"),gi=Symbol("kWasClean"),he=class{constructor(e){this[dt]=null,this[mi]=e}get target(){return this[dt]}get type(){return this[mi]}};Object.defineProperty(he.prototype,"target",{enumerable:!0});Object.defineProperty(he.prototype,"type",{enumerable:!0});var Be=class extends he{constructor(e,r={}){super(e),this[ui]=r.code===void 0?0:r.code,this[pi]=r.reason===void 0?"":r.reason,this[gi]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[ui]}get reason(){return this[pi]}get wasClean(){return this[gi]}};Object.defineProperty(Be.prototype,"code",{enumerable:!0});Object.defineProperty(Be.prototype,"reason",{enumerable:!0});Object.defineProperty(Be.prototype,"wasClean",{enumerable:!0});var ft=class extends he{constructor(e,r={}){super(e),this[fi]=r.error===void 0?null:r.error,this[hi]=r.message===void 0?"":r.message}get error(){return this[fi]}get message(){return this[hi]}};Object.defineProperty(ft.prototype,"error",{enumerable:!0});Object.defineProperty(ft.prototype,"message",{enumerable:!0});var Xt=class extends he{constructor(e,r={}){super(e),this[di]=r.data===void 0?null:r.data}get data(){return this[di]}};Object.defineProperty(Xt.prototype,"data",{enumerable:!0});var Xl={addEventListener(t,e,r={}){for(let n of this.listeners(t))if(!r[Yt]&&n[gn]===e&&!n[Yt])return;let s;if(t==="message")s=function(o,i){let a=new Xt("message",{data:i?o:o.toString()});a[dt]=this,Dr(e,this,a)};else if(t==="close")s=function(o,i){let a=new Be("close",{code:o,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[dt]=this,Dr(e,this,a)};else if(t==="error")s=function(o){let i=new ft("error",{error:o,message:o.message});i[dt]=this,Dr(e,this,i)};else if(t==="open")s=function(){let o=new he("open");o[dt]=this,Dr(e,this,o)};else return;s[Yt]=!!r[Yt],s[gn]=e,r.once?this.once(t,s):this.on(t,s)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[gn]===e&&!r[Yt]){this.removeListener(t,r);break}}};yi.exports={CloseEvent:Be,ErrorEvent:ft,Event:he,EventTarget:Xl,MessageEvent:Xt};function Dr(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Ur=J((ap,bi)=>{"use strict";var{tokenChars:Qt}=ct();function ce(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function Ql(t){let e=Object.create(null),r=Object.create(null),s=!1,n=!1,o=!1,i,a,c=-1,l=-1,u=-1,d=0;for(;d<t.length;d++)if(l=t.charCodeAt(d),i===void 0)if(u===-1&&Qt[l]===1)c===-1&&(c=d);else if(d!==0&&(l===32||l===9))u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let h=t.slice(c,u);l===44?(ce(e,h,r),r=Object.create(null)):i=h,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&Qt[l]===1)c===-1&&(c=d);else if(l===32||l===9)u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),ce(r,t.slice(c,u),!0),l===44&&(ce(e,i,r),r=Object.create(null),i=void 0),c=u=-1}else if(l===61&&c!==-1&&u===-1)a=t.slice(c,d),c=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(n){if(Qt[l]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:s||(s=!0),n=!1}else if(o)if(Qt[l]===1)c===-1&&(c=d);else if(l===34&&c!==-1)o=!1,u=d;else if(l===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(l===34&&t.charCodeAt(d-1)===61)o=!0;else if(u===-1&&Qt[l]===1)c===-1&&(c=d);else if(c!==-1&&(l===32||l===9))u===-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let h=t.slice(c,u);s&&(h=h.replace(/\\/g,""),s=!1),ce(r,a,h),l===44&&(ce(e,i,r),r=Object.create(null),i=void 0),a=void 0,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(c===-1||o||l===32||l===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let p=t.slice(c,u);return i===void 0?ce(e,p,r):(a===void 0?ce(r,p,!0):s?ce(r,a,p.replace(/\\/g,"")):ce(r,a,p),ce(e,i,r)),e}function Zl(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(s=>[e].concat(Object.keys(s).map(n=>{let o=s[n];return Array.isArray(o)||(o=[o]),o.map(i=>i===!0?n:`${n}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}bi.exports={format:Zl,parse:Ql}});var Wr=J((up,Ii)=>{"use strict";var eu=C("events"),tu=C("https"),ru=C("http"),Si=C("net"),su=C("tls"),{randomBytes:nu,createHash:ou}=C("crypto"),{Duplex:cp,Readable:lp}=C("stream"),{URL:yn}=C("url"),Ee=at(),iu=fn(),au=mn(),{isBlob:cu}=ct(),{BINARY_TYPES:wi,CLOSE_TIMEOUT:lu,EMPTY_BUFFER:qr,GUID:uu,kForOnEventAttribute:_n,kListener:du,kStatusCode:fu,kWebSocket:j,NOOP:vi}=de(),{EventTarget:{addEventListener:hu,removeEventListener:pu}}=_i(),{format:mu,parse:gu}=Ur(),{toBuffer:yu}=zt(),Ei=Symbol("kAborted"),bn=[8,13],pe=["CONNECTING","OPEN","CLOSING","CLOSED"],_u=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,O=class t extends eu{constructor(e,r,s){super(),this._binaryType=wi[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=qr,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(s=r,r=[]):r=[r]),ki(this,e,r,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){wi.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,s){let n=new iu({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),o=new au(e,this._extensions,s.generateMask);this._receiver=n,this._sender=o,this._socket=e,n[j]=this,o[j]=this,e[j]=this,n.on("conclude",xu),n.on("drain",Su),n.on("error",vu),n.on("message",Eu),n.on("ping",ku),n.on("pong",Ru),o.onerror=Pu,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",Ti),e.on("data",Hr),e.on("end",Ai),e.on("error",Oi),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Ee.extensionName]&&this._extensions[Ee.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Y(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,s=>{s||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Pi(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){wn(this,e,s);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||qr,r,s)}pong(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){wn(this,e,s);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||qr,r,s)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(s=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){wn(this,e,s);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Ee.extensionName]||(n.compress=!1),this._sender.send(e||qr,n,s)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Y(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(O,"CONNECTING",{enumerable:!0,value:pe.indexOf("CONNECTING")});Object.defineProperty(O.prototype,"CONNECTING",{enumerable:!0,value:pe.indexOf("CONNECTING")});Object.defineProperty(O,"OPEN",{enumerable:!0,value:pe.indexOf("OPEN")});Object.defineProperty(O.prototype,"OPEN",{enumerable:!0,value:pe.indexOf("OPEN")});Object.defineProperty(O,"CLOSING",{enumerable:!0,value:pe.indexOf("CLOSING")});Object.defineProperty(O.prototype,"CLOSING",{enumerable:!0,value:pe.indexOf("CLOSING")});Object.defineProperty(O,"CLOSED",{enumerable:!0,value:pe.indexOf("CLOSED")});Object.defineProperty(O.prototype,"CLOSED",{enumerable:!0,value:pe.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(O.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(O.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[_n])return e[du];return null},set(e){for(let r of this.listeners(t))if(r[_n]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[_n]:!0})}})});O.prototype.addEventListener=hu;O.prototype.removeEventListener=pu;Ii.exports=O;function ki(t,e,r,s){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:lu,protocolVersion:bn[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=n.autoPong,t._closeTimeout=n.closeTimeout,!bn.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${bn.join(", ")})`);let o;if(e instanceof yn)o=e;else try{o=new yn(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),t._url=o.href;let i=o.protocol==="wss:",a=o.protocol==="ws+unix:",c;if(o.protocol!=="ws:"&&!i&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"),c){let b=new SyntaxError(c);if(t._redirects===0)throw b;Fr(t,b);return}let l=i?443:80,u=nu(16).toString("base64"),d=i?tu.request:ru.request,p=new Set,h;if(n.createConnection=n.createConnection||(i?wu:bu),n.defaultPort=n.defaultPort||l,n.port=o.port||l,n.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},n.path=o.pathname+o.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(h=new Ee({...n.perMessageDeflate,isServer:!1,maxPayload:n.maxPayload}),n.headers["Sec-WebSocket-Extensions"]=mu({[Ee.extensionName]:h.offer()})),r.length){for(let b of r){if(typeof b!="string"||!_u.test(b)||p.has(b))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(b)}n.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(o.username||o.password)&&(n.auth=`${o.username}:${o.password}`),a){let b=n.path.split(":");n.socketPath=b[0],n.path=b[1]}let g;if(n.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=i,t._originalHostOrSocketPath=a?n.socketPath:o.host;let b=s&&s.headers;if(s={...s,headers:{}},b)for(let[S,v]of Object.entries(b))s.headers[S.toLowerCase()]=v}else if(t.listenerCount("redirect")===0){let b=a?t._originalIpc?n.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!b||t._originalSecure&&!i)&&(delete n.headers.authorization,delete n.headers.cookie,b||delete n.headers.host,n.auth=void 0)}n.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),g=t._req=d(n),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(n);n.timeout&&g.on("timeout",()=>{Y(t,g,"Opening handshake has timed out")}),g.on("error",b=>{g===null||g[Ei]||(g=t._req=null,Fr(t,b))}),g.on("response",b=>{let S=b.headers.location,v=b.statusCode;if(S&&n.followRedirects&&v>=300&&v<400){if(++t._redirects>n.maxRedirects){Y(t,g,"Maximum redirects exceeded");return}g.abort();let k;try{k=new yn(S,e)}catch{let N=new SyntaxError(`Invalid URL: ${S}`);Fr(t,N);return}ki(t,k,r,s)}else t.emit("unexpected-response",g,b)||Y(t,g,`Unexpected server response: ${b.statusCode}`)}),g.on("upgrade",(b,S,v)=>{if(t.emit("upgrade",b),t.readyState!==O.CONNECTING)return;g=t._req=null;let k=b.headers.upgrade;if(k===void 0||k.toLowerCase()!=="websocket"){Y(t,S,"Invalid Upgrade header");return}let U=ou("sha1").update(u+uu).digest("base64");if(b.headers["sec-websocket-accept"]!==U){Y(t,S,"Invalid Sec-WebSocket-Accept header");return}let N=b.headers["sec-websocket-protocol"],V;if(N!==void 0?p.size?p.has(N)||(V="Server sent an invalid subprotocol"):V="Server sent a subprotocol but none was requested":p.size&&(V="Server sent no subprotocol"),V){Y(t,S,V);return}N&&(t._protocol=N);let W=b.headers["sec-websocket-extensions"];if(W!==void 0){if(!h){Y(t,S,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let x;try{x=gu(W)}catch{Y(t,S,"Invalid Sec-WebSocket-Extensions header");return}let $=Object.keys(x);if($.length!==1||$[0]!==Ee.extensionName){Y(t,S,"Server indicated an extension that was not requested");return}try{h.accept(x[Ee.extensionName])}catch{Y(t,S,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Ee.extensionName]=h}t.setSocket(S,v,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(g,t):g.end()}function Fr(t,e){t._readyState=O.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function bu(t){return t.path=t.socketPath,Si.connect(t)}function wu(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Si.isIP(t.host)?"":t.host),su.connect(t)}function Y(t,e,r){t._readyState=O.CLOSING;let s=new Error(r);Error.captureStackTrace(s,Y),e.setHeader?(e[Ei]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Fr,t,s)):(e.destroy(s),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function wn(t,e,r){if(e){let s=cu(e)?e.size:yu(e).length;t._socket?t._sender._bufferedBytes+=s:t._bufferedAmount+=s}if(r){let s=new Error(`WebSocket is not open: readyState ${t.readyState} (${pe[t.readyState]})`);process.nextTick(r,s)}}function xu(t,e){let r=this[j];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[j]!==void 0&&(r._socket.removeListener("data",Hr),process.nextTick(Ri,r._socket),t===1005?r.close():r.close(t,e))}function Su(){let t=this[j];t.isPaused||t._socket.resume()}function vu(t){let e=this[j];e._socket[j]!==void 0&&(e._socket.removeListener("data",Hr),process.nextTick(Ri,e._socket),e.close(t[fu])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function xi(){this[j].emitClose()}function Eu(t,e){this[j].emit("message",t,e)}function ku(t){let e=this[j];e._autoPong&&e.pong(t,!this._isServer,vi),e.emit("ping",t)}function Ru(t){this[j].emit("pong",t)}function Ri(t){t.resume()}function Pu(t){let e=this[j];e.readyState!==O.CLOSED&&(e.readyState===O.OPEN&&(e._readyState=O.CLOSING,Pi(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Pi(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Ti(){let t=this[j];if(this.removeListener("close",Ti),this.removeListener("data",Hr),this.removeListener("end",Ai),t._readyState=O.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[j]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",xi),t._receiver.on("finish",xi))}function Hr(t){this[j]._receiver.write(t)||this.pause()}function Ai(){let t=this[j];t._readyState=O.CLOSING,t._receiver.end(),this.end()}function Oi(){let t=this[j];this.removeListener("error",Oi),this.on("error",vi),t&&(t._readyState=O.CLOSING,this.destroy())}});var Li=J((fp,Ni)=>{"use strict";var dp=Wr(),{Duplex:Tu}=C("stream");function Mi(t){t.emit("close")}function Au(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ci(t){this.removeListener("error",Ci),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Ou(t,e){let r=!0,s=new Tu({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,i){let a=!i&&s._readableState.objectMode?o.toString():o;s.push(a)||t.pause()}),t.once("error",function(o){s.destroyed||(r=!1,s.destroy(o))}),t.once("close",function(){s.destroyed||s.push(null)}),s._destroy=function(n,o){if(t.readyState===t.CLOSED){o(n),process.nextTick(Mi,s);return}let i=!1;t.once("error",function(c){i=!0,o(c)}),t.once("close",function(){i||o(n),process.nextTick(Mi,s)}),r&&t.terminate()},s._final=function(n){if(t.readyState===t.CONNECTING){t.once("open",function(){s._final(n)});return}t._socket!==null&&(t._socket._writableState.finished?(n(),s._readableState.endEmitted&&s.destroy()):(t._socket.once("finish",function(){n()}),t.close()))},s._read=function(){t.isPaused&&t.resume()},s._write=function(n,o,i){if(t.readyState===t.CONNECTING){t.once("open",function(){s._write(n,o,i)});return}t.send(n,i)},s.on("end",Au),s.on("error",Ci),s}Ni.exports=Ou});var xn=J((hp,$i)=>{"use strict";var{tokenChars:Iu}=ct();function Mu(t){let e=new Set,r=-1,s=-1,n=0;for(n;n<t.length;n++){let i=t.charCodeAt(n);if(s===-1&&Iu[i]===1)r===-1&&(r=n);else if(n!==0&&(i===32||i===9))s===-1&&r!==-1&&(s=n);else if(i===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${n}`);s===-1&&(s=n);let a=t.slice(r,s);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),r=s=-1}else throw new SyntaxError(`Unexpected character at index ${n}`)}if(r===-1||s!==-1)throw new SyntaxError("Unexpected end of input");let o=t.slice(r,n);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}$i.exports={parse:Mu}});var Hi=J((mp,Fi)=>{"use strict";var Cu=C("events"),Vr=C("http"),{Duplex:pp}=C("stream"),{createHash:Nu}=C("crypto"),ji=Ur(),De=at(),Lu=xn(),$u=Wr(),{CLOSE_TIMEOUT:ju,GUID:Bu,kWebSocket:Du}=de(),Uu=/^[+/0-9A-Za-z]{22}==$/,Bi=0,Di=1,qi=2,Sn=class extends Cu{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:ju,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:$u,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Vr.createServer((s,n)=>{let o=Vr.STATUS_CODES[426];n.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),n.end(o)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let s=this.emit.bind(this,"connection");this._removeListeners=qu(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(n,o,i)=>{this.handleUpgrade(n,o,i,s)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Bi}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===qi){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Zt,this);return}if(e&&this.once("close",e),this._state!==Di)if(this._state=Di,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Zt,this):process.nextTick(Zt,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Zt(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,s,n){r.on("error",Ui);let o=e.headers["sec-websocket-key"],i=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ue(this,e,r,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){Ue(this,e,r,400,"Invalid Upgrade header");return}if(o===void 0||!Uu.test(o)){Ue(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Ue(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){er(r,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=Lu.parse(c)}catch{Ue(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let p=new De({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=ji.parse(u);h[De.extensionName]&&(p.accept(h[De.extensionName]),d[De.extensionName]=p)}catch{Ue(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let p={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(p,(h,g,b,S)=>{if(!h)return er(r,g||401,b,S);this.completeUpgrade(d,o,l,e,r,s,n)});return}if(!this.options.verifyClient(p))return er(r,401)}this.completeUpgrade(d,o,l,e,r,s,n)}completeUpgrade(e,r,s,n,o,i,a){if(!o.readable||!o.writable)return o.destroy();if(o[Du])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Bi)return er(o,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Nu("sha1").update(r+Bu).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(s.size){let d=this.options.handleProtocols?this.options.handleProtocols(s,n):s.values().next().value;d&&(l.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[De.extensionName]){let d=e[De.extensionName].params,p=ji.format({[De.extensionName]:[d]});l.push(`Sec-WebSocket-Extensions: ${p}`),u._extensions=e}this.emit("headers",l,n),o.write(l.concat(`\r
|
|
2
|
+
var Dc=Object.create;var Eo=Object.defineProperty;var Uc=Object.getOwnPropertyDescriptor;var qc=Object.getOwnPropertyNames;var Fc=Object.getPrototypeOf,Hc=Object.prototype.hasOwnProperty;var C=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var J=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Wc=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of qc(e))!Hc.call(t,n)&&n!==r&&Eo(t,n,{get:()=>e[n],enumerable:!(s=Uc(e,n))||s.enumerable});return t};var Se=(t,e,r)=>(r=t!=null?Dc(Fc(t)):{},Wc(e||!t||!t.__esModule?Eo(r,"default",{value:t,enumerable:!0}):r,t));var de=J((ep,Ho)=>{"use strict";var qo=["nodebuffer","arraybuffer","fragments"],Fo=typeof Blob<"u";Fo&&qo.push("blob");Ho.exports={BINARY_TYPES:qo,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Fo,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var zt=J((tp,Mr)=>{"use strict";var{EMPTY_BUFFER:vl}=de(),en=Buffer[Symbol.species];function El(t,e){if(t.length===0)return vl;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),s=0;for(let n=0;n<t.length;n++){let o=t[n];r.set(o,s),s+=o.length}return s<e?new en(r.buffer,r.byteOffset,s):r}function Wo(t,e,r,s,n){for(let o=0;o<n;o++)r[s+o]=t[o]^e[o&3]}function Vo(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function kl(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function tn(t){if(tn.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new en(t):ArrayBuffer.isView(t)?e=new en(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),tn.readOnly=!1),e}Mr.exports={concat:El,mask:Wo,toArrayBuffer:kl,toBuffer:tn,unmask:Vo};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=C("bufferutil");Mr.exports.mask=function(e,r,s,n,o){o<48?Wo(e,r,s,n,o):t.mask(e,r,s,n,o)},Mr.exports.unmask=function(e,r){e.length<32?Vo(e,r):t.unmask(e,r)}}catch{}});var zo=J((rp,Ko)=>{"use strict";var Go=Symbol("kDone"),rn=Symbol("kRun"),sn=class{constructor(e){this[Go]=()=>{this.pending--,this[rn]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[rn]()}[rn](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Go])}}};Ko.exports=sn});var at=J((sp,Qo)=>{"use strict";var Jt=C("zlib"),Jo=zt(),Rl=zo(),{kStatusCode:Yo}=de(),Pl=Buffer[Symbol.species],Tl=Buffer.from([0,0,255,255]),Nr=Symbol("permessage-deflate"),fe=Symbol("total-length"),ot=Symbol("callback"),ve=Symbol("buffers"),it=Symbol("error"),Cr,nn=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Cr){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Cr=new Rl(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[ot];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,s=e.find(n=>!(r.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>n.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!n.client_max_window_bits));if(!s)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(s.server_no_context_takeover=!0),r.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(s.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?s.client_max_window_bits=r.clientMaxWindowBits:(s.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(s=>{let n=r[s];if(n.length>1)throw new Error(`Parameter "${s}" must have only a single value`);if(n=n[0],s==="client_max_window_bits"){if(n!==!0){let o=+n;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${s}": ${n}`);n=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${s}": ${n}`)}else if(s==="server_max_window_bits"){let o=+n;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${s}": ${n}`);n=o}else if(s==="client_no_context_takeover"||s==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${s}": ${n}`)}else throw new Error(`Unknown parameter "${s}"`);r[s]=n})}),e}decompress(e,r,s){Cr.add(n=>{this._decompress(e,r,(o,i)=>{n(),s(o,i)})})}compress(e,r,s){Cr.add(n=>{this._compress(e,r,(o,i)=>{n(),s(o,i)})})}_decompress(e,r,s){let n=this._isServer?"client":"server";if(!this._inflate){let o=`${n}_max_window_bits`,i=typeof this.params[o]!="number"?Jt.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=Jt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[Nr]=this,this._inflate[fe]=0,this._inflate[ve]=[],this._inflate.on("error",Ol),this._inflate.on("data",Xo)}this._inflate[ot]=s,this._inflate.write(e),r&&this._inflate.write(Tl),this._inflate.flush(()=>{let o=this._inflate[it];if(o){this._inflate.close(),this._inflate=null,s(o);return}let i=Jo.concat(this._inflate[ve],this._inflate[fe]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[fe]=0,this._inflate[ve]=[],r&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),s(null,i)})}_compress(e,r,s){let n=this._isServer?"server":"client";if(!this._deflate){let o=`${n}_max_window_bits`,i=typeof this.params[o]!="number"?Jt.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=Jt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[fe]=0,this._deflate[ve]=[],this._deflate.on("data",Al)}this._deflate[ot]=s,this._deflate.write(e),this._deflate.flush(Jt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=Jo.concat(this._deflate[ve],this._deflate[fe]);r&&(o=new Pl(o.buffer,o.byteOffset,o.length-4)),this._deflate[ot]=null,this._deflate[fe]=0,this._deflate[ve]=[],r&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),s(null,o)})}};Qo.exports=nn;function Al(t){this[ve].push(t),this[fe]+=t.length}function Xo(t){if(this[fe]+=t.length,this[Nr]._maxPayload<1||this[fe]<=this[Nr]._maxPayload){this[ve].push(t);return}this[it]=new RangeError("Max payload size exceeded"),this[it].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[it][Yo]=1009,this.removeListener("data",Xo),this.reset()}function Ol(t){if(this[Nr]._inflate=null,this[it]){this[ot](this[it]);return}t[Yo]=1007,this[ot](t)}});var ct=J((np,Lr)=>{"use strict";var{isUtf8:Zo}=C("buffer"),{hasBlob:Il}=de(),Ml=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Cl(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function on(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function Nl(t){return Il&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Lr.exports={isBlob:Nl,isValidStatusCode:Cl,isValidUTF8:on,tokenChars:Ml};if(Zo)Lr.exports.isValidUTF8=function(t){return t.length<24?on(t):Zo(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=C("utf-8-validate");Lr.exports.isValidUTF8=function(e){return e.length<32?on(e):t(e)}}catch{}});var dn=J((op,ii)=>{"use strict";var{Writable:Ll}=C("stream"),ei=at(),{BINARY_TYPES:$l,EMPTY_BUFFER:ti,kStatusCode:jl,kWebSocket:Bl}=de(),{concat:an,toArrayBuffer:Dl,unmask:Ul}=zt(),{isValidStatusCode:ql,isValidUTF8:ri}=ct(),$r=Buffer[Symbol.species],ee=0,si=1,ni=2,oi=3,cn=4,ln=5,jr=6,un=class extends Ll{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||$l[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Bl]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=ee}_write(e,r,s){if(this._opcode===8&&this._state==ee)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let s=this._buffers[0];return this._buffers[0]=new $r(s.buffer,s.byteOffset+e,s.length-e),new $r(s.buffer,s.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let s=this._buffers[0],n=r.length-e;e>=s.length?r.set(this._buffers.shift(),n):(r.set(new Uint8Array(s.buffer,s.byteOffset,e),n),this._buffers[0]=new $r(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case ee:this.getInfo(e);break;case si:this.getPayloadLength16(e);break;case ni:this.getPayloadLength64(e);break;case oi:this.getMask();break;case cn:this.getData(e);break;case ln:case jr:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(n);return}let s=(r[0]&64)===64;if(s&&!this._extensions[ei.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(s){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(n);return}if(s){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(n);return}this._payloadLength===126?this._state=si:this._payloadLength===127?this._state=ni:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),s=r.readUInt32BE(0);if(s>Math.pow(2,21)-1){let n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(n);return}this._payloadLength=s*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=oi:this._state=cn}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=cn}getData(e){let r=ti;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Ul(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=ln,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[ei.extensionName].decompress(e,this._fin,(n,o)=>{if(n)return r(n);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(i);return}this._fragments.push(o)}this.dataMessage(r),this._state===ee&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=ee;return}let r=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let n;this._binaryType==="nodebuffer"?n=an(s,r):this._binaryType==="arraybuffer"?n=Dl(an(s,r)):this._binaryType==="blob"?n=new Blob(s):n=s,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=ee):(this._state=jr,setImmediate(()=>{this.emit("message",n,!0),this._state=ee,this.startLoop(e)}))}else{let n=an(s,r);if(!this._skipUTF8Validation&&!ri(n)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===ln||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=ee):(this._state=jr,setImmediate(()=>{this.emit("message",n,!1),this._state=ee,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,ti),this.end();else{let s=e.readUInt16BE(0);if(!ql(s)){let o=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(o);return}let n=new $r(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!ri(n)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(o);return}this._loop=!1,this.emit("conclude",s,n),this.end()}this._state=ee;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ee):(this._state=jr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ee,this.startLoop(r)}))}createError(e,r,s,n,o){this._loop=!1,this._errored=!0;let i=new e(s?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(i,this.createError),i.code=o,i[jl]=n,i}};ii.exports=un});var pn=J((ap,li)=>{"use strict";var{Duplex:ip}=C("stream"),{randomFillSync:Fl}=C("crypto"),ai=at(),{EMPTY_BUFFER:Hl,kWebSocket:Wl,NOOP:Vl}=de(),{isBlob:lt,isValidStatusCode:Gl}=ct(),{mask:ci,toBuffer:$e}=zt(),te=Symbol("kByteLength"),Kl=Buffer.alloc(4),Br=8*1024,je,ut=Br,ae=0,zl=1,Jl=2,fn=class t{constructor(e,r,s){this._extensions=r||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ae,this.onerror=Vl,this[Wl]=void 0}static frame(e,r){let s,n=!1,o=2,i=!1;r.mask&&(s=r.maskBuffer||Kl,r.generateMask?r.generateMask(s):(ut===Br&&(je===void 0&&(je=Buffer.alloc(Br)),Fl(je,0,Br),ut=0),s[0]=je[ut++],s[1]=je[ut++],s[2]=je[ut++],s[3]=je[ut++]),i=(s[0]|s[1]|s[2]|s[3])===0,o=6);let a;typeof e=="string"?(!r.mask||i)&&r[te]!==void 0?a=r[te]:(e=Buffer.from(e),a=e.length):(a=e.length,n=r.mask&&r.readOnly&&!i);let c=a;a>=65536?(o+=8,c=127):a>125&&(o+=2,c=126);let l=Buffer.allocUnsafe(n?a+o:o);return l[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),r.mask?(l[1]|=128,l[o-4]=s[0],l[o-3]=s[1],l[o-2]=s[2],l[o-1]=s[3],i?[l,e]:n?(ci(e,s,l,o,a),[l]):(ci(e,s,e,0,a),[l,e])):[l,e]}close(e,r,s,n){let o;if(e===void 0)o=Hl;else{if(typeof e!="number"||!Gl(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");o=Buffer.allocUnsafe(2+a),o.writeUInt16BE(e,0),typeof r=="string"?o.write(r,2):o.set(r,2)}}let i={[te]:o.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ae?this.enqueue([this.dispatch,o,!1,i,n]):this.sendFrame(t.frame(o,i),n)}ping(e,r,s){let n,o;if(typeof e=="string"?(n=Buffer.byteLength(e),o=!1):lt(e)?(n=e.size,o=!1):(e=$e(e),n=e.length,o=$e.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[te]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};lt(e)?this._state!==ae?this.enqueue([this.getBlobData,e,!1,i,s]):this.getBlobData(e,!1,i,s):this._state!==ae?this.enqueue([this.dispatch,e,!1,i,s]):this.sendFrame(t.frame(e,i),s)}pong(e,r,s){let n,o;if(typeof e=="string"?(n=Buffer.byteLength(e),o=!1):lt(e)?(n=e.size,o=!1):(e=$e(e),n=e.length,o=$e.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[te]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};lt(e)?this._state!==ae?this.enqueue([this.getBlobData,e,!1,i,s]):this.getBlobData(e,!1,i,s):this._state!==ae?this.enqueue([this.dispatch,e,!1,i,s]):this.sendFrame(t.frame(e,i),s)}send(e,r,s){let n=this._extensions[ai.extensionName],o=r.binary?2:1,i=r.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):lt(e)?(a=e.size,c=!1):(e=$e(e),a=e.length,c=$e.readOnly),this._firstFragment?(this._firstFragment=!1,i&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=a>=n._threshold),this._compress=i):(i=!1,o=0),r.fin&&(this._firstFragment=!0);let l={[te]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:i};lt(e)?this._state!==ae?this.enqueue([this.getBlobData,e,this._compress,l,s]):this.getBlobData(e,this._compress,l,s):this._state!==ae?this.enqueue([this.dispatch,e,this._compress,l,s]):this.dispatch(e,this._compress,l,s)}getBlobData(e,r,s,n){this._bufferedBytes+=s[te],this._state=Jl,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(hn,this,a,n);return}this._bufferedBytes-=s[te];let i=$e(o);r?this.dispatch(i,r,s,n):(this._state=ae,this.sendFrame(t.frame(i,s),n),this.dequeue())}).catch(o=>{process.nextTick(Yl,this,o,n)})}dispatch(e,r,s,n){if(!r){this.sendFrame(t.frame(e,s),n);return}let o=this._extensions[ai.extensionName];this._bufferedBytes+=s[te],this._state=zl,o.compress(e,s.fin,(i,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");hn(this,c,n);return}this._bufferedBytes-=s[te],this._state=ae,s.readOnly=!1,this.sendFrame(t.frame(a,s),n),this.dequeue()})}dequeue(){for(;this._state===ae&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][te],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][te],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};li.exports=fn;function hn(t,e,r){typeof r=="function"&&r(e);for(let s=0;s<t._queue.length;s++){let n=t._queue[s],o=n[n.length-1];typeof o=="function"&&o(e)}}function Yl(t,e,r){hn(t,e,r),t.onerror(e)}});var _i=J((cp,yi)=>{"use strict";var{kForOnEventAttribute:Yt,kListener:mn}=de(),ui=Symbol("kCode"),di=Symbol("kData"),fi=Symbol("kError"),hi=Symbol("kMessage"),pi=Symbol("kReason"),dt=Symbol("kTarget"),mi=Symbol("kType"),gi=Symbol("kWasClean"),he=class{constructor(e){this[dt]=null,this[mi]=e}get target(){return this[dt]}get type(){return this[mi]}};Object.defineProperty(he.prototype,"target",{enumerable:!0});Object.defineProperty(he.prototype,"type",{enumerable:!0});var Be=class extends he{constructor(e,r={}){super(e),this[ui]=r.code===void 0?0:r.code,this[pi]=r.reason===void 0?"":r.reason,this[gi]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[ui]}get reason(){return this[pi]}get wasClean(){return this[gi]}};Object.defineProperty(Be.prototype,"code",{enumerable:!0});Object.defineProperty(Be.prototype,"reason",{enumerable:!0});Object.defineProperty(Be.prototype,"wasClean",{enumerable:!0});var ft=class extends he{constructor(e,r={}){super(e),this[fi]=r.error===void 0?null:r.error,this[hi]=r.message===void 0?"":r.message}get error(){return this[fi]}get message(){return this[hi]}};Object.defineProperty(ft.prototype,"error",{enumerable:!0});Object.defineProperty(ft.prototype,"message",{enumerable:!0});var Xt=class extends he{constructor(e,r={}){super(e),this[di]=r.data===void 0?null:r.data}get data(){return this[di]}};Object.defineProperty(Xt.prototype,"data",{enumerable:!0});var Xl={addEventListener(t,e,r={}){for(let n of this.listeners(t))if(!r[Yt]&&n[mn]===e&&!n[Yt])return;let s;if(t==="message")s=function(o,i){let a=new Xt("message",{data:i?o:o.toString()});a[dt]=this,Dr(e,this,a)};else if(t==="close")s=function(o,i){let a=new Be("close",{code:o,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[dt]=this,Dr(e,this,a)};else if(t==="error")s=function(o){let i=new ft("error",{error:o,message:o.message});i[dt]=this,Dr(e,this,i)};else if(t==="open")s=function(){let o=new he("open");o[dt]=this,Dr(e,this,o)};else return;s[Yt]=!!r[Yt],s[mn]=e,r.once?this.once(t,s):this.on(t,s)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[mn]===e&&!r[Yt]){this.removeListener(t,r);break}}};yi.exports={CloseEvent:Be,ErrorEvent:ft,Event:he,EventTarget:Xl,MessageEvent:Xt};function Dr(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Ur=J((lp,bi)=>{"use strict";var{tokenChars:Qt}=ct();function ce(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function Ql(t){let e=Object.create(null),r=Object.create(null),s=!1,n=!1,o=!1,i,a,c=-1,l=-1,u=-1,d=0;for(;d<t.length;d++)if(l=t.charCodeAt(d),i===void 0)if(u===-1&&Qt[l]===1)c===-1&&(c=d);else if(d!==0&&(l===32||l===9))u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let h=t.slice(c,u);l===44?(ce(e,h,r),r=Object.create(null)):i=h,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&Qt[l]===1)c===-1&&(c=d);else if(l===32||l===9)u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),ce(r,t.slice(c,u),!0),l===44&&(ce(e,i,r),r=Object.create(null),i=void 0),c=u=-1}else if(l===61&&c!==-1&&u===-1)a=t.slice(c,d),c=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(n){if(Qt[l]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:s||(s=!0),n=!1}else if(o)if(Qt[l]===1)c===-1&&(c=d);else if(l===34&&c!==-1)o=!1,u=d;else if(l===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(l===34&&t.charCodeAt(d-1)===61)o=!0;else if(u===-1&&Qt[l]===1)c===-1&&(c=d);else if(c!==-1&&(l===32||l===9))u===-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let h=t.slice(c,u);s&&(h=h.replace(/\\/g,""),s=!1),ce(r,a,h),l===44&&(ce(e,i,r),r=Object.create(null),i=void 0),a=void 0,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(c===-1||o||l===32||l===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let p=t.slice(c,u);return i===void 0?ce(e,p,r):(a===void 0?ce(r,p,!0):s?ce(r,a,p.replace(/\\/g,"")):ce(r,a,p),ce(e,i,r)),e}function Zl(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(s=>[e].concat(Object.keys(s).map(n=>{let o=s[n];return Array.isArray(o)||(o=[o]),o.map(i=>i===!0?n:`${n}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}bi.exports={format:Zl,parse:Ql}});var Wr=J((fp,Ii)=>{"use strict";var eu=C("events"),tu=C("https"),ru=C("http"),Si=C("net"),su=C("tls"),{randomBytes:nu,createHash:ou}=C("crypto"),{Duplex:up,Readable:dp}=C("stream"),{URL:gn}=C("url"),Ee=at(),iu=dn(),au=pn(),{isBlob:cu}=ct(),{BINARY_TYPES:wi,CLOSE_TIMEOUT:lu,EMPTY_BUFFER:qr,GUID:uu,kForOnEventAttribute:yn,kListener:du,kStatusCode:fu,kWebSocket:j,NOOP:vi}=de(),{EventTarget:{addEventListener:hu,removeEventListener:pu}}=_i(),{format:mu,parse:gu}=Ur(),{toBuffer:yu}=zt(),Ei=Symbol("kAborted"),_n=[8,13],pe=["CONNECTING","OPEN","CLOSING","CLOSED"],_u=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,O=class t extends eu{constructor(e,r,s){super(),this._binaryType=wi[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=qr,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(s=r,r=[]):r=[r]),ki(this,e,r,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){wi.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,s){let n=new iu({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),o=new au(e,this._extensions,s.generateMask);this._receiver=n,this._sender=o,this._socket=e,n[j]=this,o[j]=this,e[j]=this,n.on("conclude",xu),n.on("drain",Su),n.on("error",vu),n.on("message",Eu),n.on("ping",ku),n.on("pong",Ru),o.onerror=Pu,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",Ti),e.on("data",Hr),e.on("end",Ai),e.on("error",Oi),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Ee.extensionName]&&this._extensions[Ee.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Y(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,s=>{s||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Pi(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){bn(this,e,s);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||qr,r,s)}pong(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){bn(this,e,s);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||qr,r,s)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(s=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){bn(this,e,s);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Ee.extensionName]||(n.compress=!1),this._sender.send(e||qr,n,s)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Y(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(O,"CONNECTING",{enumerable:!0,value:pe.indexOf("CONNECTING")});Object.defineProperty(O.prototype,"CONNECTING",{enumerable:!0,value:pe.indexOf("CONNECTING")});Object.defineProperty(O,"OPEN",{enumerable:!0,value:pe.indexOf("OPEN")});Object.defineProperty(O.prototype,"OPEN",{enumerable:!0,value:pe.indexOf("OPEN")});Object.defineProperty(O,"CLOSING",{enumerable:!0,value:pe.indexOf("CLOSING")});Object.defineProperty(O.prototype,"CLOSING",{enumerable:!0,value:pe.indexOf("CLOSING")});Object.defineProperty(O,"CLOSED",{enumerable:!0,value:pe.indexOf("CLOSED")});Object.defineProperty(O.prototype,"CLOSED",{enumerable:!0,value:pe.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(O.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(O.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[yn])return e[du];return null},set(e){for(let r of this.listeners(t))if(r[yn]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[yn]:!0})}})});O.prototype.addEventListener=hu;O.prototype.removeEventListener=pu;Ii.exports=O;function ki(t,e,r,s){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:lu,protocolVersion:_n[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=n.autoPong,t._closeTimeout=n.closeTimeout,!_n.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${_n.join(", ")})`);let o;if(e instanceof gn)o=e;else try{o=new gn(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),t._url=o.href;let i=o.protocol==="wss:",a=o.protocol==="ws+unix:",c;if(o.protocol!=="ws:"&&!i&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"),c){let b=new SyntaxError(c);if(t._redirects===0)throw b;Fr(t,b);return}let l=i?443:80,u=nu(16).toString("base64"),d=i?tu.request:ru.request,p=new Set,h;if(n.createConnection=n.createConnection||(i?wu:bu),n.defaultPort=n.defaultPort||l,n.port=o.port||l,n.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},n.path=o.pathname+o.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(h=new Ee({...n.perMessageDeflate,isServer:!1,maxPayload:n.maxPayload}),n.headers["Sec-WebSocket-Extensions"]=mu({[Ee.extensionName]:h.offer()})),r.length){for(let b of r){if(typeof b!="string"||!_u.test(b)||p.has(b))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(b)}n.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(o.username||o.password)&&(n.auth=`${o.username}:${o.password}`),a){let b=n.path.split(":");n.socketPath=b[0],n.path=b[1]}let g;if(n.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=i,t._originalHostOrSocketPath=a?n.socketPath:o.host;let b=s&&s.headers;if(s={...s,headers:{}},b)for(let[S,v]of Object.entries(b))s.headers[S.toLowerCase()]=v}else if(t.listenerCount("redirect")===0){let b=a?t._originalIpc?n.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!b||t._originalSecure&&!i)&&(delete n.headers.authorization,delete n.headers.cookie,b||delete n.headers.host,n.auth=void 0)}n.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),g=t._req=d(n),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(n);n.timeout&&g.on("timeout",()=>{Y(t,g,"Opening handshake has timed out")}),g.on("error",b=>{g===null||g[Ei]||(g=t._req=null,Fr(t,b))}),g.on("response",b=>{let S=b.headers.location,v=b.statusCode;if(S&&n.followRedirects&&v>=300&&v<400){if(++t._redirects>n.maxRedirects){Y(t,g,"Maximum redirects exceeded");return}g.abort();let k;try{k=new gn(S,e)}catch{let N=new SyntaxError(`Invalid URL: ${S}`);Fr(t,N);return}ki(t,k,r,s)}else t.emit("unexpected-response",g,b)||Y(t,g,`Unexpected server response: ${b.statusCode}`)}),g.on("upgrade",(b,S,v)=>{if(t.emit("upgrade",b),t.readyState!==O.CONNECTING)return;g=t._req=null;let k=b.headers.upgrade;if(k===void 0||k.toLowerCase()!=="websocket"){Y(t,S,"Invalid Upgrade header");return}let U=ou("sha1").update(u+uu).digest("base64");if(b.headers["sec-websocket-accept"]!==U){Y(t,S,"Invalid Sec-WebSocket-Accept header");return}let N=b.headers["sec-websocket-protocol"],V;if(N!==void 0?p.size?p.has(N)||(V="Server sent an invalid subprotocol"):V="Server sent a subprotocol but none was requested":p.size&&(V="Server sent no subprotocol"),V){Y(t,S,V);return}N&&(t._protocol=N);let W=b.headers["sec-websocket-extensions"];if(W!==void 0){if(!h){Y(t,S,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let x;try{x=gu(W)}catch{Y(t,S,"Invalid Sec-WebSocket-Extensions header");return}let $=Object.keys(x);if($.length!==1||$[0]!==Ee.extensionName){Y(t,S,"Server indicated an extension that was not requested");return}try{h.accept(x[Ee.extensionName])}catch{Y(t,S,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Ee.extensionName]=h}t.setSocket(S,v,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(g,t):g.end()}function Fr(t,e){t._readyState=O.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function bu(t){return t.path=t.socketPath,Si.connect(t)}function wu(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Si.isIP(t.host)?"":t.host),su.connect(t)}function Y(t,e,r){t._readyState=O.CLOSING;let s=new Error(r);Error.captureStackTrace(s,Y),e.setHeader?(e[Ei]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Fr,t,s)):(e.destroy(s),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function bn(t,e,r){if(e){let s=cu(e)?e.size:yu(e).length;t._socket?t._sender._bufferedBytes+=s:t._bufferedAmount+=s}if(r){let s=new Error(`WebSocket is not open: readyState ${t.readyState} (${pe[t.readyState]})`);process.nextTick(r,s)}}function xu(t,e){let r=this[j];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[j]!==void 0&&(r._socket.removeListener("data",Hr),process.nextTick(Ri,r._socket),t===1005?r.close():r.close(t,e))}function Su(){let t=this[j];t.isPaused||t._socket.resume()}function vu(t){let e=this[j];e._socket[j]!==void 0&&(e._socket.removeListener("data",Hr),process.nextTick(Ri,e._socket),e.close(t[fu])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function xi(){this[j].emitClose()}function Eu(t,e){this[j].emit("message",t,e)}function ku(t){let e=this[j];e._autoPong&&e.pong(t,!this._isServer,vi),e.emit("ping",t)}function Ru(t){this[j].emit("pong",t)}function Ri(t){t.resume()}function Pu(t){let e=this[j];e.readyState!==O.CLOSED&&(e.readyState===O.OPEN&&(e._readyState=O.CLOSING,Pi(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Pi(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Ti(){let t=this[j];if(this.removeListener("close",Ti),this.removeListener("data",Hr),this.removeListener("end",Ai),t._readyState=O.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[j]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",xi),t._receiver.on("finish",xi))}function Hr(t){this[j]._receiver.write(t)||this.pause()}function Ai(){let t=this[j];t._readyState=O.CLOSING,t._receiver.end(),this.end()}function Oi(){let t=this[j];this.removeListener("error",Oi),this.on("error",vi),t&&(t._readyState=O.CLOSING,this.destroy())}});var Li=J((pp,Ni)=>{"use strict";var hp=Wr(),{Duplex:Tu}=C("stream");function Mi(t){t.emit("close")}function Au(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ci(t){this.removeListener("error",Ci),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Ou(t,e){let r=!0,s=new Tu({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,i){let a=!i&&s._readableState.objectMode?o.toString():o;s.push(a)||t.pause()}),t.once("error",function(o){s.destroyed||(r=!1,s.destroy(o))}),t.once("close",function(){s.destroyed||s.push(null)}),s._destroy=function(n,o){if(t.readyState===t.CLOSED){o(n),process.nextTick(Mi,s);return}let i=!1;t.once("error",function(c){i=!0,o(c)}),t.once("close",function(){i||o(n),process.nextTick(Mi,s)}),r&&t.terminate()},s._final=function(n){if(t.readyState===t.CONNECTING){t.once("open",function(){s._final(n)});return}t._socket!==null&&(t._socket._writableState.finished?(n(),s._readableState.endEmitted&&s.destroy()):(t._socket.once("finish",function(){n()}),t.close()))},s._read=function(){t.isPaused&&t.resume()},s._write=function(n,o,i){if(t.readyState===t.CONNECTING){t.once("open",function(){s._write(n,o,i)});return}t.send(n,i)},s.on("end",Au),s.on("error",Ci),s}Ni.exports=Ou});var wn=J((mp,$i)=>{"use strict";var{tokenChars:Iu}=ct();function Mu(t){let e=new Set,r=-1,s=-1,n=0;for(n;n<t.length;n++){let i=t.charCodeAt(n);if(s===-1&&Iu[i]===1)r===-1&&(r=n);else if(n!==0&&(i===32||i===9))s===-1&&r!==-1&&(s=n);else if(i===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${n}`);s===-1&&(s=n);let a=t.slice(r,s);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),r=s=-1}else throw new SyntaxError(`Unexpected character at index ${n}`)}if(r===-1||s!==-1)throw new SyntaxError("Unexpected end of input");let o=t.slice(r,n);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}$i.exports={parse:Mu}});var Hi=J((yp,Fi)=>{"use strict";var Cu=C("events"),Vr=C("http"),{Duplex:gp}=C("stream"),{createHash:Nu}=C("crypto"),ji=Ur(),De=at(),Lu=wn(),$u=Wr(),{CLOSE_TIMEOUT:ju,GUID:Bu,kWebSocket:Du}=de(),Uu=/^[+/0-9A-Za-z]{22}==$/,Bi=0,Di=1,qi=2,xn=class extends Cu{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:ju,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:$u,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Vr.createServer((s,n)=>{let o=Vr.STATUS_CODES[426];n.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),n.end(o)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let s=this.emit.bind(this,"connection");this._removeListeners=qu(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(n,o,i)=>{this.handleUpgrade(n,o,i,s)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Bi}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===qi){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Zt,this);return}if(e&&this.once("close",e),this._state!==Di)if(this._state=Di,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Zt,this):process.nextTick(Zt,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Zt(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,s,n){r.on("error",Ui);let o=e.headers["sec-websocket-key"],i=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ue(this,e,r,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){Ue(this,e,r,400,"Invalid Upgrade header");return}if(o===void 0||!Uu.test(o)){Ue(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Ue(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){er(r,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=Lu.parse(c)}catch{Ue(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let p=new De({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=ji.parse(u);h[De.extensionName]&&(p.accept(h[De.extensionName]),d[De.extensionName]=p)}catch{Ue(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let p={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(p,(h,g,b,S)=>{if(!h)return er(r,g||401,b,S);this.completeUpgrade(d,o,l,e,r,s,n)});return}if(!this.options.verifyClient(p))return er(r,401)}this.completeUpgrade(d,o,l,e,r,s,n)}completeUpgrade(e,r,s,n,o,i,a){if(!o.readable||!o.writable)return o.destroy();if(o[Du])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Bi)return er(o,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Nu("sha1").update(r+Bu).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(s.size){let d=this.options.handleProtocols?this.options.handleProtocols(s,n):s.values().next().value;d&&(l.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[De.extensionName]){let d=e[De.extensionName].params,p=ji.format({[De.extensionName]:[d]});l.push(`Sec-WebSocket-Extensions: ${p}`),u._extensions=e}this.emit("headers",l,n),o.write(l.concat(`\r
|
|
3
3
|
`).join(`\r
|
|
4
|
-
`)),o.removeListener("error",Ui),u.setSocket(o,i,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Zt,this)})),a(u,n)}};Fi.exports=
|
|
4
|
+
`)),o.removeListener("error",Ui),u.setSocket(o,i,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Zt,this)})),a(u,n)}};Fi.exports=xn;function qu(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let s of Object.keys(e))t.removeListener(s,e[s])}}function Zt(t){t._state=qi,t.emit("close")}function Ui(){this.destroy()}function er(t,e,r,s){r=r||Vr.STATUS_CODES[e],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Vr.STATUS_CODES[e]}\r
|
|
5
5
|
`+Object.keys(s).map(n=>`${n}: ${s[n]}`).join(`\r
|
|
6
6
|
`)+`\r
|
|
7
7
|
\r
|
|
8
|
-
`+r)}function Ue(t,e,r,s,n,o){if(t.listenerCount("wsClientError")){let i=new Error(n);Error.captureStackTrace(i,Ue),t.emit("wsClientError",i,r,e)}else er(r,s,n,o)}});import{stat as Oh}from"fs/promises";import{dirname as Ih,join as $c}from"path";import{createServer as Vc}from"http";import{Http2ServerRequest as To,constants as Gc}from"http2";import{Http2ServerRequest as Vs}from"http2";import{Readable as Ro}from"stream";import sl from"crypto";var Ne=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},Kc=t=>t instanceof Ne?t:new Ne(t.message,{cause:t}),zc=global.Request,Gt=class extends zc{constructor(t,e){typeof t=="object"&&st in t&&(t=t[st]()),typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},Jc=t=>{let e=[],r=t.rawHeaders;for(let s=0;s<r.length;s+=2){let{[s]:n,[s+1]:o}=r;n.charCodeAt(0)!==58&&e.push([n,o])}return new Headers(e)},Ao=Symbol("wrapBodyStream"),Yc=(t,e,r,s,n)=>{let o={method:t,headers:r,signal:n.signal};if(t==="TRACE"){o.method="GET";let i=new Gt(e,o);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(t==="GET"||t==="HEAD"))if("rawBody"in s&&s.rawBody instanceof Buffer)o.body=new ReadableStream({start(i){i.enqueue(s.rawBody),i.close()}});else if(s[Ao]){let i;o.body=new ReadableStream({async pull(a){try{i||=Ro.toWeb(s).getReader();let{done:c,value:l}=await i.read();c?a.close():a.enqueue(l)}catch(c){a.error(c)}}})}else o.body=Ro.toWeb(s);return new Gt(e,o)},st=Symbol("getRequestCache"),Oo=Symbol("requestCache"),Or=Symbol("incomingKey"),Ir=Symbol("urlKey"),Xc=Symbol("headersKey"),rt=Symbol("abortControllerKey"),Qc=Symbol("getAbortController"),Kt={get method(){return this[Or].method||"GET"},get url(){return this[Ir]},get headers(){return this[Xc]||=Jc(this[Or])},[Qc](){return this[st](),this[rt]},[st](){return this[rt]||=new AbortController,this[Oo]||=Yc(this.method,this[Ir],this.headers,this[Or],this[rt])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(t=>{Object.defineProperty(Kt,t,{get(){return this[st]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Kt,t,{value:function(){return this[st]()[t]()}})});Object.defineProperty(Kt,Symbol.for("nodejs.util.inspect.custom"),{value:function(t,e,r){let s={method:this.method,url:this.url,headers:this.headers,nativeRequest:this[Oo]};return`Request (lightweight) ${r(s,{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Kt,Gt.prototype);var Zc=(t,e)=>{let r=Object.create(Kt);r[Or]=t;let s=t.url||"";if(s[0]!=="/"&&(s.startsWith("http://")||s.startsWith("https://"))){if(t instanceof Vs)throw new Ne("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(s);r[Ir]=a.href}catch(a){throw new Ne("Invalid absolute URL",{cause:a})}return r}let n=(t instanceof Vs?t.authority:t.headers.host)||e;if(!n)throw new Ne("Missing host header");let o;if(t instanceof Vs){if(o=t.scheme,!(o==="http"||o==="https"))throw new Ne("Unsupported scheme")}else o=t.socket&&t.socket.encrypted?"https":"http";let i=new URL(`${o}://${n}${s}`);if(i.hostname.length!==n.length&&i.hostname!==n.replace(/:\d+$/,""))throw new Ne("Invalid host header");return r[Ir]=i.href,r},Ks=Symbol("responseCache"),tt=Symbol("getResponseCache"),Le=Symbol("cache"),Ys=global.Response,nt=class Io{#e;#t;[tt](){return delete this[Le],this[Ks]||=new Ys(this.#e,this.#t)}constructor(e,r){let s;if(this.#e=e,r instanceof Io){let n=r[Ks];if(n){this.#t=n,this[tt]();return}else this.#t=r.#t,s=new Headers(r.#t.headers)}else this.#t=r;(typeof e=="string"||typeof e?.getReader<"u"||e instanceof Blob||e instanceof Uint8Array)&&(this[Le]=[r?.status||200,e,s||r?.headers])}get headers(){let e=this[Le];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":"text/plain; charset=UTF-8"})),e[2]):this[tt]().headers}get status(){return this[Le]?.[0]??this[tt]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(nt.prototype,t,{get(){return this[tt]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(nt.prototype,t,{value:function(){return this[tt]()[t]()}})});Object.defineProperty(nt.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(t,e,r){let s={status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[Ks]};return`Response (lightweight) ${r(s,{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(nt,Ys);Object.setPrototypeOf(nt.prototype,Ys.prototype);async function el(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Mo(t,e,r){let s=a=>{t.cancel(a).catch(()=>{})};return e.on("close",s),e.on("error",s),(r??t.read()).then(i,n),t.closed.finally(()=>{e.off("close",s),e.off("error",s)});function n(a){a&&e.destroy(a)}function o(){t.read().then(i,n)}function i({done:a,value:c}){try{if(a)e.end();else if(!e.write(c))e.once("drain",o);else return t.read().then(i,n)}catch(l){n(l)}}}function tl(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:Mo(t.getReader(),e)}var zs=t=>{let e={};t instanceof Headers||(t=new Headers(t??void 0));let r=[];for(let[s,n]of t)s==="set-cookie"?r.push(n):e[s]=n;return r.length>0&&(e["set-cookie"]=r),e["content-type"]??="text/plain; charset=UTF-8",e},rl="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=sl);var Xs=Symbol("outgoingEnded"),Po=Symbol("incomingDraining"),nl=500,ol=64*1024*1024,Gs=t=>{let e=t;if(t.destroyed||e[Po])return;if(e[Po]=!0,t instanceof To){try{t.stream?.close?.(Gc.NGHTTP2_NO_ERROR)}catch{}return}let r=0,s=()=>{clearTimeout(o),t.off("data",i),t.off("end",s),t.off("error",s)},n=()=>{s();let a=t.socket;a&&!a.destroyed&&a.destroySoon()},o=setTimeout(n,nl);o.unref?.();let i=a=>{r+=a.length,r>ol&&n()};t.on("data",i),t.on("end",s),t.on("error",s),t.resume()},il=()=>new Response(null,{status:400}),Co=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),Js=(t,e)=>{let r=t instanceof Error?t:new Error("unknown error",{cause:t});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(t),e.headersSent||e.writeHead(500,{"Content-Type":"text/plain"}),e.end(`Error: ${r.message}`),e.destroy(r))},No=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},Lo=async(t,e)=>{let[r,s,n]=t[Le],o=!1;if(!n)n={"content-type":"text/plain; charset=UTF-8"};else if(n instanceof Headers)o=n.has("content-length"),n=zs(n);else if(Array.isArray(n)){let i=new Headers(n);o=i.has("content-length"),n=zs(i)}else for(let i in n)if(i.length===14&&i.toLowerCase()==="content-length"){o=!0;break}o||(typeof s=="string"?n["Content-Length"]=Buffer.byteLength(s):s instanceof Uint8Array?n["Content-Length"]=s.byteLength:s instanceof Blob&&(n["Content-Length"]=s.size)),e.writeHead(r,n),typeof s=="string"||s instanceof Uint8Array?e.end(s):s instanceof Blob?e.end(new Uint8Array(await s.arrayBuffer())):(No(e),await tl(s,e)?.catch(i=>Js(i,e))),e[Xs]?.()},al=t=>typeof t.then=="function",cl=async(t,e,r={})=>{if(al(t))if(r.errorHandler)try{t=await t}catch(n){let o=await r.errorHandler(n);if(!o)return;t=o}else t=await t.catch(Co);if(Le in t)return Lo(t,e);let s=zs(t.headers);if(t.body){let n=t.body.getReader(),o=[],i=!1,a;if(s["transfer-encoding"]!=="chunked"){let c=2;for(let l=0;l<c;l++){a||=n.read();let u=await el(a).catch(d=>{console.error(d),i=!0});if(!u){if(l===1){await new Promise(d=>setTimeout(d)),c=3;continue}break}if(a=void 0,u.value&&o.push(u.value),u.done){i=!0;break}}i&&!("content-length"in s)&&(s["content-length"]=o.reduce((l,u)=>l+u.length,0))}e.writeHead(t.status,s),o.forEach(c=>{e.write(c)}),i?e.end():(o.length===0&&No(e),await Mo(n,e,a))}else s[rl]||(e.writeHead(t.status,s),e.end());e[Xs]?.()},ll=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==Gt&&(Object.defineProperty(global,"Request",{value:Gt}),Object.defineProperty(global,"Response",{value:nt})),async(s,n)=>{let o,i;try{i=Zc(s,e.hostname);let a=!r||s.method==="GET"||s.method==="HEAD";if(a||(s[Ao]=!0,s.on("end",()=>{a=!0}),s instanceof To&&(n[Xs]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{Gs(s)})})}),n.on("finish",()=>{a||Gs(s)})),n.on("close",()=>{i[rt]&&(s.errored?i[rt].abort(s.errored.toString()):n.writableFinished||i[rt].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{Gs(s)})})}),o=t(i,{incoming:s,outgoing:n}),Le in o)return Lo(o,n)}catch(a){if(o)return Js(a,n);if(e.errorHandler){if(o=await e.errorHandler(i?a:Kc(a)),!o)return}else i?o=Co(a):o=il()}try{return await cl(o,n,e)}catch(a){return Js(a,n)}}},ul=t=>{let e=t.fetch,r=ll(e,{hostname:t.hostname,overrideGlobalObjects:t.overrideGlobalObjects,autoCleanupIncoming:t.autoCleanupIncoming});return(t.createServer||Vc)(t.serverOptions||{},r)},$o=(t,e)=>{let r=ul(t);return r.listen(t?.port??3e3,t.hostname,()=>{let s=r.address();e&&e(s)}),r};var jo=(t,e=fl)=>{let r=/\.([a-zA-Z0-9]+?)$/,s=t.match(r);if(!s)return;let n=e[s[1].toLowerCase()];return n&&n.startsWith("text")&&(n+="; charset=utf-8"),n};var dl={aac:"audio/aac",avi:"video/x-msvideo",avif:"image/avif",av1:"video/av1",bin:"application/octet-stream",bmp:"image/bmp",css:"text/css",csv:"text/csv",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",gz:"application/gzip",htm:"text/html",html:"text/html",ico:"image/x-icon",ics:"text/calendar",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",map:"application/json",mid:"audio/x-midi",midi:"audio/x-midi",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",pdf:"application/pdf",png:"image/png",rtf:"application/rtf",svg:"image/svg+xml",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",wasm:"application/wasm",webm:"video/webm",weba:"audio/webm",webmanifest:"application/manifest+json",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xml:"application/xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2",gltf:"model/gltf+json",glb:"model/gltf-binary"},fl=dl;import{createReadStream as Bo,statSync as hl,existsSync as pl}from"fs";import{join as Do}from"path";import{versions as ml}from"process";import{Readable as gl}from"stream";var yl=/^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i,Zs={br:".br",zstd:".zst",gzip:".gz"},_l=Object.keys(Zs),bl=()=>{let[t,e]=ml.node.split(".").map(r=>parseInt(r));return t>=23||t===22&&e>=7||t===20&&e>=18},wl=bl(),Uo=t=>wl?gl.toWeb(t):new ReadableStream({start(r){t.on("data",s=>{r.enqueue(s)}),t.on("error",s=>{r.error(s)}),t.on("end",()=>{r.close()})},cancel(){t.destroy()}}),Qs=t=>{let e;try{e=hl(t)}catch{}return e},xl=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},Sl=t=>xl(t,decodeURI),en=(t={root:""})=>{let e=t.root||"",r=t.path;return e!==""&&!pl(e)&&console.error(`serveStatic: root path '${e}' is not found, are you sure it's correct?`),async(s,n)=>{if(s.finalized)return n();let o;if(r)o=r;else try{if(o=Sl(s.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}/.test(o))throw new Error}catch{return await t.onNotFound?.(s.req.path,s),n()}let i=Do(e,!r&&t.rewriteRequestPath?t.rewriteRequestPath(o,s):o),a=Qs(i);if(a&&a.isDirectory()){let p=t.index??"index.html";i=Do(i,p),a=Qs(i)}if(!a)return await t.onNotFound?.(i,s),n();let c=jo(i);if(s.header("Content-Type",c||"application/octet-stream"),t.precompressed&&(!c||yl.test(c))){let p=new Set(s.req.header("Accept-Encoding")?.split(",").map(h=>h.trim()));for(let h of _l){if(!p.has(h))continue;let g=Qs(i+Zs[h]);if(g){s.header("Content-Encoding",h),s.header("Vary","Accept-Encoding",{append:!0}),a=g,i=i+Zs[h];break}}}let l,u=a.size,d=s.req.header("range")||"";if(s.req.method=="HEAD"||s.req.method=="OPTIONS")s.header("Content-Length",u.toString()),s.status(200),l=s.body(null);else if(!d)s.header("Content-Length",u.toString()),l=s.body(Uo(Bo(i)),200);else{s.header("Accept-Ranges","bytes"),s.header("Date",a.birthtime.toUTCString());let p=d.replace(/bytes=/,"").split("-",2),h=parseInt(p[0],10)||0,g=parseInt(p[1],10)||u-1;u<g-h+1&&(g=u-1);let b=g-h+1,S=Bo(i,{start:h,end:g});s.header("Content-Length",b.toString()),s.header("Content-Range",`bytes ${h}-${g}/${a.size}`),l=s.body(Uo(S),206)}return await t.onFound?.(i,s),l}};var Fu=Se(Li(),1),Hu=Se(Ur(),1),Wu=Se(at(),1),Vu=Se(fn(),1),Gu=Se(mn(),1),Ku=Se(xn(),1),zu=Se(Wr(),1),vn=Se(Hi(),1);var En=(t,e,r)=>(s,n)=>{let o=-1;return i(0);async function i(a){if(a<=o)throw new Error("next() called multiple times");o=a;let c,l=!1,u;if(t[a]?(u=t[a][0][0],s.req.routeIndex=a):u=a===t.length&&n||void 0,u)try{c=await u(s,()=>i(a+1))}catch(d){if(d instanceof Error&&e)s.error=d,c=await e(d,s),l=!0;else throw d}else s.finalized===!1&&r&&(c=await r(s));return c&&(s.finalized===!1||l)&&(s.res=c),s}};var Wi=Symbol();var Vi=async(t,e=Object.create(null))=>{let{all:r=!1,dot:s=!1}=e,o=(t instanceof Gr?t.raw.headers:t.headers).get("Content-Type");return o?.startsWith("multipart/form-data")||o?.startsWith("application/x-www-form-urlencoded")?Ju(t,{all:r,dot:s}):{}};async function Ju(t,e){let r=await t.formData();return r?Yu(r,e):{}}function Yu(t,e){let r=Object.create(null);return t.forEach((s,n)=>{e.all||n.endsWith("[]")?Xu(r,n,s):r[n]=s}),e.dot&&Object.entries(r).forEach(([s,n])=>{s.includes(".")&&(Qu(r,s,n),delete r[s])}),r}var Xu=(t,e,r)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(r):t[e]=[t[e],r]:e.endsWith("[]")?t[e]=[r]:t[e]=r},Qu=(t,e,r)=>{if(/(?:^|\.)__proto__\./.test(e))return;let s=t,n=e.split(".");n.forEach((o,i)=>{i===n.length-1?s[o]=r:((!s[o]||typeof s[o]!="object"||Array.isArray(s[o])||s[o]instanceof File)&&(s[o]=Object.create(null)),s=s[o])})};var Rn=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},Gi=t=>{let{groups:e,path:r}=Zu(t),s=Rn(r);return ed(s,e)},Zu=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,s)=>{let n=`@${s}`;return e.push([n,r]),n}),{groups:e,path:t}},ed=(t,e)=>{for(let r=e.length-1;r>=0;r--){let[s]=e[r];for(let n=t.length-1;n>=0;n--)if(t[n].includes(s)){t[n]=t[n].replace(s,e[r][1]);break}}return t},Kr={},Ki=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let s=`${t}#${e}`;return Kr[s]||(r[2]?Kr[s]=e&&e[0]!==":"&&e[0]!=="*"?[s,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:Kr[s]=[t,r[1],!0]),Kr[s]}return null},zr=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},td=t=>zr(t,decodeURI),Pn=t=>{let e=t.url,r=e.indexOf("/",e.indexOf(":")+4),s=r;for(;s<e.length;s++){let n=e.charCodeAt(s);if(n===37){let o=e.indexOf("?",s),i=e.indexOf("#",s),a=o===-1?i===-1?void 0:i:i===-1?o:Math.min(o,i),c=e.slice(r,a);return td(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(n===63||n===35)break}return e.slice(r,s)};var zi=t=>{let e=Pn(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},qe=(t,e,...r)=>(r.length&&(e=qe(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),Jr=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),r=[],s="";return e.forEach(n=>{if(n!==""&&!/\:/.test(n))s+="/"+n;else if(/\:/.test(n))if(/\?/.test(n)){r.length===0&&s===""?r.push("/"):r.push(s);let o=n.replace("?","");s+="/"+o,r.push(s)}else s+="/"+n}),r.filter((n,o,i)=>i.indexOf(n)===o)},kn=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?zr(t,Tn):t):t,Ji=(t,e,r)=>{let s;if(!r&&e&&!/[%+]/.test(e)){let i=t.indexOf("?",8);if(i===-1)return;for(t.startsWith(e,i+1)||(i=t.indexOf(`&${e}`,i+1));i!==-1;){let a=t.charCodeAt(i+e.length+1);if(a===61){let c=i+e.length+2,l=t.indexOf("&",c);return kn(t.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";i=t.indexOf(`&${e}`,i+1)}if(s=/[%+]/.test(t),!s)return}let n={};s??=/[%+]/.test(t);let o=t.indexOf("?",8);for(;o!==-1;){let i=t.indexOf("&",o+1),a=t.indexOf("=",o);a>i&&i!==-1&&(a=-1);let c=t.slice(o+1,a===-1?i===-1?void 0:i:a);if(s&&(c=kn(c)),o=i,c==="")continue;let l;a===-1?l="":(l=t.slice(a+1,i===-1?void 0:i),s&&(l=kn(l))),r?(n[c]&&Array.isArray(n[c])||(n[c]=[]),n[c].push(l)):n[c]??=l}return e?n[e]:n},Yi=Ji,Xi=(t,e)=>Ji(t,e,!0),Tn=decodeURIComponent;var Qi=t=>zr(t,Tn),Gr=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(t,e="/",r=[[]]){this.raw=t,this.path=e,this.#t=r,this.#e={}}param(t){return t?this.#s(t):this.#o()}#s(t){let e=this.#t[0][this.routeIndex][1][t],r=this.#r(e);return r&&/\%/.test(r)?Qi(r):r}#o(){let t={},e=Object.keys(this.#t[0][this.routeIndex][1]);for(let r of e){let s=this.#r(this.#t[0][this.routeIndex][1][r]);s!==void 0&&(t[r]=/\%/.test(s)?Qi(s):s)}return t}#r(t){return this.#t[1]?this.#t[1][t]:t}query(t){return Yi(this.url,t)}queries(t){return Xi(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e={};return this.raw.headers.forEach((r,s)=>{e[s]=r}),e}async parseBody(t){return Vi(this,t)}#n=t=>{let{bodyCache:e,raw:r}=this,s=e[t];if(s)return s;let n=Object.keys(e)[0];return n?e[n].then(o=>(n==="json"&&(o=JSON.stringify(o)),new Response(o)[t]())):e[t]=r[t]()};json(){return this.#n("text").then(t=>JSON.parse(t))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(t,e){this.#e[t]=e}valid(t){return this.#e[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[Wi](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,t]])=>t)}get routePath(){return this.#t[0].map(([[,t]])=>t)[this.routeIndex].path}};var Yr={Stringify:1,BeforeStream:2,Stream:3},rd=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r};var tr=async(t,e,r,s,n)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let o=t.callbacks;if(!o?.length)return Promise.resolve(t);n?n[0]+=t:n=[t];let i=Promise.all(o.map(a=>a({phase:e,buffer:n,context:s}))).then(a=>Promise.all(a.filter(Boolean).map(c=>tr(c,e,!1,s,n))).then(()=>n[0]));return r?rd(await i,o):i};var Zi="text/plain; charset=UTF-8",An=(t,e)=>({"Content-Type":t,...e}),rr=(t,e)=>new Response(t,e),ea=class{#e;#t;env={};#s;finalized=!1;error;#o;#r;#n;#a;#l;#h;#c;#d;#p;constructor(t,e){this.#e=t,e&&(this.#r=e.executionCtx,this.env=e.env,this.#h=e.notFoundHandler,this.#p=e.path,this.#d=e.matchResult)}get req(){return this.#t??=new Gr(this.#e,this.#p,this.#d),this.#t}get event(){if(this.#r&&"respondWith"in this.#r)return this.#r;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#r)return this.#r;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=rr(null,{headers:this.#c??=new Headers})}set res(t){if(this.#n&&t){t=rr(t.body,t);for(let[e,r]of this.#n.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let s=this.#n.headers.getSetCookie();t.headers.delete("set-cookie");for(let n of s)t.headers.append("set-cookie",n)}else t.headers.set(e,r)}this.#n=t,this.finalized=!0}render=(...t)=>(this.#l??=e=>this.html(e),this.#l(...t));setLayout=t=>this.#a=t;getLayout=()=>this.#a;setRenderer=t=>{this.#l=t};header=(t,e,r)=>{this.finalized&&(this.#n=rr(this.#n.body,this.#n));let s=this.#n?this.#n.headers:this.#c??=new Headers;e===void 0?s.delete(t):r?.append?s.append(t,e):s.set(t,e)};status=t=>{this.#o=t};set=(t,e)=>{this.#s??=new Map,this.#s.set(t,e)};get=t=>this.#s?this.#s.get(t):void 0;get var(){return this.#s?Object.fromEntries(this.#s):{}}#f(t,e,r){let s=this.#n?new Headers(this.#n.headers):this.#c??new Headers;if(typeof e=="object"&&"headers"in e){let o=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[i,a]of o)i.toLowerCase()==="set-cookie"?s.append(i,a):s.set(i,a)}if(r)for(let[o,i]of Object.entries(r))if(typeof i=="string")s.set(o,i);else{s.delete(o);for(let a of i)s.append(o,a)}let n=typeof e=="number"?e:e?.status??this.#o;return rr(t,{status:n,headers:s})}newResponse=(...t)=>this.#f(...t);body=(t,e,r)=>this.#f(t,e,r);text=(t,e,r)=>!this.#c&&!this.#o&&!e&&!r&&!this.finalized?new Response(t):this.#f(t,e,An(Zi,r));json=(t,e,r)=>this.#f(JSON.stringify(t),e,An("application/json",r));html=(t,e,r)=>{let s=n=>this.#f(n,e,An("text/html; charset=UTF-8",r));return typeof t=="object"?tr(t,Yr.Stringify,!1,{}).then(s):s(t)};redirect=(t,e)=>{let r=String(t);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,e??302)};notFound=()=>(this.#h??=()=>rr(),this.#h(this))};var I="ALL",ta="all",ra=["get","post","put","delete","options","patch"],Xr="Can not add a route since the matcher is already built.",Qr=class extends Error{};var sa="__COMPOSED_HANDLER";var sd=t=>t.text("404 Not Found",404),na=(t,e)=>{if("getResponse"in t){let r=t.getResponse();return e.newResponse(r.body,r)}return console.error(t),e.text("Internal Server Error",500)},oa=class ia{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(e={}){[...ra,ta].forEach(o=>{this[o]=(i,...a)=>(typeof i=="string"?this.#e=i:this.#o(o,this.#e,i),a.forEach(c=>{this.#o(o,this.#e,c)}),this)}),this.on=(o,i,...a)=>{for(let c of[i].flat()){this.#e=c;for(let l of[o].flat())a.map(u=>{this.#o(l.toUpperCase(),this.#e,u)})}return this},this.use=(o,...i)=>(typeof o=="string"?this.#e=o:(this.#e="*",i.unshift(o)),i.forEach(a=>{this.#o(I,this.#e,a)}),this);let{strict:s,...n}=e;Object.assign(this,n),this.getPath=s??!0?e.getPath??Pn:zi}#t(){let e=new ia({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#s=this.#s,e.routes=this.routes,e}#s=sd;errorHandler=na;route(e,r){let s=this.basePath(e);return r.routes.map(n=>{let o;r.errorHandler===na?o=n.handler:(o=async(i,a)=>(await En([],r.errorHandler)(i,()=>n.handler(i,a))).res,o[sa]=n.handler),s.#o(n.method,n.path,o)}),this}basePath(e){let r=this.#t();return r._basePath=qe(this._basePath,e),r}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#s=e,this);mount(e,r,s){let n,o;s&&(typeof s=="function"?o=s:(o=s.optionHandler,s.replaceRequest===!1?n=c=>c:n=s.replaceRequest));let i=o?c=>{let l=o(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};n||=(()=>{let c=qe(this._basePath,e),l=c==="/"?0:c.length;return u=>{let d=new URL(u.url);return d.pathname=d.pathname.slice(l)||"/",new Request(d,u)}})();let a=async(c,l)=>{let u=await r(n(c.req.raw),...i(c));if(u)return u;await l()};return this.#o(I,qe(e,"*"),a),this}#o(e,r,s){e=e.toUpperCase(),r=qe(this._basePath,r);let n={basePath:this._basePath,path:r,method:e,handler:s};this.router.add(e,r,[s,n]),this.routes.push(n)}#r(e,r){if(e instanceof Error)return this.errorHandler(e,r);throw e}#n(e,r,s,n){if(n==="HEAD")return(async()=>new Response(null,await this.#n(e,r,s,"GET")))();let o=this.getPath(e,{env:s}),i=this.router.match(n,o),a=new ea(e,{path:o,matchResult:i,env:s,executionCtx:r,notFoundHandler:this.#s});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#s(a)})}catch(u){return this.#r(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#s(a))).catch(u=>this.#r(u,a)):l??this.#s(a)}let c=En(i[0],this.errorHandler,this.#s);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#r(l,a)}})()}fetch=(e,...r)=>this.#n(e,r[1],r[0],e.method);request=(e,r,s,n)=>e instanceof Request?this.fetch(r?new Request(e,r):e,s,n):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${qe("/",e)}`,r),s,n));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#n(e.request,e,void 0,e.request.method))})}};var Zr=[];function On(t,e){let r=this.buildAllMatchers(),s=((n,o)=>{let i=r[n]||r[I],a=i[2][o];if(a)return a;let c=o.match(i[0]);if(!c)return[[],Zr];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=s,s(t,e)}var es="[^/]+",sr=".*",nr="(?:|/.*)",Fe=Symbol(),nd=new Set(".\\+*[^]$()");function od(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===sr||t===nr?1:e===sr||e===nr?-1:t===es?1:e===es?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var aa=class In{#e;#t;#s=Object.create(null);insert(e,r,s,n,o){if(e.length===0){if(this.#e!==void 0)throw Fe;if(o)return;this.#e=r;return}let[i,...a]=e,c=i==="*"?a.length===0?["","",sr]:["","",es]:i==="/*"?["","",nr]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],d=c[2]||es;if(u&&c[2]&&(d===".*"||(d=d.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(d))))throw Fe;if(l=this.#s[d],!l){if(Object.keys(this.#s).some(p=>p!==sr&&p!==nr))throw Fe;if(o)return;l=this.#s[d]=new In,u!==""&&(l.#t=n.varIndex++)}!o&&u!==""&&s.push([u,l.#t])}else if(l=this.#s[i],!l){if(Object.keys(this.#s).some(u=>u.length>1&&u!==sr&&u!==nr))throw Fe;if(o)return;l=this.#s[i]=new In}l.insert(a,r,s,n,o)}buildRegExpStr(){let r=Object.keys(this.#s).sort(od).map(s=>{let n=this.#s[s];return(typeof n.#t=="number"?`(${s})@${n.#t}`:nd.has(s)?`\\${s}`:s)+n.buildRegExpStr()});return typeof this.#e=="number"&&r.unshift(`#${this.#e}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var ca=class{#e={varIndex:0};#t=new aa;insert(t,e,r){let s=[],n=[];for(let i=0;;){let a=!1;if(t=t.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return n[i]=[l,c],i++,a=!0,l}),!a)break}let o=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=n.length-1;i>=0;i--){let[a]=n[i];for(let c=o.length-1;c>=0;c--)if(o[c].indexOf(a)!==-1){o[c]=o[c].replace(a,n[i][1]);break}}return this.#t.insert(o,e,s,this.#e,r),s}buildRegExp(){let t=this.#t.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,r=[],s=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(n,o,i)=>o!==void 0?(r[++e]=Number(o),"$()"):(i!==void 0&&(s[Number(i)]=++e),"")),[new RegExp(`^${t}`),r,s]}};var id=[/^$/,[],Object.create(null)],la=Object.create(null);function ua(t){return la[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function ad(){la=Object.create(null)}function cd(t){let e=new ca,r=[];if(t.length===0)return id;let s=t.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[d,p])=>l?1:d?-1:u.length-p.length),n=Object.create(null);for(let l=0,u=-1,d=s.length;l<d;l++){let[p,h,g]=s[l];p?n[h]=[g.map(([S])=>[S,Object.create(null)]),Zr]:u++;let b;try{b=e.insert(h,u,p)}catch(S){throw S===Fe?new Qr(h):S}p||(r[u]=g.map(([S,v])=>{let k=Object.create(null);for(v-=1;v>=0;v--){let[U,N]=b[v];k[U]=N}return[S,k]}))}let[o,i,a]=e.buildRegExp();for(let l=0,u=r.length;l<u;l++)for(let d=0,p=r[l].length;d<p;d++){let h=r[l][d]?.[1];if(!h)continue;let g=Object.keys(h);for(let b=0,S=g.length;b<S;b++)h[g[b]]=a[h[g[b]]]}let c=[];for(let l in i)c[l]=r[i[l]];return[o,c,n]}function ht(t,e){if(t){for(let r of Object.keys(t).sort((s,n)=>n.length-s.length))if(ua(r).test(e))return[...t[r]]}}var ts=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[I]:Object.create(null)},this.#t={[I]:Object.create(null)}}add(t,e,r){let s=this.#e,n=this.#t;if(!s||!n)throw new Error(Xr);s[t]||[s,n].forEach(a=>{a[t]=Object.create(null),Object.keys(a[I]).forEach(c=>{a[t][c]=[...a[I][c]]})}),e==="/*"&&(e="*");let o=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=ua(e);t===I?Object.keys(s).forEach(c=>{s[c][e]||=ht(s[c],e)||ht(s[I],e)||[]}):s[t][e]||=ht(s[t],e)||ht(s[I],e)||[],Object.keys(s).forEach(c=>{(t===I||t===c)&&Object.keys(s[c]).forEach(l=>{a.test(l)&&s[c][l].push([r,o])})}),Object.keys(n).forEach(c=>{(t===I||t===c)&&Object.keys(n[c]).forEach(l=>a.test(l)&&n[c][l].push([r,o]))});return}let i=Jr(e)||[e];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(n).forEach(u=>{(t===I||t===u)&&(n[u][l]||=[...ht(s[u],l)||ht(s[I],l)||[]],n[u][l].push([r,o-c+a+1]))})}}match=On;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach(e=>{t[e]||=this.#s(e)}),this.#e=this.#t=void 0,ad(),t}#s(t){let e=[],r=t===I;return[this.#e,this.#t].forEach(s=>{let n=s[t]?Object.keys(s[t]).map(o=>[o,s[t][o]]):[];n.length!==0?(r||=!0,e.push(...n)):t!==I&&e.push(...Object.keys(s[I]).map(o=>[o,s[I][o]]))}),r?cd(e):null}};var Mn=class{name="SmartRouter";#e=[];#t=[];constructor(t){this.#e=t.routers}add(t,e,r){if(!this.#t)throw new Error(Xr);this.#t.push([t,e,r])}match(t,e){if(!this.#t)throw new Error("Fatal error");let r=this.#e,s=this.#t,n=r.length,o=0,i;for(;o<n;o++){let a=r[o];try{for(let c=0,l=s.length;c<l;c++)a.add(...s[c]);i=a.match(t,e)}catch(c){if(c instanceof Qr)continue;throw c}this.match=a.match.bind(a),this.#e=[a],this.#t=void 0;break}if(o===n)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#t||this.#e.length!==1)throw new Error("No active router has been determined yet.");return this.#e[0]}};var or=Object.create(null),ld=t=>{for(let e in t)return!0;return!1},da=class fa{#e;#t;#s;#o=0;#r=or;constructor(e,r,s){if(this.#t=s||Object.create(null),this.#e=[],e&&r){let n=Object.create(null);n[e]={handler:r,possibleKeys:[],score:0},this.#e=[n]}this.#s=[]}insert(e,r,s){this.#o=++this.#o;let n=this,o=Gi(r),i=[];for(let a=0,c=o.length;a<c;a++){let l=o[a],u=o[a+1],d=Ki(l,u),p=Array.isArray(d)?d[0]:l;if(p in n.#t){n=n.#t[p],d&&i.push(d[1]);continue}n.#t[p]=new fa,d&&(n.#s.push(d),i.push(d[1])),n=n.#t[p]}return n.#e.push({[e]:{handler:s,possibleKeys:i.filter((a,c,l)=>l.indexOf(a)===c),score:this.#o}}),n}#n(e,r,s,n,o){for(let i=0,a=r.#e.length;i<a;i++){let c=r.#e[i],l=c[s]||c[I],u={};if(l!==void 0&&(l.params=Object.create(null),e.push(l),n!==or||o&&o!==or))for(let d=0,p=l.possibleKeys.length;d<p;d++){let h=l.possibleKeys[d],g=u[l.score];l.params[h]=o?.[h]&&!g?o[h]:n[h]??o?.[h],u[l.score]=!0}}}search(e,r){let s=[];this.#r=or;let o=[this],i=Rn(r),a=[],c=i.length,l=null;for(let u=0;u<c;u++){let d=i[u],p=u===c-1,h=[];for(let b=0,S=o.length;b<S;b++){let v=o[b],k=v.#t[d];k&&(k.#r=v.#r,p?(k.#t["*"]&&this.#n(s,k.#t["*"],e,v.#r),this.#n(s,k,e,v.#r)):h.push(k));for(let U=0,N=v.#s.length;U<N;U++){let V=v.#s[U],W=v.#r===or?{}:{...v.#r};if(V==="*"){let T=v.#t["*"];T&&(this.#n(s,T,e,v.#r),T.#r=W,h.push(T));continue}let[x,$,R]=V;if(!d&&!(R instanceof RegExp))continue;let A=v.#t[x];if(R instanceof RegExp){if(l===null){l=new Array(c);let G=r[0]==="/"?1:0;for(let ie=0;ie<c;ie++)l[ie]=G,G+=i[ie].length+1}let T=r.substring(l[u]),q=R.exec(T);if(q){if(W[$]=q[0],this.#n(s,A,e,v.#r,W),ld(A.#t)){A.#r=W;let G=q[0].match(/\//)?.length??0;(a[G]||=[]).push(A)}continue}}(R===!0||R.test(d))&&(W[$]=d,p?(this.#n(s,A,e,W,v.#r),A.#t["*"]&&this.#n(s,A.#t["*"],e,W,v.#r)):(A.#r=W,h.push(A)))}}let g=a.shift();o=g?h.concat(g):h}return s.length>1&&s.sort((u,d)=>u.score-d.score),[s.map(({handler:u,params:d})=>[u,d])]}};var Cn=class{name="TrieRouter";#e;constructor(){this.#e=new da}add(t,e,r){let s=Jr(e);if(s){for(let n=0,o=s.length;n<o;n++)this.#e.insert(t,s[n],r);return}this.#e.insert(t,e,r)}match(t,e){return this.#e.search(t,e)}};var Nn=class extends oa{constructor(t={}){super(t),this.router=t.router??new Mn({routers:[new ts,new Cn]})}};var Ln=class{writer;encoder;writable;abortSubscribers=[];responseReadable;aborted=!1;closed=!1;constructor(t,e){this.writable=t,this.writer=t.getWriter(),this.encoder=new TextEncoder;let r=e.getReader();this.abortSubscribers.push(async()=>{await r.cancel()}),this.responseReadable=new ReadableStream({async pull(s){let{done:n,value:o}=await r.read();n?s.close():s.enqueue(o)},cancel:()=>{this.abort()}})}async write(t){try{typeof t=="string"&&(t=this.encoder.encode(t)),await this.writer.write(t)}catch{}return this}async writeln(t){return await this.write(t+`
|
|
9
|
-
`),this}sleep(t){return new Promise(e=>setTimeout(e,t))}async close(){try{await this.writer.close()}catch{}this.closed=!0}async pipe(t){this.writer.releaseLock(),await t.pipeTo(this.writable,{preventClose:!0}),this.writer=this.writable.getWriter()}onAbort(t){this.abortSubscribers.push(t)}abort(){this.aborted||(this.aborted=!0,this.abortSubscribers.forEach(t=>t()))}};var rs=()=>{let t=typeof Bun<"u"?Bun.version:void 0;if(t===void 0)return!1;let e=t.startsWith("1.1")||t.startsWith("1.0")||t.startsWith("0.");return rs=()=>e,e};var ha=class extends
|
|
8
|
+
`+r)}function Ue(t,e,r,s,n,o){if(t.listenerCount("wsClientError")){let i=new Error(n);Error.captureStackTrace(i,Ue),t.emit("wsClientError",i,r,e)}else er(r,s,n,o)}});import{existsSync as Oh}from"fs";import{stat as Ih}from"fs/promises";import{dirname as Mh,join as $c}from"path";import{createServer as Vc}from"http";import{Http2ServerRequest as Po,constants as Gc}from"http2";import{Http2ServerRequest as Vs}from"http2";import{Readable as ko}from"stream";import sl from"crypto";var Ne=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},Kc=t=>t instanceof Ne?t:new Ne(t.message,{cause:t}),zc=global.Request,Gt=class extends zc{constructor(t,e){typeof t=="object"&&st in t&&(t=t[st]()),typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},Jc=t=>{let e=[],r=t.rawHeaders;for(let s=0;s<r.length;s+=2){let{[s]:n,[s+1]:o}=r;n.charCodeAt(0)!==58&&e.push([n,o])}return new Headers(e)},To=Symbol("wrapBodyStream"),Yc=(t,e,r,s,n)=>{let o={method:t,headers:r,signal:n.signal};if(t==="TRACE"){o.method="GET";let i=new Gt(e,o);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(t==="GET"||t==="HEAD"))if("rawBody"in s&&s.rawBody instanceof Buffer)o.body=new ReadableStream({start(i){i.enqueue(s.rawBody),i.close()}});else if(s[To]){let i;o.body=new ReadableStream({async pull(a){try{i||=ko.toWeb(s).getReader();let{done:c,value:l}=await i.read();c?a.close():a.enqueue(l)}catch(c){a.error(c)}}})}else o.body=ko.toWeb(s);return new Gt(e,o)},st=Symbol("getRequestCache"),Ao=Symbol("requestCache"),Or=Symbol("incomingKey"),Ir=Symbol("urlKey"),Xc=Symbol("headersKey"),rt=Symbol("abortControllerKey"),Qc=Symbol("getAbortController"),Kt={get method(){return this[Or].method||"GET"},get url(){return this[Ir]},get headers(){return this[Xc]||=Jc(this[Or])},[Qc](){return this[st](),this[rt]},[st](){return this[rt]||=new AbortController,this[Ao]||=Yc(this.method,this[Ir],this.headers,this[Or],this[rt])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(t=>{Object.defineProperty(Kt,t,{get(){return this[st]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Kt,t,{value:function(){return this[st]()[t]()}})});Object.defineProperty(Kt,Symbol.for("nodejs.util.inspect.custom"),{value:function(t,e,r){let s={method:this.method,url:this.url,headers:this.headers,nativeRequest:this[Ao]};return`Request (lightweight) ${r(s,{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Kt,Gt.prototype);var Zc=(t,e)=>{let r=Object.create(Kt);r[Or]=t;let s=t.url||"";if(s[0]!=="/"&&(s.startsWith("http://")||s.startsWith("https://"))){if(t instanceof Vs)throw new Ne("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(s);r[Ir]=a.href}catch(a){throw new Ne("Invalid absolute URL",{cause:a})}return r}let n=(t instanceof Vs?t.authority:t.headers.host)||e;if(!n)throw new Ne("Missing host header");let o;if(t instanceof Vs){if(o=t.scheme,!(o==="http"||o==="https"))throw new Ne("Unsupported scheme")}else o=t.socket&&t.socket.encrypted?"https":"http";let i=new URL(`${o}://${n}${s}`);if(i.hostname.length!==n.length&&i.hostname!==n.replace(/:\d+$/,""))throw new Ne("Invalid host header");return r[Ir]=i.href,r},Ks=Symbol("responseCache"),tt=Symbol("getResponseCache"),Le=Symbol("cache"),Ys=global.Response,nt=class Oo{#e;#t;[tt](){return delete this[Le],this[Ks]||=new Ys(this.#e,this.#t)}constructor(e,r){let s;if(this.#e=e,r instanceof Oo){let n=r[Ks];if(n){this.#t=n,this[tt]();return}else this.#t=r.#t,s=new Headers(r.#t.headers)}else this.#t=r;(typeof e=="string"||typeof e?.getReader<"u"||e instanceof Blob||e instanceof Uint8Array)&&(this[Le]=[r?.status||200,e,s||r?.headers])}get headers(){let e=this[Le];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":"text/plain; charset=UTF-8"})),e[2]):this[tt]().headers}get status(){return this[Le]?.[0]??this[tt]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(nt.prototype,t,{get(){return this[tt]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(nt.prototype,t,{value:function(){return this[tt]()[t]()}})});Object.defineProperty(nt.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(t,e,r){let s={status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[Ks]};return`Response (lightweight) ${r(s,{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(nt,Ys);Object.setPrototypeOf(nt.prototype,Ys.prototype);async function el(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Io(t,e,r){let s=a=>{t.cancel(a).catch(()=>{})};return e.on("close",s),e.on("error",s),(r??t.read()).then(i,n),t.closed.finally(()=>{e.off("close",s),e.off("error",s)});function n(a){a&&e.destroy(a)}function o(){t.read().then(i,n)}function i({done:a,value:c}){try{if(a)e.end();else if(!e.write(c))e.once("drain",o);else return t.read().then(i,n)}catch(l){n(l)}}}function tl(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:Io(t.getReader(),e)}var zs=t=>{let e={};t instanceof Headers||(t=new Headers(t??void 0));let r=[];for(let[s,n]of t)s==="set-cookie"?r.push(n):e[s]=n;return r.length>0&&(e["set-cookie"]=r),e["content-type"]??="text/plain; charset=UTF-8",e},rl="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=sl);var Xs=Symbol("outgoingEnded"),Ro=Symbol("incomingDraining"),nl=500,ol=64*1024*1024,Gs=t=>{let e=t;if(t.destroyed||e[Ro])return;if(e[Ro]=!0,t instanceof Po){try{t.stream?.close?.(Gc.NGHTTP2_NO_ERROR)}catch{}return}let r=0,s=()=>{clearTimeout(o),t.off("data",i),t.off("end",s),t.off("error",s)},n=()=>{s();let a=t.socket;a&&!a.destroyed&&a.destroySoon()},o=setTimeout(n,nl);o.unref?.();let i=a=>{r+=a.length,r>ol&&n()};t.on("data",i),t.on("end",s),t.on("error",s),t.resume()},il=()=>new Response(null,{status:400}),Mo=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),Js=(t,e)=>{let r=t instanceof Error?t:new Error("unknown error",{cause:t});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(t),e.headersSent||e.writeHead(500,{"Content-Type":"text/plain"}),e.end(`Error: ${r.message}`),e.destroy(r))},Co=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},No=async(t,e)=>{let[r,s,n]=t[Le],o=!1;if(!n)n={"content-type":"text/plain; charset=UTF-8"};else if(n instanceof Headers)o=n.has("content-length"),n=zs(n);else if(Array.isArray(n)){let i=new Headers(n);o=i.has("content-length"),n=zs(i)}else for(let i in n)if(i.length===14&&i.toLowerCase()==="content-length"){o=!0;break}o||(typeof s=="string"?n["Content-Length"]=Buffer.byteLength(s):s instanceof Uint8Array?n["Content-Length"]=s.byteLength:s instanceof Blob&&(n["Content-Length"]=s.size)),e.writeHead(r,n),typeof s=="string"||s instanceof Uint8Array?e.end(s):s instanceof Blob?e.end(new Uint8Array(await s.arrayBuffer())):(Co(e),await tl(s,e)?.catch(i=>Js(i,e))),e[Xs]?.()},al=t=>typeof t.then=="function",cl=async(t,e,r={})=>{if(al(t))if(r.errorHandler)try{t=await t}catch(n){let o=await r.errorHandler(n);if(!o)return;t=o}else t=await t.catch(Mo);if(Le in t)return No(t,e);let s=zs(t.headers);if(t.body){let n=t.body.getReader(),o=[],i=!1,a;if(s["transfer-encoding"]!=="chunked"){let c=2;for(let l=0;l<c;l++){a||=n.read();let u=await el(a).catch(d=>{console.error(d),i=!0});if(!u){if(l===1){await new Promise(d=>setTimeout(d)),c=3;continue}break}if(a=void 0,u.value&&o.push(u.value),u.done){i=!0;break}}i&&!("content-length"in s)&&(s["content-length"]=o.reduce((l,u)=>l+u.length,0))}e.writeHead(t.status,s),o.forEach(c=>{e.write(c)}),i?e.end():(o.length===0&&Co(e),await Io(n,e,a))}else s[rl]||(e.writeHead(t.status,s),e.end());e[Xs]?.()},ll=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==Gt&&(Object.defineProperty(global,"Request",{value:Gt}),Object.defineProperty(global,"Response",{value:nt})),async(s,n)=>{let o,i;try{i=Zc(s,e.hostname);let a=!r||s.method==="GET"||s.method==="HEAD";if(a||(s[To]=!0,s.on("end",()=>{a=!0}),s instanceof Po&&(n[Xs]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{Gs(s)})})}),n.on("finish",()=>{a||Gs(s)})),n.on("close",()=>{i[rt]&&(s.errored?i[rt].abort(s.errored.toString()):n.writableFinished||i[rt].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{Gs(s)})})}),o=t(i,{incoming:s,outgoing:n}),Le in o)return No(o,n)}catch(a){if(o)return Js(a,n);if(e.errorHandler){if(o=await e.errorHandler(i?a:Kc(a)),!o)return}else i?o=Mo(a):o=il()}try{return await cl(o,n,e)}catch(a){return Js(a,n)}}},ul=t=>{let e=t.fetch,r=ll(e,{hostname:t.hostname,overrideGlobalObjects:t.overrideGlobalObjects,autoCleanupIncoming:t.autoCleanupIncoming});return(t.createServer||Vc)(t.serverOptions||{},r)},Lo=(t,e)=>{let r=ul(t);return r.listen(t?.port??3e3,t.hostname,()=>{let s=r.address();e&&e(s)}),r};var $o=(t,e=fl)=>{let r=/\.([a-zA-Z0-9]+?)$/,s=t.match(r);if(!s)return;let n=e[s[1].toLowerCase()];return n&&n.startsWith("text")&&(n+="; charset=utf-8"),n};var dl={aac:"audio/aac",avi:"video/x-msvideo",avif:"image/avif",av1:"video/av1",bin:"application/octet-stream",bmp:"image/bmp",css:"text/css",csv:"text/csv",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",gz:"application/gzip",htm:"text/html",html:"text/html",ico:"image/x-icon",ics:"text/calendar",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",map:"application/json",mid:"audio/x-midi",midi:"audio/x-midi",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",pdf:"application/pdf",png:"image/png",rtf:"application/rtf",svg:"image/svg+xml",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",wasm:"application/wasm",webm:"video/webm",weba:"audio/webm",webmanifest:"application/manifest+json",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xml:"application/xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2",gltf:"model/gltf+json",glb:"model/gltf-binary"},fl=dl;import{createReadStream as jo,statSync as hl,existsSync as pl}from"fs";import{join as Bo}from"path";import{versions as ml}from"process";import{Readable as gl}from"stream";var yl=/^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i,Zs={br:".br",zstd:".zst",gzip:".gz"},_l=Object.keys(Zs),bl=()=>{let[t,e]=ml.node.split(".").map(r=>parseInt(r));return t>=23||t===22&&e>=7||t===20&&e>=18},wl=bl(),Do=t=>wl?gl.toWeb(t):new ReadableStream({start(r){t.on("data",s=>{r.enqueue(s)}),t.on("error",s=>{r.error(s)}),t.on("end",()=>{r.close()})},cancel(){t.destroy()}}),Qs=t=>{let e;try{e=hl(t)}catch{}return e},xl=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},Sl=t=>xl(t,decodeURI),Uo=(t={root:""})=>{let e=t.root||"",r=t.path;return e!==""&&!pl(e)&&console.error(`serveStatic: root path '${e}' is not found, are you sure it's correct?`),async(s,n)=>{if(s.finalized)return n();let o;if(r)o=r;else try{if(o=Sl(s.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}/.test(o))throw new Error}catch{return await t.onNotFound?.(s.req.path,s),n()}let i=Bo(e,!r&&t.rewriteRequestPath?t.rewriteRequestPath(o,s):o),a=Qs(i);if(a&&a.isDirectory()){let p=t.index??"index.html";i=Bo(i,p),a=Qs(i)}if(!a)return await t.onNotFound?.(i,s),n();let c=$o(i);if(s.header("Content-Type",c||"application/octet-stream"),t.precompressed&&(!c||yl.test(c))){let p=new Set(s.req.header("Accept-Encoding")?.split(",").map(h=>h.trim()));for(let h of _l){if(!p.has(h))continue;let g=Qs(i+Zs[h]);if(g){s.header("Content-Encoding",h),s.header("Vary","Accept-Encoding",{append:!0}),a=g,i=i+Zs[h];break}}}let l,u=a.size,d=s.req.header("range")||"";if(s.req.method=="HEAD"||s.req.method=="OPTIONS")s.header("Content-Length",u.toString()),s.status(200),l=s.body(null);else if(!d)s.header("Content-Length",u.toString()),l=s.body(Do(jo(i)),200);else{s.header("Accept-Ranges","bytes"),s.header("Date",a.birthtime.toUTCString());let p=d.replace(/bytes=/,"").split("-",2),h=parseInt(p[0],10)||0,g=parseInt(p[1],10)||u-1;u<g-h+1&&(g=u-1);let b=g-h+1,S=jo(i,{start:h,end:g});s.header("Content-Length",b.toString()),s.header("Content-Range",`bytes ${h}-${g}/${a.size}`),l=s.body(Do(S),206)}return await t.onFound?.(i,s),l}};var Fu=Se(Li(),1),Hu=Se(Ur(),1),Wu=Se(at(),1),Vu=Se(dn(),1),Gu=Se(pn(),1),Ku=Se(wn(),1),zu=Se(Wr(),1),Sn=Se(Hi(),1);var vn=(t,e,r)=>(s,n)=>{let o=-1;return i(0);async function i(a){if(a<=o)throw new Error("next() called multiple times");o=a;let c,l=!1,u;if(t[a]?(u=t[a][0][0],s.req.routeIndex=a):u=a===t.length&&n||void 0,u)try{c=await u(s,()=>i(a+1))}catch(d){if(d instanceof Error&&e)s.error=d,c=await e(d,s),l=!0;else throw d}else s.finalized===!1&&r&&(c=await r(s));return c&&(s.finalized===!1||l)&&(s.res=c),s}};var Wi=Symbol();var Vi=async(t,e=Object.create(null))=>{let{all:r=!1,dot:s=!1}=e,o=(t instanceof Gr?t.raw.headers:t.headers).get("Content-Type");return o?.startsWith("multipart/form-data")||o?.startsWith("application/x-www-form-urlencoded")?Ju(t,{all:r,dot:s}):{}};async function Ju(t,e){let r=await t.formData();return r?Yu(r,e):{}}function Yu(t,e){let r=Object.create(null);return t.forEach((s,n)=>{e.all||n.endsWith("[]")?Xu(r,n,s):r[n]=s}),e.dot&&Object.entries(r).forEach(([s,n])=>{s.includes(".")&&(Qu(r,s,n),delete r[s])}),r}var Xu=(t,e,r)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(r):t[e]=[t[e],r]:e.endsWith("[]")?t[e]=[r]:t[e]=r},Qu=(t,e,r)=>{if(/(?:^|\.)__proto__\./.test(e))return;let s=t,n=e.split(".");n.forEach((o,i)=>{i===n.length-1?s[o]=r:((!s[o]||typeof s[o]!="object"||Array.isArray(s[o])||s[o]instanceof File)&&(s[o]=Object.create(null)),s=s[o])})};var kn=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},Gi=t=>{let{groups:e,path:r}=Zu(t),s=kn(r);return ed(s,e)},Zu=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,s)=>{let n=`@${s}`;return e.push([n,r]),n}),{groups:e,path:t}},ed=(t,e)=>{for(let r=e.length-1;r>=0;r--){let[s]=e[r];for(let n=t.length-1;n>=0;n--)if(t[n].includes(s)){t[n]=t[n].replace(s,e[r][1]);break}}return t},Kr={},Ki=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let s=`${t}#${e}`;return Kr[s]||(r[2]?Kr[s]=e&&e[0]!==":"&&e[0]!=="*"?[s,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:Kr[s]=[t,r[1],!0]),Kr[s]}return null},zr=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},td=t=>zr(t,decodeURI),Rn=t=>{let e=t.url,r=e.indexOf("/",e.indexOf(":")+4),s=r;for(;s<e.length;s++){let n=e.charCodeAt(s);if(n===37){let o=e.indexOf("?",s),i=e.indexOf("#",s),a=o===-1?i===-1?void 0:i:i===-1?o:Math.min(o,i),c=e.slice(r,a);return td(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(n===63||n===35)break}return e.slice(r,s)};var zi=t=>{let e=Rn(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},qe=(t,e,...r)=>(r.length&&(e=qe(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),Jr=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),r=[],s="";return e.forEach(n=>{if(n!==""&&!/\:/.test(n))s+="/"+n;else if(/\:/.test(n))if(/\?/.test(n)){r.length===0&&s===""?r.push("/"):r.push(s);let o=n.replace("?","");s+="/"+o,r.push(s)}else s+="/"+n}),r.filter((n,o,i)=>i.indexOf(n)===o)},En=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?zr(t,Pn):t):t,Ji=(t,e,r)=>{let s;if(!r&&e&&!/[%+]/.test(e)){let i=t.indexOf("?",8);if(i===-1)return;for(t.startsWith(e,i+1)||(i=t.indexOf(`&${e}`,i+1));i!==-1;){let a=t.charCodeAt(i+e.length+1);if(a===61){let c=i+e.length+2,l=t.indexOf("&",c);return En(t.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";i=t.indexOf(`&${e}`,i+1)}if(s=/[%+]/.test(t),!s)return}let n={};s??=/[%+]/.test(t);let o=t.indexOf("?",8);for(;o!==-1;){let i=t.indexOf("&",o+1),a=t.indexOf("=",o);a>i&&i!==-1&&(a=-1);let c=t.slice(o+1,a===-1?i===-1?void 0:i:a);if(s&&(c=En(c)),o=i,c==="")continue;let l;a===-1?l="":(l=t.slice(a+1,i===-1?void 0:i),s&&(l=En(l))),r?(n[c]&&Array.isArray(n[c])||(n[c]=[]),n[c].push(l)):n[c]??=l}return e?n[e]:n},Yi=Ji,Xi=(t,e)=>Ji(t,e,!0),Pn=decodeURIComponent;var Qi=t=>zr(t,Pn),Gr=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(t,e="/",r=[[]]){this.raw=t,this.path=e,this.#t=r,this.#e={}}param(t){return t?this.#s(t):this.#o()}#s(t){let e=this.#t[0][this.routeIndex][1][t],r=this.#r(e);return r&&/\%/.test(r)?Qi(r):r}#o(){let t={},e=Object.keys(this.#t[0][this.routeIndex][1]);for(let r of e){let s=this.#r(this.#t[0][this.routeIndex][1][r]);s!==void 0&&(t[r]=/\%/.test(s)?Qi(s):s)}return t}#r(t){return this.#t[1]?this.#t[1][t]:t}query(t){return Yi(this.url,t)}queries(t){return Xi(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e={};return this.raw.headers.forEach((r,s)=>{e[s]=r}),e}async parseBody(t){return Vi(this,t)}#n=t=>{let{bodyCache:e,raw:r}=this,s=e[t];if(s)return s;let n=Object.keys(e)[0];return n?e[n].then(o=>(n==="json"&&(o=JSON.stringify(o)),new Response(o)[t]())):e[t]=r[t]()};json(){return this.#n("text").then(t=>JSON.parse(t))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(t,e){this.#e[t]=e}valid(t){return this.#e[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[Wi](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,t]])=>t)}get routePath(){return this.#t[0].map(([[,t]])=>t)[this.routeIndex].path}};var Yr={Stringify:1,BeforeStream:2,Stream:3},rd=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r};var tr=async(t,e,r,s,n)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let o=t.callbacks;if(!o?.length)return Promise.resolve(t);n?n[0]+=t:n=[t];let i=Promise.all(o.map(a=>a({phase:e,buffer:n,context:s}))).then(a=>Promise.all(a.filter(Boolean).map(c=>tr(c,e,!1,s,n))).then(()=>n[0]));return r?rd(await i,o):i};var Zi="text/plain; charset=UTF-8",Tn=(t,e)=>({"Content-Type":t,...e}),rr=(t,e)=>new Response(t,e),ea=class{#e;#t;env={};#s;finalized=!1;error;#o;#r;#n;#a;#l;#h;#c;#d;#p;constructor(t,e){this.#e=t,e&&(this.#r=e.executionCtx,this.env=e.env,this.#h=e.notFoundHandler,this.#p=e.path,this.#d=e.matchResult)}get req(){return this.#t??=new Gr(this.#e,this.#p,this.#d),this.#t}get event(){if(this.#r&&"respondWith"in this.#r)return this.#r;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#r)return this.#r;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=rr(null,{headers:this.#c??=new Headers})}set res(t){if(this.#n&&t){t=rr(t.body,t);for(let[e,r]of this.#n.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let s=this.#n.headers.getSetCookie();t.headers.delete("set-cookie");for(let n of s)t.headers.append("set-cookie",n)}else t.headers.set(e,r)}this.#n=t,this.finalized=!0}render=(...t)=>(this.#l??=e=>this.html(e),this.#l(...t));setLayout=t=>this.#a=t;getLayout=()=>this.#a;setRenderer=t=>{this.#l=t};header=(t,e,r)=>{this.finalized&&(this.#n=rr(this.#n.body,this.#n));let s=this.#n?this.#n.headers:this.#c??=new Headers;e===void 0?s.delete(t):r?.append?s.append(t,e):s.set(t,e)};status=t=>{this.#o=t};set=(t,e)=>{this.#s??=new Map,this.#s.set(t,e)};get=t=>this.#s?this.#s.get(t):void 0;get var(){return this.#s?Object.fromEntries(this.#s):{}}#f(t,e,r){let s=this.#n?new Headers(this.#n.headers):this.#c??new Headers;if(typeof e=="object"&&"headers"in e){let o=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[i,a]of o)i.toLowerCase()==="set-cookie"?s.append(i,a):s.set(i,a)}if(r)for(let[o,i]of Object.entries(r))if(typeof i=="string")s.set(o,i);else{s.delete(o);for(let a of i)s.append(o,a)}let n=typeof e=="number"?e:e?.status??this.#o;return rr(t,{status:n,headers:s})}newResponse=(...t)=>this.#f(...t);body=(t,e,r)=>this.#f(t,e,r);text=(t,e,r)=>!this.#c&&!this.#o&&!e&&!r&&!this.finalized?new Response(t):this.#f(t,e,Tn(Zi,r));json=(t,e,r)=>this.#f(JSON.stringify(t),e,Tn("application/json",r));html=(t,e,r)=>{let s=n=>this.#f(n,e,Tn("text/html; charset=UTF-8",r));return typeof t=="object"?tr(t,Yr.Stringify,!1,{}).then(s):s(t)};redirect=(t,e)=>{let r=String(t);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,e??302)};notFound=()=>(this.#h??=()=>rr(),this.#h(this))};var I="ALL",ta="all",ra=["get","post","put","delete","options","patch"],Xr="Can not add a route since the matcher is already built.",Qr=class extends Error{};var sa="__COMPOSED_HANDLER";var sd=t=>t.text("404 Not Found",404),na=(t,e)=>{if("getResponse"in t){let r=t.getResponse();return e.newResponse(r.body,r)}return console.error(t),e.text("Internal Server Error",500)},oa=class ia{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(e={}){[...ra,ta].forEach(o=>{this[o]=(i,...a)=>(typeof i=="string"?this.#e=i:this.#o(o,this.#e,i),a.forEach(c=>{this.#o(o,this.#e,c)}),this)}),this.on=(o,i,...a)=>{for(let c of[i].flat()){this.#e=c;for(let l of[o].flat())a.map(u=>{this.#o(l.toUpperCase(),this.#e,u)})}return this},this.use=(o,...i)=>(typeof o=="string"?this.#e=o:(this.#e="*",i.unshift(o)),i.forEach(a=>{this.#o(I,this.#e,a)}),this);let{strict:s,...n}=e;Object.assign(this,n),this.getPath=s??!0?e.getPath??Rn:zi}#t(){let e=new ia({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#s=this.#s,e.routes=this.routes,e}#s=sd;errorHandler=na;route(e,r){let s=this.basePath(e);return r.routes.map(n=>{let o;r.errorHandler===na?o=n.handler:(o=async(i,a)=>(await vn([],r.errorHandler)(i,()=>n.handler(i,a))).res,o[sa]=n.handler),s.#o(n.method,n.path,o)}),this}basePath(e){let r=this.#t();return r._basePath=qe(this._basePath,e),r}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#s=e,this);mount(e,r,s){let n,o;s&&(typeof s=="function"?o=s:(o=s.optionHandler,s.replaceRequest===!1?n=c=>c:n=s.replaceRequest));let i=o?c=>{let l=o(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};n||=(()=>{let c=qe(this._basePath,e),l=c==="/"?0:c.length;return u=>{let d=new URL(u.url);return d.pathname=d.pathname.slice(l)||"/",new Request(d,u)}})();let a=async(c,l)=>{let u=await r(n(c.req.raw),...i(c));if(u)return u;await l()};return this.#o(I,qe(e,"*"),a),this}#o(e,r,s){e=e.toUpperCase(),r=qe(this._basePath,r);let n={basePath:this._basePath,path:r,method:e,handler:s};this.router.add(e,r,[s,n]),this.routes.push(n)}#r(e,r){if(e instanceof Error)return this.errorHandler(e,r);throw e}#n(e,r,s,n){if(n==="HEAD")return(async()=>new Response(null,await this.#n(e,r,s,"GET")))();let o=this.getPath(e,{env:s}),i=this.router.match(n,o),a=new ea(e,{path:o,matchResult:i,env:s,executionCtx:r,notFoundHandler:this.#s});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#s(a)})}catch(u){return this.#r(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#s(a))).catch(u=>this.#r(u,a)):l??this.#s(a)}let c=vn(i[0],this.errorHandler,this.#s);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#r(l,a)}})()}fetch=(e,...r)=>this.#n(e,r[1],r[0],e.method);request=(e,r,s,n)=>e instanceof Request?this.fetch(r?new Request(e,r):e,s,n):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${qe("/",e)}`,r),s,n));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#n(e.request,e,void 0,e.request.method))})}};var Zr=[];function An(t,e){let r=this.buildAllMatchers(),s=((n,o)=>{let i=r[n]||r[I],a=i[2][o];if(a)return a;let c=o.match(i[0]);if(!c)return[[],Zr];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=s,s(t,e)}var es="[^/]+",sr=".*",nr="(?:|/.*)",Fe=Symbol(),nd=new Set(".\\+*[^]$()");function od(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===sr||t===nr?1:e===sr||e===nr?-1:t===es?1:e===es?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var aa=class On{#e;#t;#s=Object.create(null);insert(e,r,s,n,o){if(e.length===0){if(this.#e!==void 0)throw Fe;if(o)return;this.#e=r;return}let[i,...a]=e,c=i==="*"?a.length===0?["","",sr]:["","",es]:i==="/*"?["","",nr]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],d=c[2]||es;if(u&&c[2]&&(d===".*"||(d=d.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(d))))throw Fe;if(l=this.#s[d],!l){if(Object.keys(this.#s).some(p=>p!==sr&&p!==nr))throw Fe;if(o)return;l=this.#s[d]=new On,u!==""&&(l.#t=n.varIndex++)}!o&&u!==""&&s.push([u,l.#t])}else if(l=this.#s[i],!l){if(Object.keys(this.#s).some(u=>u.length>1&&u!==sr&&u!==nr))throw Fe;if(o)return;l=this.#s[i]=new On}l.insert(a,r,s,n,o)}buildRegExpStr(){let r=Object.keys(this.#s).sort(od).map(s=>{let n=this.#s[s];return(typeof n.#t=="number"?`(${s})@${n.#t}`:nd.has(s)?`\\${s}`:s)+n.buildRegExpStr()});return typeof this.#e=="number"&&r.unshift(`#${this.#e}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var ca=class{#e={varIndex:0};#t=new aa;insert(t,e,r){let s=[],n=[];for(let i=0;;){let a=!1;if(t=t.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return n[i]=[l,c],i++,a=!0,l}),!a)break}let o=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=n.length-1;i>=0;i--){let[a]=n[i];for(let c=o.length-1;c>=0;c--)if(o[c].indexOf(a)!==-1){o[c]=o[c].replace(a,n[i][1]);break}}return this.#t.insert(o,e,s,this.#e,r),s}buildRegExp(){let t=this.#t.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,r=[],s=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(n,o,i)=>o!==void 0?(r[++e]=Number(o),"$()"):(i!==void 0&&(s[Number(i)]=++e),"")),[new RegExp(`^${t}`),r,s]}};var id=[/^$/,[],Object.create(null)],la=Object.create(null);function ua(t){return la[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function ad(){la=Object.create(null)}function cd(t){let e=new ca,r=[];if(t.length===0)return id;let s=t.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[d,p])=>l?1:d?-1:u.length-p.length),n=Object.create(null);for(let l=0,u=-1,d=s.length;l<d;l++){let[p,h,g]=s[l];p?n[h]=[g.map(([S])=>[S,Object.create(null)]),Zr]:u++;let b;try{b=e.insert(h,u,p)}catch(S){throw S===Fe?new Qr(h):S}p||(r[u]=g.map(([S,v])=>{let k=Object.create(null);for(v-=1;v>=0;v--){let[U,N]=b[v];k[U]=N}return[S,k]}))}let[o,i,a]=e.buildRegExp();for(let l=0,u=r.length;l<u;l++)for(let d=0,p=r[l].length;d<p;d++){let h=r[l][d]?.[1];if(!h)continue;let g=Object.keys(h);for(let b=0,S=g.length;b<S;b++)h[g[b]]=a[h[g[b]]]}let c=[];for(let l in i)c[l]=r[i[l]];return[o,c,n]}function ht(t,e){if(t){for(let r of Object.keys(t).sort((s,n)=>n.length-s.length))if(ua(r).test(e))return[...t[r]]}}var ts=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[I]:Object.create(null)},this.#t={[I]:Object.create(null)}}add(t,e,r){let s=this.#e,n=this.#t;if(!s||!n)throw new Error(Xr);s[t]||[s,n].forEach(a=>{a[t]=Object.create(null),Object.keys(a[I]).forEach(c=>{a[t][c]=[...a[I][c]]})}),e==="/*"&&(e="*");let o=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=ua(e);t===I?Object.keys(s).forEach(c=>{s[c][e]||=ht(s[c],e)||ht(s[I],e)||[]}):s[t][e]||=ht(s[t],e)||ht(s[I],e)||[],Object.keys(s).forEach(c=>{(t===I||t===c)&&Object.keys(s[c]).forEach(l=>{a.test(l)&&s[c][l].push([r,o])})}),Object.keys(n).forEach(c=>{(t===I||t===c)&&Object.keys(n[c]).forEach(l=>a.test(l)&&n[c][l].push([r,o]))});return}let i=Jr(e)||[e];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(n).forEach(u=>{(t===I||t===u)&&(n[u][l]||=[...ht(s[u],l)||ht(s[I],l)||[]],n[u][l].push([r,o-c+a+1]))})}}match=An;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach(e=>{t[e]||=this.#s(e)}),this.#e=this.#t=void 0,ad(),t}#s(t){let e=[],r=t===I;return[this.#e,this.#t].forEach(s=>{let n=s[t]?Object.keys(s[t]).map(o=>[o,s[t][o]]):[];n.length!==0?(r||=!0,e.push(...n)):t!==I&&e.push(...Object.keys(s[I]).map(o=>[o,s[I][o]]))}),r?cd(e):null}};var In=class{name="SmartRouter";#e=[];#t=[];constructor(t){this.#e=t.routers}add(t,e,r){if(!this.#t)throw new Error(Xr);this.#t.push([t,e,r])}match(t,e){if(!this.#t)throw new Error("Fatal error");let r=this.#e,s=this.#t,n=r.length,o=0,i;for(;o<n;o++){let a=r[o];try{for(let c=0,l=s.length;c<l;c++)a.add(...s[c]);i=a.match(t,e)}catch(c){if(c instanceof Qr)continue;throw c}this.match=a.match.bind(a),this.#e=[a],this.#t=void 0;break}if(o===n)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#t||this.#e.length!==1)throw new Error("No active router has been determined yet.");return this.#e[0]}};var or=Object.create(null),ld=t=>{for(let e in t)return!0;return!1},da=class fa{#e;#t;#s;#o=0;#r=or;constructor(e,r,s){if(this.#t=s||Object.create(null),this.#e=[],e&&r){let n=Object.create(null);n[e]={handler:r,possibleKeys:[],score:0},this.#e=[n]}this.#s=[]}insert(e,r,s){this.#o=++this.#o;let n=this,o=Gi(r),i=[];for(let a=0,c=o.length;a<c;a++){let l=o[a],u=o[a+1],d=Ki(l,u),p=Array.isArray(d)?d[0]:l;if(p in n.#t){n=n.#t[p],d&&i.push(d[1]);continue}n.#t[p]=new fa,d&&(n.#s.push(d),i.push(d[1])),n=n.#t[p]}return n.#e.push({[e]:{handler:s,possibleKeys:i.filter((a,c,l)=>l.indexOf(a)===c),score:this.#o}}),n}#n(e,r,s,n,o){for(let i=0,a=r.#e.length;i<a;i++){let c=r.#e[i],l=c[s]||c[I],u={};if(l!==void 0&&(l.params=Object.create(null),e.push(l),n!==or||o&&o!==or))for(let d=0,p=l.possibleKeys.length;d<p;d++){let h=l.possibleKeys[d],g=u[l.score];l.params[h]=o?.[h]&&!g?o[h]:n[h]??o?.[h],u[l.score]=!0}}}search(e,r){let s=[];this.#r=or;let o=[this],i=kn(r),a=[],c=i.length,l=null;for(let u=0;u<c;u++){let d=i[u],p=u===c-1,h=[];for(let b=0,S=o.length;b<S;b++){let v=o[b],k=v.#t[d];k&&(k.#r=v.#r,p?(k.#t["*"]&&this.#n(s,k.#t["*"],e,v.#r),this.#n(s,k,e,v.#r)):h.push(k));for(let U=0,N=v.#s.length;U<N;U++){let V=v.#s[U],W=v.#r===or?{}:{...v.#r};if(V==="*"){let T=v.#t["*"];T&&(this.#n(s,T,e,v.#r),T.#r=W,h.push(T));continue}let[x,$,R]=V;if(!d&&!(R instanceof RegExp))continue;let A=v.#t[x];if(R instanceof RegExp){if(l===null){l=new Array(c);let G=r[0]==="/"?1:0;for(let ie=0;ie<c;ie++)l[ie]=G,G+=i[ie].length+1}let T=r.substring(l[u]),q=R.exec(T);if(q){if(W[$]=q[0],this.#n(s,A,e,v.#r,W),ld(A.#t)){A.#r=W;let G=q[0].match(/\//)?.length??0;(a[G]||=[]).push(A)}continue}}(R===!0||R.test(d))&&(W[$]=d,p?(this.#n(s,A,e,W,v.#r),A.#t["*"]&&this.#n(s,A.#t["*"],e,W,v.#r)):(A.#r=W,h.push(A)))}}let g=a.shift();o=g?h.concat(g):h}return s.length>1&&s.sort((u,d)=>u.score-d.score),[s.map(({handler:u,params:d})=>[u,d])]}};var Mn=class{name="TrieRouter";#e;constructor(){this.#e=new da}add(t,e,r){let s=Jr(e);if(s){for(let n=0,o=s.length;n<o;n++)this.#e.insert(t,s[n],r);return}this.#e.insert(t,e,r)}match(t,e){return this.#e.search(t,e)}};var Cn=class extends oa{constructor(t={}){super(t),this.router=t.router??new In({routers:[new ts,new Mn]})}};var Nn=class{writer;encoder;writable;abortSubscribers=[];responseReadable;aborted=!1;closed=!1;constructor(t,e){this.writable=t,this.writer=t.getWriter(),this.encoder=new TextEncoder;let r=e.getReader();this.abortSubscribers.push(async()=>{await r.cancel()}),this.responseReadable=new ReadableStream({async pull(s){let{done:n,value:o}=await r.read();n?s.close():s.enqueue(o)},cancel:()=>{this.abort()}})}async write(t){try{typeof t=="string"&&(t=this.encoder.encode(t)),await this.writer.write(t)}catch{}return this}async writeln(t){return await this.write(t+`
|
|
9
|
+
`),this}sleep(t){return new Promise(e=>setTimeout(e,t))}async close(){try{await this.writer.close()}catch{}this.closed=!0}async pipe(t){this.writer.releaseLock(),await t.pipeTo(this.writable,{preventClose:!0}),this.writer=this.writable.getWriter()}onAbort(t){this.abortSubscribers.push(t)}abort(){this.aborted||(this.aborted=!0,this.abortSubscribers.forEach(t=>t()))}};var rs=()=>{let t=typeof Bun<"u"?Bun.version:void 0;if(t===void 0)return!1;let e=t.startsWith("1.1")||t.startsWith("1.0")||t.startsWith("0.");return rs=()=>e,e};var ha=class extends Nn{constructor(t,e){super(t,e)}async writeSSE(t){let r=(await tr(t.data,Yr.Stringify,!1,{})).split(/\r\n|\r|\n/).map(n=>`data: ${n}`).join(`
|
|
10
10
|
`);for(let n of["event","id","retry"])if(t[n]&&/[\r\n]/.test(t[n]))throw new Error(`${n} must not contain "\\r" or "\\n"`);let s=[t.event&&`event: ${t.event}`,r,t.id&&`id: ${t.id}`,t.retry&&`retry: ${t.retry}`].filter(Boolean).join(`
|
|
11
11
|
`)+`
|
|
12
12
|
|
|
13
|
-
`;await this.write(s)}},ud=async(t,e,r)=>{try{await e(t)}catch(s){s instanceof Error&&r?(await r(s,t),await t.writeSSE({event:"error",data:s.message})):console.error(s)}finally{t.close()}},dd=new WeakMap
|
|
13
|
+
`;await this.write(s)}},ud=async(t,e,r)=>{try{await e(t)}catch(s){s instanceof Error&&r?(await r(s,t),await t.writeSSE({event:"error",data:s.message})):console.error(s)}finally{t.close()}},dd=new WeakMap,Ln=(t,e,r)=>{let{readable:s,writable:n}=new TransformStream,o=new ha(n,s);return rs()&&t.req.raw.signal.addEventListener("abort",()=>{o.closed||o.abort()}),dd.set(o.responseReadable,t),t.header("Transfer-Encoding","chunked"),t.header("Content-Type","text/event-stream"),t.header("Cache-Control","no-cache"),t.header("Connection","keep-alive"),ud(o,e,r),t.newResponse(o.responseReadable)};var pa={streaming:!0,approvalPrompts:!0,background:!1};var hd={full:{name:"full",description:"All available tools.",allowedTools:[]},coding:{name:"coding",description:"File system, search, and shell tools for coding tasks.",allowedTools:["read_file","list_directory","write_file","edit_file","append_file","run_shell","search_files","load_skill","update_todos","spawn_subagent","spawn_subagent_async","check_subagent"]},messaging:{name:"messaging",description:"Read-only tools for informational tasks without file writes or shell execution.",allowedTools:["read_file","list_directory","read_web_page","memory_search","memory_get","load_skill","update_todos"]},background:{name:"background",description:"File system tools only for unattended background tasks.",allowedTools:["read_file","list_directory","write_file","memory_search","memory_get","append_daily_memory","update_todos","spawn_subagent","update_heartbeat"]}};function ma(t,e){let r=hd[e];return r.allowedTools.length===0?t:t.filter(s=>r.allowedTools.includes(s.name))}import{join as pd}from"path";var md={baseURL:"https://openrouter.ai/api/v1"},gd={model:"claude-haiku-4-5-20251001"},K=class extends Error{constructor(e){super(e),this.name="ConfigValidationError"}},yd={model:{provider:"openai-compatible",baseURL:"https://api.openai.com/v1",model:"gpt-4.1-mini",temperature:.2,maxTokens:4096},workspace:{root:"."},runtime:{defaultMode:"confirm",maxSteps:12},trace:{verbosity:"explainable"},tools:{fileSystem:!0,shell:!0,web:!1},permissions:{allowLowRisk:!0},sessions:{directory:"~/.vole/sessions"},memory:{longTermFiles:"disabled",writes:"disabled"},secrets:{apiKey:void 0}};function ya(t={}){let e=_d(yd);return ga(e,t.userConfig),ga(e,t.projectConfig),bd(e,t.env??{}),wd(e),e}function _d(t){return{model:{...t.model},workspace:{...t.workspace},runtime:{...t.runtime},trace:{...t.trace},tools:{...t.tools},permissions:{...t.permissions},sessions:{...t.sessions},memory:{...t.memory},secrets:{...t.secrets}}}function ga(t,e){if(e!==void 0){if(!_a(e))throw new K("Configuration must be an object.");ke(t.model,e.model),ke(t.workspace,e.workspace),ke(t.runtime,e.runtime),ke(t.trace,e.trace),ke(t.tools,e.tools),ke(t.permissions,e.permissions),ke(t.sessions,e.sessions),ke(t.memory,e.memory)}}function ke(t,e){if(e!==void 0){if(!_a(e))throw new K("Configuration sections must be objects.");for(let[r,s]of Object.entries(e))r in t&&(t[r]=s)}}function bd(t,e){e.OPENROUTER_API_KEY!==void 0&&(t.model.provider="openai-compatible",t.model.baseURL=md.baseURL,t.model.model="",t.secrets.apiKey=e.OPENROUTER_API_KEY),e.ANTHROPIC_API_KEY!==void 0&&(t.model.provider="anthropic",t.model.model=gd.model,t.secrets.apiKey=e.ANTHROPIC_API_KEY),e.VOLE_BASE_URL!==void 0&&(t.model.baseURL=e.VOLE_BASE_URL),e.VOLE_MODEL!==void 0&&(t.model.model=e.VOLE_MODEL),e.VOLE_DEFAULT_MODE!==void 0&&(t.runtime.defaultMode=e.VOLE_DEFAULT_MODE),e.VOLE_WORKSPACE_ROOT!==void 0&&(t.workspace.root=e.VOLE_WORKSPACE_ROOT),e.VOLE_LONG_TERM_MEMORY!==void 0&&(t.memory.longTermFiles=e.VOLE_LONG_TERM_MEMORY),e.VOLE_API_KEY!==void 0&&(t.secrets.apiKey=e.VOLE_API_KEY),e.VOLE_PROMPT_MODE!==void 0&&(t.runtime.promptMode=e.VOLE_PROMPT_MODE),e.VOLE_EXECUTION_CONTRACT!==void 0&&(t.runtime.executionContract=e.VOLE_EXECUTION_CONTRACT),e.VOLE_TOOL_PROFILE!==void 0&&(t.runtime.toolProfile=e.VOLE_TOOL_PROFILE),e.VOLE_SANDBOX!==void 0&&(t.runtime.sandboxed=e.VOLE_SANDBOX==="true"),e.VOLE_THINKING_BUDGET!==void 0&&(t.model.thinkingBudget=e.VOLE_THINKING_BUDGET)}function wd(t){if(t.model.provider!=="openai-compatible"&&t.model.provider!=="anthropic")throw new K(`Invalid model.provider "${String(t.model.provider)}". Expected openai-compatible or anthropic.`);if(t.model.model.trim().length===0)throw new K("No model configured. Set VOLE_MODEL=<model-name> (e.g. VOLE_MODEL=openai/gpt-4o for OpenRouter).");if(!xd(t.runtime.defaultMode))throw new K(`Invalid runtime.defaultMode "${String(t.runtime.defaultMode)}". Expected observe, confirm, or auto.`);if(!Sd(t.trace.verbosity))throw new K(`Invalid trace.verbosity "${String(t.trace.verbosity)}". Expected explainable or debug.`);if(!vd(t.memory.longTermFiles))throw new K(`Invalid memory.longTermFiles "${String(t.memory.longTermFiles)}". Expected disabled or read-only.`);if(t.memory.writes!=="disabled")throw new K(`Invalid memory.writes "${String(t.memory.writes)}". Only disabled is supported.`);if(t.runtime.promptMode!==void 0&&!Ed(t.runtime.promptMode))throw new K(`Invalid runtime.promptMode "${String(t.runtime.promptMode)}". Expected full, minimal, or none.`);if(t.runtime.executionContract!==void 0&&!kd(t.runtime.executionContract))throw new K(`Invalid runtime.executionContract "${String(t.runtime.executionContract)}". Expected default or strict-agentic.`);if(t.runtime.toolProfile!==void 0&&!Rd(t.runtime.toolProfile))throw new K(`Invalid runtime.toolProfile "${String(t.runtime.toolProfile)}". Expected coding, full, messaging, or background.`);if(t.model.thinkingBudget!==void 0&&!Pd(t.model.thinkingBudget))throw new K(`Invalid model.thinkingBudget "${String(t.model.thinkingBudget)}". Expected off, minimal, low, medium, high, max, or adaptive.`)}function _a(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function xd(t){return t==="observe"||t==="confirm"||t==="auto"}function Sd(t){return t==="explainable"||t==="debug"}function vd(t){return t==="disabled"||t==="read-only"||t==="write"}function Ed(t){return t==="full"||t==="minimal"||t==="none"}function kd(t){return t==="default"||t==="strict-agentic"}function Rd(t){return t==="coding"||t==="full"||t==="messaging"||t==="background"}function Pd(t){return t==="off"||t==="minimal"||t==="low"||t==="medium"||t==="high"||t==="max"||t==="adaptive"}function ba(t,e){let r=t.sessions.directory;if(!r.startsWith("~/"))return r;let s=e?.HOME??process.env.HOME;return s===void 0?r:pd(s,r.slice(2))}import{readFile as Td}from"fs/promises";import{join as Ad}from"path";var ss=class{async assemble(e){let r=[];return e.systemInstruction&&r.push({role:"system",content:e.systemInstruction}),e.recentMessages&&r.push(...e.recentMessages),r.push({role:"user",content:e.userMessage}),{modelInput:{messages:r},report:{includedSections:e.systemInstruction?["identity"]:[],omittedSections:["runtime","tooling","safety","skills","workspace"],sections:[]}}}},ns=class{#e;#t;constructor(e={}){this.#e=e.workspacePromptFiles??[],this.#t=e.readWorkspaceFile??(r=>Td(r,"utf8"))}async assemble(e){let r=e.promptMode??"full",s=[],n=[];if(r==="none"){let c=e.recentMessages??[];c.length>0&&s.push({name:"conversation_history",included:!0}),s.push({name:"user_message",included:!0});let l=s.filter(d=>d.included).map(d=>d.name),u=s.filter(d=>!d.included).map(d=>d.name);return{modelInput:{messages:[...c.map(d=>({...d})),{role:"user",content:e.userMessage}]},report:{includedSections:l,omittedSections:u,sections:s}}}if(n.push(`<identity>
|
|
14
14
|
${e.systemInstruction}
|
|
15
15
|
</identity>`),s.push({name:"identity",included:!0}),r==="full"){if(e.runtime?(n.push("",`<runtime>
|
|
16
16
|
- Mode: ${e.runtime.mode}
|
|
@@ -32,15 +32,15 @@ ${l}
|
|
|
32
32
|
|
|
33
33
|
${d}`}]});return p.type!=="message"||!p.content?u:[...o!==void 0?[o]:[],{role:"system",content:`Conversation summary:
|
|
34
34
|
${p.content}`},...c]}catch{return u}}function Cd(t){if(t.role!=="tool"||t.content===null)return t;let e;try{e=JSON.parse(t.content)}catch{return t.content.length>400?{...t,content:`${t.content.slice(0,400)}
|
|
35
|
-
[${t.content.length-400} chars omitted]`}:t}let r={};return"ok"in e&&(r.ok=e.ok),"summary"in e&&typeof e.summary=="string"&&(r.summary=e.summary),"exitCode"in e&&(r.exitCode=e.exitCode),"error"in e&&(r.error=e.error),"type"in e&&(r.type=e.type),"result"in e&&typeof e.result=="string"&&e.result.length<=200&&(r.result=e.result),{...t,content:JSON.stringify(r)}}function _(t,e,r,s,n){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(t,r):n?n.value=r:e.set(t,r),r}function f(t,e,r,s){if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?s:r==="a"?s.call(t):s?s.value:e.get(t)}var
|
|
35
|
+
[${t.content.length-400} chars omitted]`}:t}let r={};return"ok"in e&&(r.ok=e.ok),"summary"in e&&typeof e.summary=="string"&&(r.summary=e.summary),"exitCode"in e&&(r.exitCode=e.exitCode),"error"in e&&(r.error=e.error),"type"in e&&(r.type=e.type),"result"in e&&typeof e.result=="string"&&e.result.length<=200&&(r.result=e.result),{...t,content:JSON.stringify(r)}}function _(t,e,r,s,n){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(t,r):n?n.value=r:e.set(t,r),r}function f(t,e,r,s){if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?s:r==="a"?s.call(t):s?s.value:e.get(t)}var $n=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return $n=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^r()&15>>+s/4).toString(16))};function me(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var ir=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var w=class extends Error{},B=class t extends w{constructor(e,r,s,n,o){super(`${t.makeMessage(e,r,s)}`),this.status=e,this.headers=n,this.requestID=n?.get("request-id"),this.error=r,this.type=o??null}static makeMessage(e,r,s){let n=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):s;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,r,s,n){if(!e||!n)return new Re({message:s,cause:ir(r)});let o=r,i=o?.error?.type;return e===400?new mt(e,o,s,n,i):e===401?new gt(e,o,s,n,i):e===403?new yt(e,o,s,n,i):e===404?new _t(e,o,s,n,i):e===409?new bt(e,o,s,n,i):e===422?new wt(e,o,s,n,i):e===429?new xt(e,o,s,n,i):e>=500?new St(e,o,s,n,i):new t(e,o,s,n,i)}},F=class extends B{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Re=class extends B{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},pt=class extends Re{constructor({message:e}={}){super({message:e??"Request timed out."})}},mt=class extends B{},gt=class extends B{},yt=class extends B{},_t=class extends B{},bt=class extends B{},wt=class extends B{},xt=class extends B{},St=class extends B{};var Ld=/^[a-z][a-z0-9+.-]*:/i,xa=t=>Ld.test(t),jn=t=>(jn=Array.isArray,jn(t)),Bn=jn;function os(t){return typeof t!="object"?{}:t??{}}function Dn(t){if(!t)return!0;for(let e in t)return!1;return!0}function Sa(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var va=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new w(`${t} must be an integer`);if(e<0)throw new w(`${t} must be a positive integer`);return e};var is=t=>{try{return JSON.parse(t)}catch{return}};var Ea=t=>new Promise(e=>setTimeout(e,t));var Pe="0.92.0";var Ta=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function $d(){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 jd=()=>{let t=$d();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Pe,"X-Stainless-OS":Ra(Deno.build.os),"X-Stainless-Arch":ka(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":Pe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Pe,"X-Stainless-OS":Ra(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ka(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Bd();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Pe,"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":Pe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Bd(){if(typeof navigator>"u"||!navigator)return null;let t=[{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:r}of t){let s=r.exec(navigator.userAgent);if(s){let n=s[1]||0,o=s[2]||0,i=s[3]||0;return{browser:e,version:`${n}.${o}.${i}`}}}return null}var ka=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Ra=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),Pa,Aa=()=>Pa??(Pa=jd());function Oa(){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 Un(...t){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(...t)}function as(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Un({start(){},async pull(r){let{done:s,value:n}=await e.next();s?r.close():r.enqueue(n)},async cancel(){await e.return?.()}})}function ar(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Ia(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}var Ma=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function Ca(t){return Object.entries(t).filter(([e,r])=>typeof r<"u").map(([e,r])=>{if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return`${encodeURIComponent(e)}=${encodeURIComponent(r)}`;if(r===null)return`${encodeURIComponent(e)}=`;throw new w(`Cannot stringify type ${typeof r}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}function $a(t){let e=0;for(let n of t)e+=n.length;let r=new Uint8Array(e),s=0;for(let n of t)r.set(n,s),s+=n.length;return r}var Na;function cr(t){let e;return(Na??(e=new globalThis.TextEncoder,Na=e.encode.bind(e)))(t)}var La;function qn(t){let e;return(La??(e=new globalThis.TextDecoder,La=e.decode.bind(e)))(t)}var X,Q,ge=class{constructor(){X.set(this,void 0),Q.set(this,void 0),_(this,X,new Uint8Array,"f"),_(this,Q,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?cr(e):e;_(this,X,$a([f(this,X,"f"),r]),"f");let s=[],n;for(;(n=qd(f(this,X,"f"),f(this,Q,"f")))!=null;){if(n.carriage&&f(this,Q,"f")==null){_(this,Q,n.index,"f");continue}if(f(this,Q,"f")!=null&&(n.index!==f(this,Q,"f")+1||n.carriage)){s.push(qn(f(this,X,"f").subarray(0,f(this,Q,"f")-1))),_(this,X,f(this,X,"f").subarray(f(this,Q,"f")),"f"),_(this,Q,null,"f");continue}let o=f(this,Q,"f")!==null?n.preceding-1:n.preceding,i=qn(f(this,X,"f").subarray(0,o));s.push(i),_(this,X,f(this,X,"f").subarray(n.index),"f"),_(this,Q,null,"f")}return s}flush(){return f(this,X,"f").length?this.decode(`
|
|
36
36
|
`):[]}};X=new WeakMap,Q=new WeakMap;ge.NEWLINE_CHARS=new Set([`
|
|
37
|
-
`,"\r"]);ge.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function qd(t,e){for(let n=e??0;n<t.length;n++){if(t[n]===10)return{preceding:n,index:n+1,carriage:!1};if(t[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function ja(t){for(let s=0;s<t.length-1;s++){if(t[s]===10&&t[s+1]===10||t[s]===13&&t[s+1]===13)return s+2;if(t[s]===13&&t[s+1]===10&&s+3<t.length&&t[s+2]===13&&t[s+3]===10)return s+4}return-1}var ls={off:0,error:200,warn:300,info:400,debug:500},
|
|
38
|
-
`);s.enqueue(i)}catch(n){s.error(n)}},async cancel(){await r.return?.()}})}};async function*Hd(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new w("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 w("Attempted to iterate over a response with no body");let r=new
|
|
39
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,s,n]=Vd(e,":");return n.startsWith(" ")&&(n=n.substring(1)),r==="event"?this.event=n:r==="data"&&this.data.push(n),null}};function Vd(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function us(t,e){let{response:r,requestLogID:s,retryOfRequestLogID:n,startTime:o}=e,i=await(async()=>{if(e.options.stream)return D(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller):le.fromSSEResponse(r,e.controller);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let c=r.headers.get("content-type")?.split(";")[0]?.trim();if(c?.includes("application/json")||c?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let p=await r.json();return
|
|
37
|
+
`,"\r"]);ge.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function qd(t,e){for(let n=e??0;n<t.length;n++){if(t[n]===10)return{preceding:n,index:n+1,carriage:!1};if(t[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function ja(t){for(let s=0;s<t.length-1;s++){if(t[s]===10&&t[s+1]===10||t[s]===13&&t[s+1]===13)return s+2;if(t[s]===13&&t[s+1]===10&&s+3<t.length&&t[s+2]===13&&t[s+3]===10)return s+4}return-1}var ls={off:0,error:200,warn:300,info:400,debug:500},Fn=(t,e,r)=>{if(t){if(Sa(ls,t))return t;D(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(ls))}`)}};function lr(){}function cs(t,e,r){return!e||ls[t]>ls[r]?lr:e[t].bind(e)}var Fd={error:lr,warn:lr,info:lr,debug:lr},Ba=new WeakMap;function D(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Fd;let s=Ba.get(e);if(s&&s[0]===r)return s[1];let n={error:cs("error",e,r),warn:cs("warn",e,r),info:cs("info",e,r),debug:cs("debug",e,r)};return Ba.set(e,[r,n]),n}var ye=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var ur,le=class t{constructor(e,r,s){this.iterator=e,ur.set(this,void 0),this.controller=r,_(this,ur,s,"f")}static fromSSEResponse(e,r,s){let n=!1,o=s?D(s):console;async function*i(){if(n)throw new w("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(let c of Hd(e,r)){if(c.event==="completion")try{yield JSON.parse(c.data)}catch(l){throw o.error("Could not parse message into JSON:",c.data),o.error("From chunk:",c.raw),l}if(c.event==="message_start"||c.event==="message_delta"||c.event==="message_stop"||c.event==="content_block_start"||c.event==="content_block_delta"||c.event==="content_block_stop"||c.event==="message"||c.event==="user.message"||c.event==="user.interrupt"||c.event==="user.tool_confirmation"||c.event==="user.custom_tool_result"||c.event==="agent.message"||c.event==="agent.thinking"||c.event==="agent.tool_use"||c.event==="agent.tool_result"||c.event==="agent.mcp_tool_use"||c.event==="agent.mcp_tool_result"||c.event==="agent.custom_tool_use"||c.event==="agent.thread_context_compacted"||c.event==="session.status_running"||c.event==="session.status_idle"||c.event==="session.status_rescheduled"||c.event==="session.status_terminated"||c.event==="session.error"||c.event==="session.deleted"||c.event==="span.model_request_start"||c.event==="span.model_request_end")try{yield JSON.parse(c.data)}catch(l){throw o.error("Could not parse message into JSON:",c.data),o.error("From chunk:",c.raw),l}if(c.event!=="ping"&&c.event==="error"){let l=is(c.data)??c.data,u=l?.error?.type;throw new B(void 0,l,void 0,e.headers,u)}}a=!0}catch(c){if(me(c))return;throw c}finally{a||r.abort()}}return new t(i,r,s)}static fromReadableStream(e,r,s){let n=!1;async function*o(){let a=new ge,c=ar(e);for await(let l of c)for(let u of a.decode(l))yield u;for(let l of a.flush())yield l}async function*i(){if(n)throw new w("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(let c of o())a||c&&(yield JSON.parse(c));a=!0}catch(c){if(me(c))return;throw c}finally{a||r.abort()}}return new t(i,r,s)}[(ur=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],s=this.iterator(),n=o=>({next:()=>{if(o.length===0){let i=s.next();e.push(i),r.push(i)}return o.shift()}});return[new t(()=>n(e),this.controller,f(this,ur,"f")),new t(()=>n(r),this.controller,f(this,ur,"f"))]}toReadableStream(){let e=this,r;return Un({async start(){r=e[Symbol.asyncIterator]()},async pull(s){try{let{value:n,done:o}=await r.next();if(o)return s.close();let i=cr(JSON.stringify(n)+`
|
|
38
|
+
`);s.enqueue(i)}catch(n){s.error(n)}},async cancel(){await r.return?.()}})}};async function*Hd(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new w("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 w("Attempted to iterate over a response with no body");let r=new Hn,s=new ge,n=ar(t.body);for await(let o of Wd(n))for(let i of s.decode(o)){let a=r.decode(i);a&&(yield a)}for(let o of s.flush()){let i=r.decode(o);i&&(yield i)}}async function*Wd(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let s=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?cr(r):r,n=new Uint8Array(e.length+s.length);n.set(e),n.set(s,e.length),e=n;let o;for(;(o=ja(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var Hn=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(`
|
|
39
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,s,n]=Vd(e,":");return n.startsWith(" ")&&(n=n.substring(1)),r==="event"?this.event=n:r==="data"&&this.data.push(n),null}};function Vd(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function us(t,e){let{response:r,requestLogID:s,retryOfRequestLogID:n,startTime:o}=e,i=await(async()=>{if(e.options.stream)return D(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller):le.fromSSEResponse(r,e.controller);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let c=r.headers.get("content-type")?.split(";")[0]?.trim();if(c?.includes("application/json")||c?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let p=await r.json();return Wn(p,r)}return await r.text()})();return D(t).debug(`[${s}] response parsed`,ye({retryOfRequestLogID:n,url:r.url,status:r.status,body:i,durationMs:Date.now()-o})),i}function Wn(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var dr,He=class t extends Promise{constructor(e,r,s=us){super(n=>{n(null)}),this.responsePromise=r,this.parseResponse=s,dr.set(this,void 0),_(this,dr,e,"f")}_thenUnwrap(e){return new t(f(this,dr,"f"),this.responsePromise,async(r,s)=>Wn(e(await this.parseResponse(r,s),s),s.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(f(this,dr,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};dr=new WeakMap;var ds,fs=class{constructor(e,r,s,n){ds.set(this,void 0),_(this,ds,e,"f"),this.options=n,this.response=r,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new w("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await f(this,ds,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ds=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},fr=class extends He{constructor(e,r,s){super(e,r,async(n,o)=>new s(n,o.response,await us(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},re=class extends fs{constructor(e,r,s,n){super(e,r,s,n),this.data=s.data||[],this.has_more=s.has_more||!1,this.first_id=s.first_id||null,this.last_id=s.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let r=this.first_id;return r?{...this.options,query:{...os(this.options.query),before_id:r}}:null}let e=this.last_id;return e?{...this.options,query:{...os(this.options.query),after_id:e}}:null}};var P=class extends fs{constructor(e,r,s,n){super(e,r,s,n),this.data=s.data||[],this.next_page=s.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...os(this.options.query),page:e}}:null}};var Gn=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.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 We(t,e,r){return Gn(),new File(t,e??"unknown_file",r)}function hr(t,e){let r=typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"";return e?r.split(/[\\/]/).pop()||void 0:r}var Kn=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function";var vt=async(t,e,r=!0)=>({...t,body:await zd(t.body,e,r)}),Da=new WeakMap;function Kd(t){let e=typeof t=="function"?t:t.fetch,r=Da.get(e);if(r)return r;let s=(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 Da.set(e,s),s}var zd=async(t,e,r=!0)=>{if(!await Kd(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let s=new FormData;return await Promise.all(Object.entries(t||{}).map(([n,o])=>Vn(s,n,o,r))),s},Jd=t=>t instanceof Blob&&"name"in t;var Vn=async(t,e,r,s)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(r instanceof Response){let n={},o=r.headers.get("Content-Type");o&&(n={type:o}),t.append(e,We([await r.blob()],hr(r,s),n))}else if(Kn(r))t.append(e,We([await new Response(as(r)).blob()],hr(r,s)));else if(Jd(r))t.append(e,We([r],hr(r,s),{type:r.type}));else if(Array.isArray(r))await Promise.all(r.map(n=>Vn(t,e+"[]",n,s)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>Vn(t,`${e}[${n}]`,o,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var Ua=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",Yd=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Ua(t),Xd=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function hs(t,e,r){if(Gn(),t=await t,e||(e=hr(t,!0)),Yd(t))return t instanceof File&&e==null&&r==null?t:We([await t.arrayBuffer()],e??t.name,{type:t.type,lastModified:t.lastModified,...r});if(Xd(t)){let n=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),We(await zn(n),e,r)}let s=await zn(t);if(!r?.type){let n=s.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(r={...r,type:n})}return We(s,e,r)}async function zn(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Ua(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Kn(t))for await(let r of t)e.push(...await zn(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${Qd(t)}`)}return e}function Qd(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var E=class{constructor(e){this._client=e}};var qa=Symbol.for("brand.privateNullableHeaders");function*ef(t){if(!t)return;if(qa in t){let{values:s,nulls:n}=t;yield*s.entries();for(let o of n)yield[o,null];return}let e=!1,r;t instanceof Headers?r=t.entries():Bn(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let s of r){let n=s[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let o=Bn(s[1])?s[1]:[s[1]],i=!1;for(let a of o)a!==void 0&&(e&&!i&&(i=!0,yield[n,null]),yield[n,a])}}var m=t=>{let e=new Headers,r=new Set;for(let s of t){let n=new Set;for(let[o,i]of ef(s)){let a=o.toLowerCase();n.has(a)||(e.delete(o),n.add(a)),i===null?(e.delete(o),r.add(a)):(e.append(o,i),r.delete(a))}}return{[qa]:!0,values:e,nulls:r}};function Ha(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Fa=Object.freeze(Object.create(null)),tf=(t=Ha)=>function(r,...s){if(r.length===1)return r[0];let n=!1,o=[],i=r.reduce((u,d,p)=>{/[?#]/.test(d)&&(n=!0);let h=s[p],g=(n?encodeURIComponent:t)(""+h);return p!==s.length&&(h==null||typeof h=="object"&&h.toString===Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??Fa)??Fa)?.toString)&&(g=h+"",o.push({start:u.length+d.length,length:g.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),u+d+(p===s.length?"":g)},""),a=i.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(a))!==null;)o.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(o.sort((u,d)=>u.start-d.start),o.length>0){let u=0,d=o.reduce((p,h)=>{let g=" ".repeat(h.start-u),b="^".repeat(h.length);return u=h.start+h.length,p+g+b},"");throw new w(`Path parameters result in path with invalid segments:
|
|
40
40
|
${o.map(p=>p.error).join(`
|
|
41
41
|
`)}
|
|
42
42
|
${i}
|
|
43
|
-
${d}`)}return i},y=tf(Ha);var Et=class extends E{create(e,r){let{betas:s,...n}=e;return this._client.post("/v1/environments?beta=true",{body:n,...r,headers:m([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/environments/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}update(e,r,s){let{betas:n,...o}=r;return this._client.post(y`/v1/environments/${e}?beta=true`,{body:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/environments?beta=true",P,{query:n,...r,headers:m([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,r={},s){let{betas:n}=r??{};return this._client.delete(y`/v1/environments/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}archive(e,r={},s){let{betas:n}=r??{};return this._client.post(y`/v1/environments/${e}/archive?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};var pr=Symbol("anthropic.sdk.stainlessHelper");function ps(t){return typeof t=="object"&&t!==null&&pr in t}function Yn(t,e){let r=new Set;if(t)for(let s of t)ps(s)&&r.add(s[pr]);if(e){for(let s of e)if(ps(s)&&r.add(s[pr]),Array.isArray(s.content))for(let n of s.content)ps(n)&&r.add(n[pr])}return Array.from(r)}function ms(t,e){let r=Yn(t,e);return r.length===0?{}:{"x-stainless-helper":r.join(", ")}}function Wa(t){return ps(t)?{"x-stainless-helper":t[pr]}:{}}var kt=class extends E{list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/files?beta=true",se,{query:n,...r,headers:m([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},r?.headers])})}delete(e,r={},s){let{betas:n}=r??{};return this._client.delete(y`/v1/files/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},s?.headers])})}download(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/files/${e}/content?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}retrieveMetadata(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/files/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},s?.headers])})}upload(e,r){let{betas:s,...n}=e;return this._client.post("/v1/files?beta=true",vt({body:n,...r,headers:m([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},Wa(n.file),r?.headers])},this._client))}};var Rt=class extends E{retrieve(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/models/${e}?beta=true`,{...s,headers:m([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/models?beta=true",se,{query:n,...r,headers:m([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},r?.headers])})}};var Pt=class extends E{create(e,r){let{betas:s,...n}=e;return this._client.post("/v1/user_profiles?beta=true",{body:n,...r,headers:m([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}retrieve(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/user_profiles/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"user-profiles-2026-03-24"].toString()},s?.headers])})}update(e,r,s){let{betas:n,...o}=r;return this._client.post(y`/v1/user_profiles/${e}?beta=true`,{body:o,...s,headers:m([{"anthropic-beta":[...n??[],"user-profiles-2026-03-24"].toString()},s?.headers])})}list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/user_profiles?beta=true",P,{query:n,...r,headers:m([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}createEnrollmentURL(e,r={},s){let{betas:n}=r??{};return this._client.post(y`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"user-profiles-2026-03-24"].toString()},s?.headers])})}};var Tt=class extends E{list(e,r={},s){let{betas:n,...o}=r??{};return this._client.getAPIList(y`/v1/agents/${e}/versions?beta=true`,P,{query:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};var Ve=class extends E{constructor(){super(...arguments),this.versions=new Tt(this._client)}create(e,r){let{betas:s,...n}=e;return this._client.post("/v1/agents?beta=true",{body:n,...r,headers:m([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,r={},s){let{betas:n,...o}=r??{};return this._client.get(y`/v1/agents/${e}?beta=true`,{query:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}update(e,r,s){let{betas:n,...o}=r;return this._client.post(y`/v1/agents/${e}?beta=true`,{body:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/agents?beta=true",P,{query:n,...r,headers:m([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,r={},s){let{betas:n}=r??{};return this._client.post(y`/v1/agents/${e}/archive?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};Ve.Versions=Tt;var At=class extends E{create(e,r,s){let{view:n,betas:o,...i}=r;return this._client.post(y`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:n},body:i,...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}retrieve(e,r,s){let{memory_store_id:n,betas:o,...i}=r;return this._client.get(y`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:i,...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}update(e,r,s){let{memory_store_id:n,view:o,betas:i,...a}=r;return this._client.post(y`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:{view:o},body:a,...s,headers:m([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}list(e,r={},s){let{betas:n,...o}=r??{};return this._client.getAPIList(y`/v1/memory_stores/${e}/memories?beta=true`,P,{query:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}delete(e,r,s){let{memory_store_id:n,expected_content_sha256:o,betas:i}=r;return this._client.delete(y`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:{expected_content_sha256:o},...s,headers:m([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};var Ot=class extends E{retrieve(e,r,s){let{memory_store_id:n,betas:o,...i}=r;return this._client.get(y`/v1/memory_stores/${n}/memory_versions/${e}?beta=true`,{query:i,...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}list(e,r={},s){let{betas:n,...o}=r??{};return this._client.getAPIList(y`/v1/memory_stores/${e}/memory_versions?beta=true`,P,{query:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}redact(e,r,s){let{memory_store_id:n,betas:o}=r;return this._client.post(y`/v1/memory_stores/${n}/memory_versions/${e}/redact?beta=true`,{...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};var Te=class extends E{constructor(){super(...arguments),this.memories=new At(this._client),this.memoryVersions=new Ot(this._client)}create(e,r){let{betas:s,...n}=e;return this._client.post("/v1/memory_stores?beta=true",{body:n,...r,headers:m([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/memory_stores/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}update(e,r,s){let{betas:n,...o}=r;return this._client.post(y`/v1/memory_stores/${e}?beta=true`,{body:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/memory_stores?beta=true",P,{query:n,...r,headers:m([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,r={},s){let{betas:n}=r??{};return this._client.delete(y`/v1/memory_stores/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}archive(e,r={},s){let{betas:n}=r??{};return this._client.post(y`/v1/memory_stores/${e}/archive?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};Te.Memories=At;Te.MemoryVersions=Ot;var It=class t{constructor(e,r){this.iterator=e,this.controller=r}async*decoder(){let e=new ge;for await(let r of this.iterator)for(let s of e.decode(r))yield JSON.parse(s);for(let r of e.flush())yield JSON.parse(r)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,r){if(!e.body)throw r.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new w("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 w("Attempted to iterate over a response with no body");return new t(ar(e.body),r)}};var Mt=class extends E{create(e,r){let{betas:s,...n}=e;return this._client.post("/v1/messages/batches?beta=true",{body:n,...r,headers:m([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r?.headers])})}retrieve(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/messages/batches/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},s?.headers])})}list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",se,{query:n,...r,headers:m([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r?.headers])})}delete(e,r={},s){let{betas:n}=r??{};return this._client.delete(y`/v1/messages/batches/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},s?.headers])})}cancel(e,r={},s){let{betas:n}=r??{};return this._client.post(y`/v1/messages/batches/${e}/cancel?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},s?.headers])})}async results(e,r={},s){let n=await this.retrieve(e);if(!n.results_url)throw new w(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);let{betas:o}=r??{};return this._client.get(n.results_url,{...s,headers:m([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},s?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((i,a)=>It.fromResponse(a.response,a.controller))}};var gs={"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 Va(t){return t?.output_format??t?.output_config?.format}function Xn(t,e,r){let s=Va(e);return!e||!("parse"in(s??{}))?{...t,content:t.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 r.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return n}),parsed_output:null}:Qn(t,e,r)}function Qn(t,e,r){let s=null,n=t.content.map(o=>{if(o.type==="text"){let i=hf(e,o.text);s===null&&(s=i);let a=Object.defineProperty({...o},"parsed_output",{value:i,enumerable:!1});return Object.defineProperty(a,"parsed",{get(){return r.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),i},enumerable:!1})}return o});return{...t,content:n,parsed_output:s}}function hf(t,e){let r=Va(t);if(r?.type!=="json_schema")return null;try{return"parse"in r?r.parse(e):JSON.parse(e)}catch(s){throw new w(`Failed to parse structured output: ${s}`)}}var pf=t=>{let e=0,r=[];for(;e<t.length;){let s=t[e];if(s==="\\"){e++;continue}if(s==="{"){r.push({type:"brace",value:"{"}),e++;continue}if(s==="}"){r.push({type:"brace",value:"}"}),e++;continue}if(s==="["){r.push({type:"paren",value:"["}),e++;continue}if(s==="]"){r.push({type:"paren",value:"]"}),e++;continue}if(s===":"){r.push({type:"separator",value:":"}),e++;continue}if(s===","){r.push({type:"delimiter",value:","}),e++;continue}if(s==='"'){let a="",c=!1;for(s=t[++e];s!=='"';){if(e===t.length){c=!0;break}if(s==="\\"){if(e++,e===t.length){c=!0;break}a+=s+t[e],s=t[++e]}else a+=s,s=t[++e]}s=t[++e],c||r.push({type:"string",value:a});continue}if(s&&/\s/.test(s)){e++;continue}let o=/[0-9]/;if(s&&o.test(s)||s==="-"||s==="."){let a="";for(s==="-"&&(a+=s,s=t[++e]);s&&o.test(s)||s===".";)a+=s,s=t[++e];r.push({type:"number",value:a});continue}let i=/[a-z]/i;if(s&&i.test(s)){let a="";for(;s&&i.test(s)&&e!==t.length;)a+=s,s=t[++e];if(a=="true"||a=="false"||a==="null")r.push({type:"name",value:a});else{e++;continue}continue}e++}return r},Ct=t=>{if(t.length===0)return t;let e=t[t.length-1];switch(e.type){case"separator":return t=t.slice(0,t.length-1),Ct(t);break;case"number":let r=e.value[e.value.length-1];if(r==="."||r==="-")return t=t.slice(0,t.length-1),Ct(t);case"string":let s=t[t.length-2];if(s?.type==="delimiter")return t=t.slice(0,t.length-1),Ct(t);if(s?.type==="brace"&&s.value==="{")return t=t.slice(0,t.length-1),Ct(t);break;case"delimiter":return t=t.slice(0,t.length-1),Ct(t);break}return t},mf=t=>{let e=[];return t.map(r=>{r.type==="brace"&&(r.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),r.type==="paren"&&(r.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(r=>{r==="}"?t.push({type:"brace",value:"}"}):r==="]"&&t.push({type:"paren",value:"]"})}),t},gf=t=>{let e="";return t.map(r=>{r.type==="string"?e+='"'+r.value+'"':e+=r.value}),e},ys=t=>JSON.parse(gf(mf(Ct(pf(t)))));var ne,Ae,Nt,mr,_s,gr,yr,bs,_r,_e,br,ws,xs,Ge,Ss,vs,wr,Zn,Ga,Es,eo,to,ro,Ka,za="__json_buf";function Ja(t){return t.type==="tool_use"||t.type==="server_tool_use"||t.type==="mcp_tool_use"}var ks=class t{constructor(e,r){ne.add(this),this.messages=[],this.receivedMessages=[],Ae.set(this,void 0),Nt.set(this,null),this.controller=new AbortController,mr.set(this,void 0),_s.set(this,()=>{}),gr.set(this,()=>{}),yr.set(this,void 0),bs.set(this,()=>{}),_r.set(this,()=>{}),_e.set(this,{}),br.set(this,!1),ws.set(this,!1),xs.set(this,!1),Ge.set(this,!1),Ss.set(this,void 0),vs.set(this,void 0),wr.set(this,void 0),Es.set(this,s=>{if(_(this,ws,!0,"f"),me(s)&&(s=new F),s instanceof F)return _(this,xs,!0,"f"),this._emit("abort",s);if(s instanceof w)return this._emit("error",s);if(s instanceof Error){let n=new w(s.message);return n.cause=s,this._emit("error",n)}return this._emit("error",new w(String(s)))}),_(this,mr,new Promise((s,n)=>{_(this,_s,s,"f"),_(this,gr,n,"f")}),"f"),_(this,yr,new Promise((s,n)=>{_(this,bs,s,"f"),_(this,_r,n,"f")}),"f"),f(this,mr,"f").catch(()=>{}),f(this,yr,"f").catch(()=>{}),_(this,Nt,e,"f"),_(this,wr,r?.logger??console,"f")}get response(){return f(this,Ss,"f")}get request_id(){return f(this,vs,"f")}async withResponse(){_(this,Ge,!0,"f");let e=await f(this,mr,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createMessage(e,r,s,{logger:n}={}){let o=new t(r,{logger:n});for(let i of r.messages)o._addMessageParam(i);return _(o,Nt,{...r,stream:!0},"f"),o._run(()=>o._createMessage(e,{...r,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},f(this,Es,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,r=!0){this.receivedMessages.push(e),r&&this._emit("message",e)}async _createMessage(e,r,s){let n=s?.signal,o;n&&(n.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),n.addEventListener("abort",o));try{f(this,ne,"m",eo).call(this);let{response:i,data:a}=await e.create({...r,stream:!0},{...s,signal:this.controller.signal}).withResponse();this._connected(i);for await(let c of a)f(this,ne,"m",to).call(this,c);if(a.controller.signal?.aborted)throw new F;f(this,ne,"m",ro).call(this)}finally{n&&o&&n.removeEventListener("abort",o)}}_connected(e){this.ended||(_(this,Ss,e,"f"),_(this,vs,e?.headers.get("request-id"),"f"),f(this,_s,"f").call(this,e),this._emit("connect"))}get ended(){return f(this,br,"f")}get errored(){return f(this,ws,"f")}get aborted(){return f(this,xs,"f")}abort(){this.controller.abort()}on(e,r){return(f(this,_e,"f")[e]||(f(this,_e,"f")[e]=[])).push({listener:r}),this}off(e,r){let s=f(this,_e,"f")[e];if(!s)return this;let n=s.findIndex(o=>o.listener===r);return n>=0&&s.splice(n,1),this}once(e,r){return(f(this,_e,"f")[e]||(f(this,_e,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,s)=>{_(this,Ge,!0,"f"),e!=="error"&&this.once("error",s),this.once(e,r)})}async done(){_(this,Ge,!0,"f"),await f(this,yr,"f")}get currentMessage(){return f(this,Ae,"f")}async finalMessage(){return await this.done(),f(this,ne,"m",Zn).call(this)}async finalText(){return await this.done(),f(this,ne,"m",Ga).call(this)}_emit(e,...r){if(f(this,br,"f"))return;e==="end"&&(_(this,br,!0,"f"),f(this,bs,"f").call(this));let s=f(this,_e,"f")[e];if(s&&(f(this,_e,"f")[e]=s.filter(n=>!n.once),s.forEach(({listener:n})=>n(...r))),e==="abort"){let n=r[0];!f(this,Ge,"f")&&!s?.length&&Promise.reject(n),f(this,gr,"f").call(this,n),f(this,_r,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=r[0];!f(this,Ge,"f")&&!s?.length&&Promise.reject(n),f(this,gr,"f").call(this,n),f(this,_r,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",f(this,ne,"m",Zn).call(this))}async _fromReadableStream(e,r){let s=r?.signal,n;s&&(s.aborted&&this.controller.abort(),n=this.controller.abort.bind(this.controller),s.addEventListener("abort",n));try{f(this,ne,"m",eo).call(this),this._connected(null);let o=le.fromReadableStream(e,this.controller);for await(let i of o)f(this,ne,"m",to).call(this,i);if(o.controller.signal?.aborted)throw new F;f(this,ne,"m",ro).call(this)}finally{s&&n&&s.removeEventListener("abort",n)}}[(Ae=new WeakMap,Nt=new WeakMap,mr=new WeakMap,_s=new WeakMap,gr=new WeakMap,yr=new WeakMap,bs=new WeakMap,_r=new WeakMap,_e=new WeakMap,br=new WeakMap,ws=new WeakMap,xs=new WeakMap,Ge=new WeakMap,Ss=new WeakMap,vs=new WeakMap,wr=new WeakMap,Es=new WeakMap,ne=new WeakSet,Zn=function(){if(this.receivedMessages.length===0)throw new w("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Ga=function(){if(this.receivedMessages.length===0)throw new w("stream ended without producing a Message with role=assistant");let r=this.receivedMessages.at(-1).content.filter(s=>s.type==="text").map(s=>s.text);if(r.length===0)throw new w("stream ended without producing a content block with type=text");return r.join(" ")},eo=function(){this.ended||_(this,Ae,void 0,"f")},to=function(r){if(this.ended)return;let s=f(this,ne,"m",Ka).call(this,r);switch(this._emit("streamEvent",r,s),r.type){case"content_block_delta":{let n=s.content.at(-1);switch(r.delta.type){case"text_delta":{n.type==="text"&&this._emit("text",r.delta.text,n.text||"");break}case"citations_delta":{n.type==="text"&&this._emit("citation",r.delta.citation,n.citations??[]);break}case"input_json_delta":{Ja(n)&&n.input&&this._emit("inputJson",r.delta.partial_json,n.input);break}case"thinking_delta":{n.type==="thinking"&&this._emit("thinking",r.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:r.delta}break}case"message_stop":{this._addMessageParam(s),this._addMessage(Xn(s,f(this,Nt,"f"),{logger:f(this,wr,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",s.content.at(-1));break}case"message_start":{_(this,Ae,s,"f");break}case"content_block_start":case"message_delta":break}},ro=function(){if(this.ended)throw new w("stream has ended, this shouldn't happen");let r=f(this,Ae,"f");if(!r)throw new w("request ended without sending any chunks");return _(this,Ae,void 0,"f"),Xn(r,f(this,Nt,"f"),{logger:f(this,wr,"f")})},Ka=function(r){let s=f(this,Ae,"f");if(r.type==="message_start"){if(s)throw new w(`Unexpected event order, got ${r.type} before receiving "message_stop"`);return r.message}if(!s)throw new w(`Unexpected event order, got ${r.type} before "message_start"`);switch(r.type){case"message_stop":return s;case"message_delta":return s.container=r.delta.container,s.stop_reason=r.delta.stop_reason,s.stop_sequence=r.delta.stop_sequence,s.usage.output_tokens=r.usage.output_tokens,s.context_management=r.context_management,r.usage.input_tokens!=null&&(s.usage.input_tokens=r.usage.input_tokens),r.usage.cache_creation_input_tokens!=null&&(s.usage.cache_creation_input_tokens=r.usage.cache_creation_input_tokens),r.usage.cache_read_input_tokens!=null&&(s.usage.cache_read_input_tokens=r.usage.cache_read_input_tokens),r.usage.server_tool_use!=null&&(s.usage.server_tool_use=r.usage.server_tool_use),r.usage.iterations!=null&&(s.usage.iterations=r.usage.iterations),s;case"content_block_start":return s.content.push(r.content_block),s;case"content_block_delta":{let n=s.content.at(r.index);switch(r.delta.type){case"text_delta":{n?.type==="text"&&(s.content[r.index]={...n,text:(n.text||"")+r.delta.text});break}case"citations_delta":{n?.type==="text"&&(s.content[r.index]={...n,citations:[...n.citations??[],r.delta.citation]});break}case"input_json_delta":{if(n&&Ja(n)){let o=n[za]||"";o+=r.delta.partial_json;let i={...n};if(Object.defineProperty(i,za,{value:o,enumerable:!1,writable:!0}),o)try{i.input=ys(o)}catch(a){let c=new w(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${a}. JSON: ${o}`);f(this,Es,"f").call(this,c)}s.content[r.index]=i}break}case"thinking_delta":{n?.type==="thinking"&&(s.content[r.index]={...n,thinking:n.thinking+r.delta.thinking});break}case"signature_delta":{n?.type==="thinking"&&(s.content[r.index]={...n,signature:r.delta.signature});break}case"compaction_delta":{n?.type==="compaction"&&(s.content[r.index]={...n,content:(n.content||"")+r.delta.content});break}default:r.delta}return s}case"content_block_stop":return s}},Symbol.asyncIterator)](){let e=[],r=[],s=!1;return this.on("streamEvent",n=>{let o=r.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(let n of r)n.resolve(void 0);r.length=0}),this.on("abort",n=>{s=!0;for(let o of r)o.reject(n);r.length=0}),this.on("error",n=>{s=!0;for(let o of r)o.reject(n);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Ke=class extends Error{constructor(e){let r=typeof e=="string"?e:e.map(s=>s.type==="text"?s.text:`[${s.type}]`).join(" ");super(r),this.name="ToolError",this.content=e}};var Ya=`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:
|
|
43
|
+
${d}`)}return i},y=tf(Ha);var Et=class extends E{create(e,r){let{betas:s,...n}=e;return this._client.post("/v1/environments?beta=true",{body:n,...r,headers:m([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/environments/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}update(e,r,s){let{betas:n,...o}=r;return this._client.post(y`/v1/environments/${e}?beta=true`,{body:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/environments?beta=true",P,{query:n,...r,headers:m([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,r={},s){let{betas:n}=r??{};return this._client.delete(y`/v1/environments/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}archive(e,r={},s){let{betas:n}=r??{};return this._client.post(y`/v1/environments/${e}/archive?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};var pr=Symbol("anthropic.sdk.stainlessHelper");function ps(t){return typeof t=="object"&&t!==null&&pr in t}function Jn(t,e){let r=new Set;if(t)for(let s of t)ps(s)&&r.add(s[pr]);if(e){for(let s of e)if(ps(s)&&r.add(s[pr]),Array.isArray(s.content))for(let n of s.content)ps(n)&&r.add(n[pr])}return Array.from(r)}function ms(t,e){let r=Jn(t,e);return r.length===0?{}:{"x-stainless-helper":r.join(", ")}}function Wa(t){return ps(t)?{"x-stainless-helper":t[pr]}:{}}var kt=class extends E{list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/files?beta=true",re,{query:n,...r,headers:m([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},r?.headers])})}delete(e,r={},s){let{betas:n}=r??{};return this._client.delete(y`/v1/files/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},s?.headers])})}download(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/files/${e}/content?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}retrieveMetadata(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/files/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},s?.headers])})}upload(e,r){let{betas:s,...n}=e;return this._client.post("/v1/files?beta=true",vt({body:n,...r,headers:m([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},Wa(n.file),r?.headers])},this._client))}};var Rt=class extends E{retrieve(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/models/${e}?beta=true`,{...s,headers:m([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/models?beta=true",re,{query:n,...r,headers:m([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},r?.headers])})}};var Pt=class extends E{create(e,r){let{betas:s,...n}=e;return this._client.post("/v1/user_profiles?beta=true",{body:n,...r,headers:m([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}retrieve(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/user_profiles/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"user-profiles-2026-03-24"].toString()},s?.headers])})}update(e,r,s){let{betas:n,...o}=r;return this._client.post(y`/v1/user_profiles/${e}?beta=true`,{body:o,...s,headers:m([{"anthropic-beta":[...n??[],"user-profiles-2026-03-24"].toString()},s?.headers])})}list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/user_profiles?beta=true",P,{query:n,...r,headers:m([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}createEnrollmentURL(e,r={},s){let{betas:n}=r??{};return this._client.post(y`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"user-profiles-2026-03-24"].toString()},s?.headers])})}};var Tt=class extends E{list(e,r={},s){let{betas:n,...o}=r??{};return this._client.getAPIList(y`/v1/agents/${e}/versions?beta=true`,P,{query:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};var Ve=class extends E{constructor(){super(...arguments),this.versions=new Tt(this._client)}create(e,r){let{betas:s,...n}=e;return this._client.post("/v1/agents?beta=true",{body:n,...r,headers:m([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,r={},s){let{betas:n,...o}=r??{};return this._client.get(y`/v1/agents/${e}?beta=true`,{query:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}update(e,r,s){let{betas:n,...o}=r;return this._client.post(y`/v1/agents/${e}?beta=true`,{body:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/agents?beta=true",P,{query:n,...r,headers:m([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,r={},s){let{betas:n}=r??{};return this._client.post(y`/v1/agents/${e}/archive?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};Ve.Versions=Tt;var At=class extends E{create(e,r,s){let{view:n,betas:o,...i}=r;return this._client.post(y`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:n},body:i,...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}retrieve(e,r,s){let{memory_store_id:n,betas:o,...i}=r;return this._client.get(y`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:i,...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}update(e,r,s){let{memory_store_id:n,view:o,betas:i,...a}=r;return this._client.post(y`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:{view:o},body:a,...s,headers:m([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}list(e,r={},s){let{betas:n,...o}=r??{};return this._client.getAPIList(y`/v1/memory_stores/${e}/memories?beta=true`,P,{query:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}delete(e,r,s){let{memory_store_id:n,expected_content_sha256:o,betas:i}=r;return this._client.delete(y`/v1/memory_stores/${n}/memories/${e}?beta=true`,{query:{expected_content_sha256:o},...s,headers:m([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};var Ot=class extends E{retrieve(e,r,s){let{memory_store_id:n,betas:o,...i}=r;return this._client.get(y`/v1/memory_stores/${n}/memory_versions/${e}?beta=true`,{query:i,...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}list(e,r={},s){let{betas:n,...o}=r??{};return this._client.getAPIList(y`/v1/memory_stores/${e}/memory_versions?beta=true`,P,{query:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}redact(e,r,s){let{memory_store_id:n,betas:o}=r;return this._client.post(y`/v1/memory_stores/${n}/memory_versions/${e}/redact?beta=true`,{...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};var Te=class extends E{constructor(){super(...arguments),this.memories=new At(this._client),this.memoryVersions=new Ot(this._client)}create(e,r){let{betas:s,...n}=e;return this._client.post("/v1/memory_stores?beta=true",{body:n,...r,headers:m([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/memory_stores/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}update(e,r,s){let{betas:n,...o}=r;return this._client.post(y`/v1/memory_stores/${e}?beta=true`,{body:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/memory_stores?beta=true",P,{query:n,...r,headers:m([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,r={},s){let{betas:n}=r??{};return this._client.delete(y`/v1/memory_stores/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}archive(e,r={},s){let{betas:n}=r??{};return this._client.post(y`/v1/memory_stores/${e}/archive?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};Te.Memories=At;Te.MemoryVersions=Ot;var It=class t{constructor(e,r){this.iterator=e,this.controller=r}async*decoder(){let e=new ge;for await(let r of this.iterator)for(let s of e.decode(r))yield JSON.parse(s);for(let r of e.flush())yield JSON.parse(r)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,r){if(!e.body)throw r.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new w("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 w("Attempted to iterate over a response with no body");return new t(ar(e.body),r)}};var Mt=class extends E{create(e,r){let{betas:s,...n}=e;return this._client.post("/v1/messages/batches?beta=true",{body:n,...r,headers:m([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r?.headers])})}retrieve(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/messages/batches/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},s?.headers])})}list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",re,{query:n,...r,headers:m([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r?.headers])})}delete(e,r={},s){let{betas:n}=r??{};return this._client.delete(y`/v1/messages/batches/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},s?.headers])})}cancel(e,r={},s){let{betas:n}=r??{};return this._client.post(y`/v1/messages/batches/${e}/cancel?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},s?.headers])})}async results(e,r={},s){let n=await this.retrieve(e);if(!n.results_url)throw new w(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);let{betas:o}=r??{};return this._client.get(n.results_url,{...s,headers:m([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},s?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((i,a)=>It.fromResponse(a.response,a.controller))}};var gs={"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 Va(t){return t?.output_format??t?.output_config?.format}function Yn(t,e,r){let s=Va(e);return!e||!("parse"in(s??{}))?{...t,content:t.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 r.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return n}),parsed_output:null}:Xn(t,e,r)}function Xn(t,e,r){let s=null,n=t.content.map(o=>{if(o.type==="text"){let i=hf(e,o.text);s===null&&(s=i);let a=Object.defineProperty({...o},"parsed_output",{value:i,enumerable:!1});return Object.defineProperty(a,"parsed",{get(){return r.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),i},enumerable:!1})}return o});return{...t,content:n,parsed_output:s}}function hf(t,e){let r=Va(t);if(r?.type!=="json_schema")return null;try{return"parse"in r?r.parse(e):JSON.parse(e)}catch(s){throw new w(`Failed to parse structured output: ${s}`)}}var pf=t=>{let e=0,r=[];for(;e<t.length;){let s=t[e];if(s==="\\"){e++;continue}if(s==="{"){r.push({type:"brace",value:"{"}),e++;continue}if(s==="}"){r.push({type:"brace",value:"}"}),e++;continue}if(s==="["){r.push({type:"paren",value:"["}),e++;continue}if(s==="]"){r.push({type:"paren",value:"]"}),e++;continue}if(s===":"){r.push({type:"separator",value:":"}),e++;continue}if(s===","){r.push({type:"delimiter",value:","}),e++;continue}if(s==='"'){let a="",c=!1;for(s=t[++e];s!=='"';){if(e===t.length){c=!0;break}if(s==="\\"){if(e++,e===t.length){c=!0;break}a+=s+t[e],s=t[++e]}else a+=s,s=t[++e]}s=t[++e],c||r.push({type:"string",value:a});continue}if(s&&/\s/.test(s)){e++;continue}let o=/[0-9]/;if(s&&o.test(s)||s==="-"||s==="."){let a="";for(s==="-"&&(a+=s,s=t[++e]);s&&o.test(s)||s===".";)a+=s,s=t[++e];r.push({type:"number",value:a});continue}let i=/[a-z]/i;if(s&&i.test(s)){let a="";for(;s&&i.test(s)&&e!==t.length;)a+=s,s=t[++e];if(a=="true"||a=="false"||a==="null")r.push({type:"name",value:a});else{e++;continue}continue}e++}return r},Ct=t=>{if(t.length===0)return t;let e=t[t.length-1];switch(e.type){case"separator":return t=t.slice(0,t.length-1),Ct(t);break;case"number":let r=e.value[e.value.length-1];if(r==="."||r==="-")return t=t.slice(0,t.length-1),Ct(t);case"string":let s=t[t.length-2];if(s?.type==="delimiter")return t=t.slice(0,t.length-1),Ct(t);if(s?.type==="brace"&&s.value==="{")return t=t.slice(0,t.length-1),Ct(t);break;case"delimiter":return t=t.slice(0,t.length-1),Ct(t);break}return t},mf=t=>{let e=[];return t.map(r=>{r.type==="brace"&&(r.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),r.type==="paren"&&(r.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(r=>{r==="}"?t.push({type:"brace",value:"}"}):r==="]"&&t.push({type:"paren",value:"]"})}),t},gf=t=>{let e="";return t.map(r=>{r.type==="string"?e+='"'+r.value+'"':e+=r.value}),e},ys=t=>JSON.parse(gf(mf(Ct(pf(t)))));var se,Ae,Nt,mr,_s,gr,yr,bs,_r,_e,br,ws,xs,Ge,Ss,vs,wr,Qn,Ga,Es,Zn,eo,to,Ka,za="__json_buf";function Ja(t){return t.type==="tool_use"||t.type==="server_tool_use"||t.type==="mcp_tool_use"}var ks=class t{constructor(e,r){se.add(this),this.messages=[],this.receivedMessages=[],Ae.set(this,void 0),Nt.set(this,null),this.controller=new AbortController,mr.set(this,void 0),_s.set(this,()=>{}),gr.set(this,()=>{}),yr.set(this,void 0),bs.set(this,()=>{}),_r.set(this,()=>{}),_e.set(this,{}),br.set(this,!1),ws.set(this,!1),xs.set(this,!1),Ge.set(this,!1),Ss.set(this,void 0),vs.set(this,void 0),wr.set(this,void 0),Es.set(this,s=>{if(_(this,ws,!0,"f"),me(s)&&(s=new F),s instanceof F)return _(this,xs,!0,"f"),this._emit("abort",s);if(s instanceof w)return this._emit("error",s);if(s instanceof Error){let n=new w(s.message);return n.cause=s,this._emit("error",n)}return this._emit("error",new w(String(s)))}),_(this,mr,new Promise((s,n)=>{_(this,_s,s,"f"),_(this,gr,n,"f")}),"f"),_(this,yr,new Promise((s,n)=>{_(this,bs,s,"f"),_(this,_r,n,"f")}),"f"),f(this,mr,"f").catch(()=>{}),f(this,yr,"f").catch(()=>{}),_(this,Nt,e,"f"),_(this,wr,r?.logger??console,"f")}get response(){return f(this,Ss,"f")}get request_id(){return f(this,vs,"f")}async withResponse(){_(this,Ge,!0,"f");let e=await f(this,mr,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createMessage(e,r,s,{logger:n}={}){let o=new t(r,{logger:n});for(let i of r.messages)o._addMessageParam(i);return _(o,Nt,{...r,stream:!0},"f"),o._run(()=>o._createMessage(e,{...r,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},f(this,Es,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,r=!0){this.receivedMessages.push(e),r&&this._emit("message",e)}async _createMessage(e,r,s){let n=s?.signal,o;n&&(n.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),n.addEventListener("abort",o));try{f(this,se,"m",Zn).call(this);let{response:i,data:a}=await e.create({...r,stream:!0},{...s,signal:this.controller.signal}).withResponse();this._connected(i);for await(let c of a)f(this,se,"m",eo).call(this,c);if(a.controller.signal?.aborted)throw new F;f(this,se,"m",to).call(this)}finally{n&&o&&n.removeEventListener("abort",o)}}_connected(e){this.ended||(_(this,Ss,e,"f"),_(this,vs,e?.headers.get("request-id"),"f"),f(this,_s,"f").call(this,e),this._emit("connect"))}get ended(){return f(this,br,"f")}get errored(){return f(this,ws,"f")}get aborted(){return f(this,xs,"f")}abort(){this.controller.abort()}on(e,r){return(f(this,_e,"f")[e]||(f(this,_e,"f")[e]=[])).push({listener:r}),this}off(e,r){let s=f(this,_e,"f")[e];if(!s)return this;let n=s.findIndex(o=>o.listener===r);return n>=0&&s.splice(n,1),this}once(e,r){return(f(this,_e,"f")[e]||(f(this,_e,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,s)=>{_(this,Ge,!0,"f"),e!=="error"&&this.once("error",s),this.once(e,r)})}async done(){_(this,Ge,!0,"f"),await f(this,yr,"f")}get currentMessage(){return f(this,Ae,"f")}async finalMessage(){return await this.done(),f(this,se,"m",Qn).call(this)}async finalText(){return await this.done(),f(this,se,"m",Ga).call(this)}_emit(e,...r){if(f(this,br,"f"))return;e==="end"&&(_(this,br,!0,"f"),f(this,bs,"f").call(this));let s=f(this,_e,"f")[e];if(s&&(f(this,_e,"f")[e]=s.filter(n=>!n.once),s.forEach(({listener:n})=>n(...r))),e==="abort"){let n=r[0];!f(this,Ge,"f")&&!s?.length&&Promise.reject(n),f(this,gr,"f").call(this,n),f(this,_r,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=r[0];!f(this,Ge,"f")&&!s?.length&&Promise.reject(n),f(this,gr,"f").call(this,n),f(this,_r,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",f(this,se,"m",Qn).call(this))}async _fromReadableStream(e,r){let s=r?.signal,n;s&&(s.aborted&&this.controller.abort(),n=this.controller.abort.bind(this.controller),s.addEventListener("abort",n));try{f(this,se,"m",Zn).call(this),this._connected(null);let o=le.fromReadableStream(e,this.controller);for await(let i of o)f(this,se,"m",eo).call(this,i);if(o.controller.signal?.aborted)throw new F;f(this,se,"m",to).call(this)}finally{s&&n&&s.removeEventListener("abort",n)}}[(Ae=new WeakMap,Nt=new WeakMap,mr=new WeakMap,_s=new WeakMap,gr=new WeakMap,yr=new WeakMap,bs=new WeakMap,_r=new WeakMap,_e=new WeakMap,br=new WeakMap,ws=new WeakMap,xs=new WeakMap,Ge=new WeakMap,Ss=new WeakMap,vs=new WeakMap,wr=new WeakMap,Es=new WeakMap,se=new WeakSet,Qn=function(){if(this.receivedMessages.length===0)throw new w("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Ga=function(){if(this.receivedMessages.length===0)throw new w("stream ended without producing a Message with role=assistant");let r=this.receivedMessages.at(-1).content.filter(s=>s.type==="text").map(s=>s.text);if(r.length===0)throw new w("stream ended without producing a content block with type=text");return r.join(" ")},Zn=function(){this.ended||_(this,Ae,void 0,"f")},eo=function(r){if(this.ended)return;let s=f(this,se,"m",Ka).call(this,r);switch(this._emit("streamEvent",r,s),r.type){case"content_block_delta":{let n=s.content.at(-1);switch(r.delta.type){case"text_delta":{n.type==="text"&&this._emit("text",r.delta.text,n.text||"");break}case"citations_delta":{n.type==="text"&&this._emit("citation",r.delta.citation,n.citations??[]);break}case"input_json_delta":{Ja(n)&&n.input&&this._emit("inputJson",r.delta.partial_json,n.input);break}case"thinking_delta":{n.type==="thinking"&&this._emit("thinking",r.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:r.delta}break}case"message_stop":{this._addMessageParam(s),this._addMessage(Yn(s,f(this,Nt,"f"),{logger:f(this,wr,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",s.content.at(-1));break}case"message_start":{_(this,Ae,s,"f");break}case"content_block_start":case"message_delta":break}},to=function(){if(this.ended)throw new w("stream has ended, this shouldn't happen");let r=f(this,Ae,"f");if(!r)throw new w("request ended without sending any chunks");return _(this,Ae,void 0,"f"),Yn(r,f(this,Nt,"f"),{logger:f(this,wr,"f")})},Ka=function(r){let s=f(this,Ae,"f");if(r.type==="message_start"){if(s)throw new w(`Unexpected event order, got ${r.type} before receiving "message_stop"`);return r.message}if(!s)throw new w(`Unexpected event order, got ${r.type} before "message_start"`);switch(r.type){case"message_stop":return s;case"message_delta":return s.container=r.delta.container,s.stop_reason=r.delta.stop_reason,s.stop_sequence=r.delta.stop_sequence,s.usage.output_tokens=r.usage.output_tokens,s.context_management=r.context_management,r.usage.input_tokens!=null&&(s.usage.input_tokens=r.usage.input_tokens),r.usage.cache_creation_input_tokens!=null&&(s.usage.cache_creation_input_tokens=r.usage.cache_creation_input_tokens),r.usage.cache_read_input_tokens!=null&&(s.usage.cache_read_input_tokens=r.usage.cache_read_input_tokens),r.usage.server_tool_use!=null&&(s.usage.server_tool_use=r.usage.server_tool_use),r.usage.iterations!=null&&(s.usage.iterations=r.usage.iterations),s;case"content_block_start":return s.content.push(r.content_block),s;case"content_block_delta":{let n=s.content.at(r.index);switch(r.delta.type){case"text_delta":{n?.type==="text"&&(s.content[r.index]={...n,text:(n.text||"")+r.delta.text});break}case"citations_delta":{n?.type==="text"&&(s.content[r.index]={...n,citations:[...n.citations??[],r.delta.citation]});break}case"input_json_delta":{if(n&&Ja(n)){let o=n[za]||"";o+=r.delta.partial_json;let i={...n};if(Object.defineProperty(i,za,{value:o,enumerable:!1,writable:!0}),o)try{i.input=ys(o)}catch(a){let c=new w(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${a}. JSON: ${o}`);f(this,Es,"f").call(this,c)}s.content[r.index]=i}break}case"thinking_delta":{n?.type==="thinking"&&(s.content[r.index]={...n,thinking:n.thinking+r.delta.thinking});break}case"signature_delta":{n?.type==="thinking"&&(s.content[r.index]={...n,signature:r.delta.signature});break}case"compaction_delta":{n?.type==="compaction"&&(s.content[r.index]={...n,content:(n.content||"")+r.delta.content});break}default:r.delta}return s}case"content_block_stop":return s}},Symbol.asyncIterator)](){let e=[],r=[],s=!1;return this.on("streamEvent",n=>{let o=r.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(let n of r)n.resolve(void 0);r.length=0}),this.on("abort",n=>{s=!0;for(let o of r)o.reject(n);r.length=0}),this.on("error",n=>{s=!0;for(let o of r)o.reject(n);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Ke=class extends Error{constructor(e){let r=typeof e=="string"?e:e.map(s=>s.type==="text"?s.text:`[${s.type}]`).join(" ");super(r),this.name="ToolError",this.content=e}};var Ya=`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:
|
|
44
44
|
1. Task Overview
|
|
45
45
|
The user's core request and success criteria
|
|
46
46
|
Any clarifications or constraints they specified
|
|
@@ -62,25 +62,25 @@ User preferences or style requirements
|
|
|
62
62
|
Domain-specific details that aren't obvious
|
|
63
63
|
Any promises made to the user
|
|
64
64
|
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.
|
|
65
|
-
Wrap your summary in <summary></summary> tags.`;var xr,Lt,ze,L,z,Z,be,Oe,Sr,Xa,
|
|
66
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),bf.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 i=this._client._options.timeout;if(!o.stream&&i==null){let c=gs[o.model]??void 0;i=this._client.calculateNonstreamingTimeout(o.max_tokens,c)}let a=ms(o.tools,o.messages);return this._client.post("/v1/messages?beta=true",{body:o,timeout:i??6e5,...r,headers:m([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},a,r?.headers]),stream:s.stream??!1})}parse(e,r){return r={...r,headers:m([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},r?.headers])},this.create(e,r).then(s=>Qn(s,e,{logger:this._client.logger??console}))}stream(e,r){return ks.createMessage(this,e,r)}countTokens(e,r){let s=ec(e),{betas:n,...o}=s;return this._client.post("/v1/messages/count_tokens?beta=true",{body:o,...r,headers:m([{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString()},r?.headers])})}toolRunner(e,r){return new $t(this._client,e,r)}};function ec(t){if(!t.output_format)return t;if(t.output_config?.format)throw new w("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:e,...r}=t;return{...r,output_config:{...t.output_config,format:e}}}we.Batches=Mt;we.BetaToolRunner=$t;we.ToolError=Ke;var jt=class extends E{list(e,r={},s){let{betas:n,...o}=r??{};return this._client.getAPIList(y`/v1/sessions/${e}/events?beta=true`,P,{query:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}send(e,r,s){let{betas:n,...o}=r;return this._client.post(y`/v1/sessions/${e}/events?beta=true`,{body:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}stream(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/sessions/${e}/events/stream?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers]),stream:!0})}};var Bt=class extends E{retrieve(e,r,s){let{session_id:n,betas:o}=r;return this._client.get(y`/v1/sessions/${n}/resources/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}update(e,r,s){let{session_id:n,betas:o,...i}=r;return this._client.post(y`/v1/sessions/${n}/resources/${e}?beta=true`,{body:i,...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}list(e,r={},s){let{betas:n,...o}=r??{};return this._client.getAPIList(y`/v1/sessions/${e}/resources?beta=true`,P,{query:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}delete(e,r,s){let{session_id:n,betas:o}=r;return this._client.delete(y`/v1/sessions/${n}/resources/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}add(e,r,s){let{betas:n,...o}=r;return this._client.post(y`/v1/sessions/${e}/resources?beta=true`,{body:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};var Ie=class extends E{constructor(){super(...arguments),this.events=new jt(this._client),this.resources=new Bt(this._client)}create(e,r){let{betas:s,...n}=e;return this._client.post("/v1/sessions?beta=true",{body:n,...r,headers:m([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/sessions/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}update(e,r,s){let{betas:n,...o}=r;return this._client.post(y`/v1/sessions/${e}?beta=true`,{body:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/sessions?beta=true",P,{query:n,...r,headers:m([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,r={},s){let{betas:n}=r??{};return this._client.delete(y`/v1/sessions/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}archive(e,r={},s){let{betas:n}=r??{};return this._client.post(y`/v1/sessions/${e}/archive?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};Ie.Events=jt;Ie.Resources=Bt;var Dt=class extends E{create(e,r={},s){let{betas:n,...o}=r??{};return this._client.post(y`/v1/skills/${e}/versions?beta=true`,vt({body:o,...s,headers:m([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},s?.headers])},this._client))}retrieve(e,r,s){let{skill_id:n,betas:o}=r;return this._client.get(y`/v1/skills/${n}/versions/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},s?.headers])})}list(e,r={},s){let{betas:n,...o}=r??{};return this._client.getAPIList(y`/v1/skills/${e}/versions?beta=true`,P,{query:o,...s,headers:m([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},s?.headers])})}delete(e,r,s){let{skill_id:n,betas:o}=r;return this._client.delete(y`/v1/skills/${n}/versions/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},s?.headers])})}};var Je=class extends E{constructor(){super(...arguments),this.versions=new Dt(this._client)}create(e={},r){let{betas:s,...n}=e??{};return this._client.post("/v1/skills?beta=true",vt({body:n,...r,headers:m([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])},this._client,!1))}retrieve(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/skills/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},s?.headers])})}list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/skills?beta=true",P,{query:n,...r,headers:m([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])})}delete(e,r={},s){let{betas:n}=r??{};return this._client.delete(y`/v1/skills/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},s?.headers])})}};Je.Versions=Dt;var Ut=class extends E{create(e,r,s){let{betas:n,...o}=r;return this._client.post(y`/v1/vaults/${e}/credentials?beta=true`,{body:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}retrieve(e,r,s){let{vault_id:n,betas:o}=r;return this._client.get(y`/v1/vaults/${n}/credentials/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}update(e,r,s){let{vault_id:n,betas:o,...i}=r;return this._client.post(y`/v1/vaults/${n}/credentials/${e}?beta=true`,{body:i,...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}list(e,r={},s){let{betas:n,...o}=r??{};return this._client.getAPIList(y`/v1/vaults/${e}/credentials?beta=true`,P,{query:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}delete(e,r,s){let{vault_id:n,betas:o}=r;return this._client.delete(y`/v1/vaults/${n}/credentials/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}archive(e,r,s){let{vault_id:n,betas:o}=r;return this._client.post(y`/v1/vaults/${n}/credentials/${e}/archive?beta=true`,{...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};var Ye=class extends E{constructor(){super(...arguments),this.credentials=new Ut(this._client)}create(e,r){let{betas:s,...n}=e;return this._client.post("/v1/vaults?beta=true",{body:n,...r,headers:m([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/vaults/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}update(e,r,s){let{betas:n,...o}=r;return this._client.post(y`/v1/vaults/${e}?beta=true`,{body:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/vaults?beta=true",P,{query:n,...r,headers:m([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,r={},s){let{betas:n}=r??{};return this._client.delete(y`/v1/vaults/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}archive(e,r={},s){let{betas:n}=r??{};return this._client.post(y`/v1/vaults/${e}/archive?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};Ye.Credentials=Ut;var H=class extends E{constructor(){super(...arguments),this.models=new Rt(this._client),this.messages=new we(this._client),this.agents=new Ve(this._client),this.environments=new Et(this._client),this.sessions=new Ie(this._client),this.vaults=new Ye(this._client),this.memoryStores=new Te(this._client),this.files=new kt(this._client),this.skills=new Je(this._client),this.userProfiles=new Pt(this._client)}};H.Models=Rt;H.Messages=we;H.Agents=Ve;H.Environments=Et;H.Sessions=Ie;H.Vaults=Ye;H.MemoryStores=Te;H.Files=kt;H.Skills=Je;H.UserProfiles=Pt;var Xe=class extends E{create(e,r){let{betas:s,...n}=e;return this._client.post("/v1/complete",{body:n,timeout:this._client._options.timeout??6e5,...r,headers:m([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},r?.headers]),stream:e.stream??!1})}};function tc(t){return t?.output_config?.format}function no(t,e,r){let s=tc(e);return!e||!("parse"in(s??{}))?{...t,content:t.content.map(n=>n.type==="text"?Object.defineProperty({...n},"parsed_output",{value:null,enumerable:!1}):n),parsed_output:null}:oo(t,e,r)}function oo(t,e,r){let s=null,n=t.content.map(o=>{if(o.type==="text"){let i=Tf(e,o.text);return s===null&&(s=i),Object.defineProperty({...o},"parsed_output",{value:i,enumerable:!1})}return o});return{...t,content:n,parsed_output:s}}function Tf(t,e){let r=tc(t);if(r?.type!=="json_schema")return null;try{return"parse"in r?r.parse(e):JSON.parse(e)}catch(s){throw new w(`Failed to parse structured output: ${s}`)}}var oe,Me,qt,vr,Rs,Er,kr,Ps,Rr,xe,Pr,Ts,As,Qe,Os,Is,Tr,io,rc,ao,co,lo,uo,sc,nc="__json_buf";function oc(t){return t.type==="tool_use"||t.type==="server_tool_use"}var Ms=class t{constructor(e,r){oe.add(this),this.messages=[],this.receivedMessages=[],Me.set(this,void 0),qt.set(this,null),this.controller=new AbortController,vr.set(this,void 0),Rs.set(this,()=>{}),Er.set(this,()=>{}),kr.set(this,void 0),Ps.set(this,()=>{}),Rr.set(this,()=>{}),xe.set(this,{}),Pr.set(this,!1),Ts.set(this,!1),As.set(this,!1),Qe.set(this,!1),Os.set(this,void 0),Is.set(this,void 0),Tr.set(this,void 0),ao.set(this,s=>{if(_(this,Ts,!0,"f"),me(s)&&(s=new F),s instanceof F)return _(this,As,!0,"f"),this._emit("abort",s);if(s instanceof w)return this._emit("error",s);if(s instanceof Error){let n=new w(s.message);return n.cause=s,this._emit("error",n)}return this._emit("error",new w(String(s)))}),_(this,vr,new Promise((s,n)=>{_(this,Rs,s,"f"),_(this,Er,n,"f")}),"f"),_(this,kr,new Promise((s,n)=>{_(this,Ps,s,"f"),_(this,Rr,n,"f")}),"f"),f(this,vr,"f").catch(()=>{}),f(this,kr,"f").catch(()=>{}),_(this,qt,e,"f"),_(this,Tr,r?.logger??console,"f")}get response(){return f(this,Os,"f")}get request_id(){return f(this,Is,"f")}async withResponse(){_(this,Qe,!0,"f");let e=await f(this,vr,"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 r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createMessage(e,r,s,{logger:n}={}){let o=new t(r,{logger:n});for(let i of r.messages)o._addMessageParam(i);return _(o,qt,{...r,stream:!0},"f"),o._run(()=>o._createMessage(e,{...r,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},f(this,ao,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,r=!0){this.receivedMessages.push(e),r&&this._emit("message",e)}async _createMessage(e,r,s){let n=s?.signal,o;n&&(n.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),n.addEventListener("abort",o));try{f(this,oe,"m",co).call(this);let{response:i,data:a}=await e.create({...r,stream:!0},{...s,signal:this.controller.signal}).withResponse();this._connected(i);for await(let c of a)f(this,oe,"m",lo).call(this,c);if(a.controller.signal?.aborted)throw new F;f(this,oe,"m",uo).call(this)}finally{n&&o&&n.removeEventListener("abort",o)}}_connected(e){this.ended||(_(this,Os,e,"f"),_(this,Is,e?.headers.get("request-id"),"f"),f(this,Rs,"f").call(this,e),this._emit("connect"))}get ended(){return f(this,Pr,"f")}get errored(){return f(this,Ts,"f")}get aborted(){return f(this,As,"f")}abort(){this.controller.abort()}on(e,r){return(f(this,xe,"f")[e]||(f(this,xe,"f")[e]=[])).push({listener:r}),this}off(e,r){let s=f(this,xe,"f")[e];if(!s)return this;let n=s.findIndex(o=>o.listener===r);return n>=0&&s.splice(n,1),this}once(e,r){return(f(this,xe,"f")[e]||(f(this,xe,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,s)=>{_(this,Qe,!0,"f"),e!=="error"&&this.once("error",s),this.once(e,r)})}async done(){_(this,Qe,!0,"f"),await f(this,kr,"f")}get currentMessage(){return f(this,Me,"f")}async finalMessage(){return await this.done(),f(this,oe,"m",io).call(this)}async finalText(){return await this.done(),f(this,oe,"m",rc).call(this)}_emit(e,...r){if(f(this,Pr,"f"))return;e==="end"&&(_(this,Pr,!0,"f"),f(this,Ps,"f").call(this));let s=f(this,xe,"f")[e];if(s&&(f(this,xe,"f")[e]=s.filter(n=>!n.once),s.forEach(({listener:n})=>n(...r))),e==="abort"){let n=r[0];!f(this,Qe,"f")&&!s?.length&&Promise.reject(n),f(this,Er,"f").call(this,n),f(this,Rr,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=r[0];!f(this,Qe,"f")&&!s?.length&&Promise.reject(n),f(this,Er,"f").call(this,n),f(this,Rr,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",f(this,oe,"m",io).call(this))}async _fromReadableStream(e,r){let s=r?.signal,n;s&&(s.aborted&&this.controller.abort(),n=this.controller.abort.bind(this.controller),s.addEventListener("abort",n));try{f(this,oe,"m",co).call(this),this._connected(null);let o=le.fromReadableStream(e,this.controller);for await(let i of o)f(this,oe,"m",lo).call(this,i);if(o.controller.signal?.aborted)throw new F;f(this,oe,"m",uo).call(this)}finally{s&&n&&s.removeEventListener("abort",n)}}[(Me=new WeakMap,qt=new WeakMap,vr=new WeakMap,Rs=new WeakMap,Er=new WeakMap,kr=new WeakMap,Ps=new WeakMap,Rr=new WeakMap,xe=new WeakMap,Pr=new WeakMap,Ts=new WeakMap,As=new WeakMap,Qe=new WeakMap,Os=new WeakMap,Is=new WeakMap,Tr=new WeakMap,ao=new WeakMap,oe=new WeakSet,io=function(){if(this.receivedMessages.length===0)throw new w("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},rc=function(){if(this.receivedMessages.length===0)throw new w("stream ended without producing a Message with role=assistant");let r=this.receivedMessages.at(-1).content.filter(s=>s.type==="text").map(s=>s.text);if(r.length===0)throw new w("stream ended without producing a content block with type=text");return r.join(" ")},co=function(){this.ended||_(this,Me,void 0,"f")},lo=function(r){if(this.ended)return;let s=f(this,oe,"m",sc).call(this,r);switch(this._emit("streamEvent",r,s),r.type){case"content_block_delta":{let n=s.content.at(-1);switch(r.delta.type){case"text_delta":{n.type==="text"&&this._emit("text",r.delta.text,n.text||"");break}case"citations_delta":{n.type==="text"&&this._emit("citation",r.delta.citation,n.citations??[]);break}case"input_json_delta":{oc(n)&&n.input&&this._emit("inputJson",r.delta.partial_json,n.input);break}case"thinking_delta":{n.type==="thinking"&&this._emit("thinking",r.delta.thinking,n.thinking);break}case"signature_delta":{n.type==="thinking"&&this._emit("signature",n.signature);break}default:r.delta}break}case"message_stop":{this._addMessageParam(s),this._addMessage(no(s,f(this,qt,"f"),{logger:f(this,Tr,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",s.content.at(-1));break}case"message_start":{_(this,Me,s,"f");break}case"content_block_start":case"message_delta":break}},uo=function(){if(this.ended)throw new w("stream has ended, this shouldn't happen");let r=f(this,Me,"f");if(!r)throw new w("request ended without sending any chunks");return _(this,Me,void 0,"f"),no(r,f(this,qt,"f"),{logger:f(this,Tr,"f")})},sc=function(r){let s=f(this,Me,"f");if(r.type==="message_start"){if(s)throw new w(`Unexpected event order, got ${r.type} before receiving "message_stop"`);return r.message}if(!s)throw new w(`Unexpected event order, got ${r.type} before "message_start"`);switch(r.type){case"message_stop":return s;case"message_delta":return s.stop_reason=r.delta.stop_reason,s.stop_sequence=r.delta.stop_sequence,s.usage.output_tokens=r.usage.output_tokens,r.usage.input_tokens!=null&&(s.usage.input_tokens=r.usage.input_tokens),r.usage.cache_creation_input_tokens!=null&&(s.usage.cache_creation_input_tokens=r.usage.cache_creation_input_tokens),r.usage.cache_read_input_tokens!=null&&(s.usage.cache_read_input_tokens=r.usage.cache_read_input_tokens),r.usage.server_tool_use!=null&&(s.usage.server_tool_use=r.usage.server_tool_use),s;case"content_block_start":return s.content.push({...r.content_block}),s;case"content_block_delta":{let n=s.content.at(r.index);switch(r.delta.type){case"text_delta":{n?.type==="text"&&(s.content[r.index]={...n,text:(n.text||"")+r.delta.text});break}case"citations_delta":{n?.type==="text"&&(s.content[r.index]={...n,citations:[...n.citations??[],r.delta.citation]});break}case"input_json_delta":{if(n&&oc(n)){let o=n[nc]||"";o+=r.delta.partial_json;let i={...n};Object.defineProperty(i,nc,{value:o,enumerable:!1,writable:!0}),o&&(i.input=ys(o)),s.content[r.index]=i}break}case"thinking_delta":{n?.type==="thinking"&&(s.content[r.index]={...n,thinking:n.thinking+r.delta.thinking});break}case"signature_delta":{n?.type==="thinking"&&(s.content[r.index]={...n,signature:r.delta.signature});break}default:r.delta}return s}case"content_block_stop":return s}},Symbol.asyncIterator)](){let e=[],r=[],s=!1;return this.on("streamEvent",n=>{let o=r.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(let n of r)n.resolve(void 0);r.length=0}),this.on("abort",n=>{s=!0;for(let o of r)o.reject(n);r.length=0}),this.on("error",n=>{s=!0;for(let o of r)o.reject(n);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Ft=class extends E{create(e,r){return this._client.post("/v1/messages/batches",{body:e,...r})}retrieve(e,r){return this._client.get(y`/v1/messages/batches/${e}`,r)}list(e={},r){return this._client.getAPIList("/v1/messages/batches",se,{query:e,...r})}delete(e,r){return this._client.delete(y`/v1/messages/batches/${e}`,r)}cancel(e,r){return this._client.post(y`/v1/messages/batches/${e}/cancel`,r)}async results(e,r){let s=await this.retrieve(e);if(!s.results_url)throw new w(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);return this._client.get(s.results_url,{...r,headers:m([{Accept:"application/binary"},r?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((n,o)=>It.fromResponse(o.response,o.controller))}};var Ce=class extends E{constructor(){super(...arguments),this.batches=new Ft(this._client)}create(e,r){e.model in ic&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${ic[e.model]}
|
|
67
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),Of.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 s=this._client._options.timeout;if(!e.stream&&s==null){let o=gs[e.model]??void 0;s=this._client.calculateNonstreamingTimeout(e.max_tokens,o)}let n=ms(e.tools,e.messages);return this._client.post("/v1/messages",{body:e,timeout:s??6e5,...r,headers:m([n,r?.headers]),stream:e.stream??!1})}parse(e,r){return this.create(e,r).then(s=>
|
|
65
|
+
Wrap your summary in <summary></summary> tags.`;var xr,Lt,ze,L,z,Z,be,Oe,Sr,Xa,ro;function Qa(){let t,e;return{promise:new Promise((s,n)=>{t=s,e=n}),resolve:t,reject:e}}var $t=class{constructor(e,r,s){xr.add(this),this.client=e,Lt.set(this,!1),ze.set(this,!1),L.set(this,void 0),z.set(this,void 0),Z.set(this,void 0),be.set(this,void 0),Oe.set(this,void 0),Sr.set(this,0),_(this,L,{params:{...r,messages:structuredClone(r.messages)}},"f");let o=["BetaToolRunner",...Jn(r.tools,r.messages)].join(", ");_(this,z,{...s,headers:m([{"x-stainless-helper":o},s?.headers])},"f"),_(this,Oe,Qa(),"f"),r.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*[(Lt=new WeakMap,ze=new WeakMap,L=new WeakMap,z=new WeakMap,Z=new WeakMap,be=new WeakMap,Oe=new WeakMap,Sr=new WeakMap,xr=new WeakSet,Xa=async function(){let r=f(this,L,"f").params.compactionControl;if(!r||!r.enabled)return!1;let s=0;if(f(this,Z,"f")!==void 0)try{let l=await f(this,Z,"f");s=l.usage.input_tokens+(l.usage.cache_creation_input_tokens??0)+(l.usage.cache_read_input_tokens??0)+l.usage.output_tokens}catch{return!1}let n=r.contextTokenThreshold??1e5;if(s<n)return!1;let o=r.model??f(this,L,"f").params.model,i=r.summaryPrompt??Ya,a=f(this,L,"f").params.messages;if(a[a.length-1].role==="assistant"){let l=a[a.length-1];if(Array.isArray(l.content)){let u=l.content.filter(d=>d.type!=="tool_use");u.length===0?a.pop():l.content=u}}let c=await this.client.beta.messages.create({model:o,messages:[...a,{role:"user",content:[{type:"text",text:i}]}],max_tokens:f(this,L,"f").params.max_tokens},{signal:f(this,z,"f").signal,headers:m([f(this,z,"f").headers,{"x-stainless-helper":"compaction"}])});if(c.content[0]?.type!=="text")throw new w("Expected text response for compaction");return f(this,L,"f").params.messages=[{role:"user",content:c.content}],!0},Symbol.asyncIterator)](){var e;if(f(this,Lt,"f"))throw new w("Cannot iterate over a consumed stream");_(this,Lt,!0,"f"),_(this,ze,!0,"f"),_(this,be,void 0,"f");try{for(;;){let r;try{if(f(this,L,"f").params.max_iterations&&f(this,Sr,"f")>=f(this,L,"f").params.max_iterations)break;_(this,ze,!1,"f"),_(this,be,void 0,"f"),_(this,Sr,(e=f(this,Sr,"f"),e++,e),"f"),_(this,Z,void 0,"f");let{max_iterations:s,compactionControl:n,...o}=f(this,L,"f").params;if(o.stream?(r=this.client.beta.messages.stream({...o},f(this,z,"f")),_(this,Z,r.finalMessage(),"f"),f(this,Z,"f").catch(()=>{}),yield r):(_(this,Z,this.client.beta.messages.create({...o,stream:!1},f(this,z,"f")),"f"),yield f(this,Z,"f")),!await f(this,xr,"m",Xa).call(this)){if(!f(this,ze,"f")){let{role:c,content:l}=await f(this,Z,"f");f(this,L,"f").params.messages.push({role:c,content:l})}let a=await f(this,xr,"m",ro).call(this,f(this,L,"f").params.messages.at(-1));if(a)f(this,L,"f").params.messages.push(a);else if(!f(this,ze,"f"))break}}finally{r&&r.abort()}}if(!f(this,Z,"f"))throw new w("ToolRunner concluded without a message from the server");f(this,Oe,"f").resolve(await f(this,Z,"f"))}catch(r){throw _(this,Lt,!1,"f"),f(this,Oe,"f").promise.catch(()=>{}),f(this,Oe,"f").reject(r),_(this,Oe,Qa(),"f"),r}}setMessagesParams(e){typeof e=="function"?f(this,L,"f").params=e(f(this,L,"f").params):f(this,L,"f").params=e,_(this,ze,!0,"f"),_(this,be,void 0,"f")}setRequestOptions(e){typeof e=="function"?_(this,z,e(f(this,z,"f")),"f"):_(this,z,{...f(this,z,"f"),...e},"f")}async generateToolResponse(e=f(this,z,"f").signal){let r=await f(this,Z,"f")??this.params.messages.at(-1);return r?f(this,xr,"m",ro).call(this,r,e):null}done(){return f(this,Oe,"f").promise}async runUntilDone(){if(!f(this,Lt,"f"))for await(let e of this);return this.done()}get params(){return f(this,L,"f").params}pushMessages(...e){this.setMessagesParams(r=>({...r,messages:[...r.messages,...e]}))}then(e,r){return this.runUntilDone().then(e,r)}};ro=async function(e,r=f(this,z,"f").signal){return f(this,be,"f")!==void 0?f(this,be,"f"):(_(this,be,_f(f(this,L,"f").params,e,{...f(this,z,"f"),signal:r}),"f"),f(this,be,"f"))};async function _f(t,e=t.messages.at(-1),r){if(!e||e.role!=="assistant"||!e.content||typeof e.content=="string")return null;let s=e.content.filter(o=>o.type==="tool_use");return s.length===0?null:{role:"user",content:await Promise.all(s.map(async o=>{let i=t.tools.find(a=>("name"in a?a.name:a.mcp_server_name)===o.name);if(!i||!("run"in i))return{type:"tool_result",tool_use_id:o.id,content:`Error: Tool '${o.name}' not found`,is_error:!0};try{let a=o.input;"parse"in i&&i.parse&&(a=i.parse(a));let c=await i.run(a,{toolUseBlock:o,signal:r?.signal});return{type:"tool_result",tool_use_id:o.id,content:c}}catch(a){return{type:"tool_result",tool_use_id:o.id,content:a instanceof Ke?a.content:`Error: ${a instanceof Error?a.message:String(a)}`,is_error:!0}}}))}}var Za={"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"},bf=["claude-mythos-preview","claude-opus-4-6"],we=class extends E{constructor(){super(...arguments),this.batches=new Mt(this._client)}create(e,r){let s=ec(e),{betas:n,...o}=s;o.model in Za&&console.warn(`The model '${o.model}' is deprecated and will reach end-of-life on ${Za[o.model]}
|
|
66
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),bf.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 i=this._client._options.timeout;if(!o.stream&&i==null){let c=gs[o.model]??void 0;i=this._client.calculateNonstreamingTimeout(o.max_tokens,c)}let a=ms(o.tools,o.messages);return this._client.post("/v1/messages?beta=true",{body:o,timeout:i??6e5,...r,headers:m([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},a,r?.headers]),stream:s.stream??!1})}parse(e,r){return r={...r,headers:m([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},r?.headers])},this.create(e,r).then(s=>Xn(s,e,{logger:this._client.logger??console}))}stream(e,r){return ks.createMessage(this,e,r)}countTokens(e,r){let s=ec(e),{betas:n,...o}=s;return this._client.post("/v1/messages/count_tokens?beta=true",{body:o,...r,headers:m([{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString()},r?.headers])})}toolRunner(e,r){return new $t(this._client,e,r)}};function ec(t){if(!t.output_format)return t;if(t.output_config?.format)throw new w("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:e,...r}=t;return{...r,output_config:{...t.output_config,format:e}}}we.Batches=Mt;we.BetaToolRunner=$t;we.ToolError=Ke;var jt=class extends E{list(e,r={},s){let{betas:n,...o}=r??{};return this._client.getAPIList(y`/v1/sessions/${e}/events?beta=true`,P,{query:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}send(e,r,s){let{betas:n,...o}=r;return this._client.post(y`/v1/sessions/${e}/events?beta=true`,{body:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}stream(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/sessions/${e}/events/stream?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers]),stream:!0})}};var Bt=class extends E{retrieve(e,r,s){let{session_id:n,betas:o}=r;return this._client.get(y`/v1/sessions/${n}/resources/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}update(e,r,s){let{session_id:n,betas:o,...i}=r;return this._client.post(y`/v1/sessions/${n}/resources/${e}?beta=true`,{body:i,...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}list(e,r={},s){let{betas:n,...o}=r??{};return this._client.getAPIList(y`/v1/sessions/${e}/resources?beta=true`,P,{query:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}delete(e,r,s){let{session_id:n,betas:o}=r;return this._client.delete(y`/v1/sessions/${n}/resources/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}add(e,r,s){let{betas:n,...o}=r;return this._client.post(y`/v1/sessions/${e}/resources?beta=true`,{body:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};var Ie=class extends E{constructor(){super(...arguments),this.events=new jt(this._client),this.resources=new Bt(this._client)}create(e,r){let{betas:s,...n}=e;return this._client.post("/v1/sessions?beta=true",{body:n,...r,headers:m([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/sessions/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}update(e,r,s){let{betas:n,...o}=r;return this._client.post(y`/v1/sessions/${e}?beta=true`,{body:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/sessions?beta=true",P,{query:n,...r,headers:m([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,r={},s){let{betas:n}=r??{};return this._client.delete(y`/v1/sessions/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}archive(e,r={},s){let{betas:n}=r??{};return this._client.post(y`/v1/sessions/${e}/archive?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};Ie.Events=jt;Ie.Resources=Bt;var Dt=class extends E{create(e,r={},s){let{betas:n,...o}=r??{};return this._client.post(y`/v1/skills/${e}/versions?beta=true`,vt({body:o,...s,headers:m([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},s?.headers])},this._client))}retrieve(e,r,s){let{skill_id:n,betas:o}=r;return this._client.get(y`/v1/skills/${n}/versions/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},s?.headers])})}list(e,r={},s){let{betas:n,...o}=r??{};return this._client.getAPIList(y`/v1/skills/${e}/versions?beta=true`,P,{query:o,...s,headers:m([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},s?.headers])})}delete(e,r,s){let{skill_id:n,betas:o}=r;return this._client.delete(y`/v1/skills/${n}/versions/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},s?.headers])})}};var Je=class extends E{constructor(){super(...arguments),this.versions=new Dt(this._client)}create(e={},r){let{betas:s,...n}=e??{};return this._client.post("/v1/skills?beta=true",vt({body:n,...r,headers:m([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])},this._client,!1))}retrieve(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/skills/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},s?.headers])})}list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/skills?beta=true",P,{query:n,...r,headers:m([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])})}delete(e,r={},s){let{betas:n}=r??{};return this._client.delete(y`/v1/skills/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},s?.headers])})}};Je.Versions=Dt;var Ut=class extends E{create(e,r,s){let{betas:n,...o}=r;return this._client.post(y`/v1/vaults/${e}/credentials?beta=true`,{body:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}retrieve(e,r,s){let{vault_id:n,betas:o}=r;return this._client.get(y`/v1/vaults/${n}/credentials/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}update(e,r,s){let{vault_id:n,betas:o,...i}=r;return this._client.post(y`/v1/vaults/${n}/credentials/${e}?beta=true`,{body:i,...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}list(e,r={},s){let{betas:n,...o}=r??{};return this._client.getAPIList(y`/v1/vaults/${e}/credentials?beta=true`,P,{query:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}delete(e,r,s){let{vault_id:n,betas:o}=r;return this._client.delete(y`/v1/vaults/${n}/credentials/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}archive(e,r,s){let{vault_id:n,betas:o}=r;return this._client.post(y`/v1/vaults/${n}/credentials/${e}/archive?beta=true`,{...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};var Ye=class extends E{constructor(){super(...arguments),this.credentials=new Ut(this._client)}create(e,r){let{betas:s,...n}=e;return this._client.post("/v1/vaults?beta=true",{body:n,...r,headers:m([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/vaults/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}update(e,r,s){let{betas:n,...o}=r;return this._client.post(y`/v1/vaults/${e}?beta=true`,{body:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/vaults?beta=true",P,{query:n,...r,headers:m([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,r={},s){let{betas:n}=r??{};return this._client.delete(y`/v1/vaults/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}archive(e,r={},s){let{betas:n}=r??{};return this._client.post(y`/v1/vaults/${e}/archive?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};Ye.Credentials=Ut;var H=class extends E{constructor(){super(...arguments),this.models=new Rt(this._client),this.messages=new we(this._client),this.agents=new Ve(this._client),this.environments=new Et(this._client),this.sessions=new Ie(this._client),this.vaults=new Ye(this._client),this.memoryStores=new Te(this._client),this.files=new kt(this._client),this.skills=new Je(this._client),this.userProfiles=new Pt(this._client)}};H.Models=Rt;H.Messages=we;H.Agents=Ve;H.Environments=Et;H.Sessions=Ie;H.Vaults=Ye;H.MemoryStores=Te;H.Files=kt;H.Skills=Je;H.UserProfiles=Pt;var Xe=class extends E{create(e,r){let{betas:s,...n}=e;return this._client.post("/v1/complete",{body:n,timeout:this._client._options.timeout??6e5,...r,headers:m([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},r?.headers]),stream:e.stream??!1})}};function tc(t){return t?.output_config?.format}function so(t,e,r){let s=tc(e);return!e||!("parse"in(s??{}))?{...t,content:t.content.map(n=>n.type==="text"?Object.defineProperty({...n},"parsed_output",{value:null,enumerable:!1}):n),parsed_output:null}:no(t,e,r)}function no(t,e,r){let s=null,n=t.content.map(o=>{if(o.type==="text"){let i=Tf(e,o.text);return s===null&&(s=i),Object.defineProperty({...o},"parsed_output",{value:i,enumerable:!1})}return o});return{...t,content:n,parsed_output:s}}function Tf(t,e){let r=tc(t);if(r?.type!=="json_schema")return null;try{return"parse"in r?r.parse(e):JSON.parse(e)}catch(s){throw new w(`Failed to parse structured output: ${s}`)}}var ne,Me,qt,vr,Rs,Er,kr,Ps,Rr,xe,Pr,Ts,As,Qe,Os,Is,Tr,oo,rc,io,ao,co,lo,sc,nc="__json_buf";function oc(t){return t.type==="tool_use"||t.type==="server_tool_use"}var Ms=class t{constructor(e,r){ne.add(this),this.messages=[],this.receivedMessages=[],Me.set(this,void 0),qt.set(this,null),this.controller=new AbortController,vr.set(this,void 0),Rs.set(this,()=>{}),Er.set(this,()=>{}),kr.set(this,void 0),Ps.set(this,()=>{}),Rr.set(this,()=>{}),xe.set(this,{}),Pr.set(this,!1),Ts.set(this,!1),As.set(this,!1),Qe.set(this,!1),Os.set(this,void 0),Is.set(this,void 0),Tr.set(this,void 0),io.set(this,s=>{if(_(this,Ts,!0,"f"),me(s)&&(s=new F),s instanceof F)return _(this,As,!0,"f"),this._emit("abort",s);if(s instanceof w)return this._emit("error",s);if(s instanceof Error){let n=new w(s.message);return n.cause=s,this._emit("error",n)}return this._emit("error",new w(String(s)))}),_(this,vr,new Promise((s,n)=>{_(this,Rs,s,"f"),_(this,Er,n,"f")}),"f"),_(this,kr,new Promise((s,n)=>{_(this,Ps,s,"f"),_(this,Rr,n,"f")}),"f"),f(this,vr,"f").catch(()=>{}),f(this,kr,"f").catch(()=>{}),_(this,qt,e,"f"),_(this,Tr,r?.logger??console,"f")}get response(){return f(this,Os,"f")}get request_id(){return f(this,Is,"f")}async withResponse(){_(this,Qe,!0,"f");let e=await f(this,vr,"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 r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createMessage(e,r,s,{logger:n}={}){let o=new t(r,{logger:n});for(let i of r.messages)o._addMessageParam(i);return _(o,qt,{...r,stream:!0},"f"),o._run(()=>o._createMessage(e,{...r,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},f(this,io,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,r=!0){this.receivedMessages.push(e),r&&this._emit("message",e)}async _createMessage(e,r,s){let n=s?.signal,o;n&&(n.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),n.addEventListener("abort",o));try{f(this,ne,"m",ao).call(this);let{response:i,data:a}=await e.create({...r,stream:!0},{...s,signal:this.controller.signal}).withResponse();this._connected(i);for await(let c of a)f(this,ne,"m",co).call(this,c);if(a.controller.signal?.aborted)throw new F;f(this,ne,"m",lo).call(this)}finally{n&&o&&n.removeEventListener("abort",o)}}_connected(e){this.ended||(_(this,Os,e,"f"),_(this,Is,e?.headers.get("request-id"),"f"),f(this,Rs,"f").call(this,e),this._emit("connect"))}get ended(){return f(this,Pr,"f")}get errored(){return f(this,Ts,"f")}get aborted(){return f(this,As,"f")}abort(){this.controller.abort()}on(e,r){return(f(this,xe,"f")[e]||(f(this,xe,"f")[e]=[])).push({listener:r}),this}off(e,r){let s=f(this,xe,"f")[e];if(!s)return this;let n=s.findIndex(o=>o.listener===r);return n>=0&&s.splice(n,1),this}once(e,r){return(f(this,xe,"f")[e]||(f(this,xe,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,s)=>{_(this,Qe,!0,"f"),e!=="error"&&this.once("error",s),this.once(e,r)})}async done(){_(this,Qe,!0,"f"),await f(this,kr,"f")}get currentMessage(){return f(this,Me,"f")}async finalMessage(){return await this.done(),f(this,ne,"m",oo).call(this)}async finalText(){return await this.done(),f(this,ne,"m",rc).call(this)}_emit(e,...r){if(f(this,Pr,"f"))return;e==="end"&&(_(this,Pr,!0,"f"),f(this,Ps,"f").call(this));let s=f(this,xe,"f")[e];if(s&&(f(this,xe,"f")[e]=s.filter(n=>!n.once),s.forEach(({listener:n})=>n(...r))),e==="abort"){let n=r[0];!f(this,Qe,"f")&&!s?.length&&Promise.reject(n),f(this,Er,"f").call(this,n),f(this,Rr,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=r[0];!f(this,Qe,"f")&&!s?.length&&Promise.reject(n),f(this,Er,"f").call(this,n),f(this,Rr,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",f(this,ne,"m",oo).call(this))}async _fromReadableStream(e,r){let s=r?.signal,n;s&&(s.aborted&&this.controller.abort(),n=this.controller.abort.bind(this.controller),s.addEventListener("abort",n));try{f(this,ne,"m",ao).call(this),this._connected(null);let o=le.fromReadableStream(e,this.controller);for await(let i of o)f(this,ne,"m",co).call(this,i);if(o.controller.signal?.aborted)throw new F;f(this,ne,"m",lo).call(this)}finally{s&&n&&s.removeEventListener("abort",n)}}[(Me=new WeakMap,qt=new WeakMap,vr=new WeakMap,Rs=new WeakMap,Er=new WeakMap,kr=new WeakMap,Ps=new WeakMap,Rr=new WeakMap,xe=new WeakMap,Pr=new WeakMap,Ts=new WeakMap,As=new WeakMap,Qe=new WeakMap,Os=new WeakMap,Is=new WeakMap,Tr=new WeakMap,io=new WeakMap,ne=new WeakSet,oo=function(){if(this.receivedMessages.length===0)throw new w("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},rc=function(){if(this.receivedMessages.length===0)throw new w("stream ended without producing a Message with role=assistant");let r=this.receivedMessages.at(-1).content.filter(s=>s.type==="text").map(s=>s.text);if(r.length===0)throw new w("stream ended without producing a content block with type=text");return r.join(" ")},ao=function(){this.ended||_(this,Me,void 0,"f")},co=function(r){if(this.ended)return;let s=f(this,ne,"m",sc).call(this,r);switch(this._emit("streamEvent",r,s),r.type){case"content_block_delta":{let n=s.content.at(-1);switch(r.delta.type){case"text_delta":{n.type==="text"&&this._emit("text",r.delta.text,n.text||"");break}case"citations_delta":{n.type==="text"&&this._emit("citation",r.delta.citation,n.citations??[]);break}case"input_json_delta":{oc(n)&&n.input&&this._emit("inputJson",r.delta.partial_json,n.input);break}case"thinking_delta":{n.type==="thinking"&&this._emit("thinking",r.delta.thinking,n.thinking);break}case"signature_delta":{n.type==="thinking"&&this._emit("signature",n.signature);break}default:r.delta}break}case"message_stop":{this._addMessageParam(s),this._addMessage(so(s,f(this,qt,"f"),{logger:f(this,Tr,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",s.content.at(-1));break}case"message_start":{_(this,Me,s,"f");break}case"content_block_start":case"message_delta":break}},lo=function(){if(this.ended)throw new w("stream has ended, this shouldn't happen");let r=f(this,Me,"f");if(!r)throw new w("request ended without sending any chunks");return _(this,Me,void 0,"f"),so(r,f(this,qt,"f"),{logger:f(this,Tr,"f")})},sc=function(r){let s=f(this,Me,"f");if(r.type==="message_start"){if(s)throw new w(`Unexpected event order, got ${r.type} before receiving "message_stop"`);return r.message}if(!s)throw new w(`Unexpected event order, got ${r.type} before "message_start"`);switch(r.type){case"message_stop":return s;case"message_delta":return s.stop_reason=r.delta.stop_reason,s.stop_sequence=r.delta.stop_sequence,s.usage.output_tokens=r.usage.output_tokens,r.usage.input_tokens!=null&&(s.usage.input_tokens=r.usage.input_tokens),r.usage.cache_creation_input_tokens!=null&&(s.usage.cache_creation_input_tokens=r.usage.cache_creation_input_tokens),r.usage.cache_read_input_tokens!=null&&(s.usage.cache_read_input_tokens=r.usage.cache_read_input_tokens),r.usage.server_tool_use!=null&&(s.usage.server_tool_use=r.usage.server_tool_use),s;case"content_block_start":return s.content.push({...r.content_block}),s;case"content_block_delta":{let n=s.content.at(r.index);switch(r.delta.type){case"text_delta":{n?.type==="text"&&(s.content[r.index]={...n,text:(n.text||"")+r.delta.text});break}case"citations_delta":{n?.type==="text"&&(s.content[r.index]={...n,citations:[...n.citations??[],r.delta.citation]});break}case"input_json_delta":{if(n&&oc(n)){let o=n[nc]||"";o+=r.delta.partial_json;let i={...n};Object.defineProperty(i,nc,{value:o,enumerable:!1,writable:!0}),o&&(i.input=ys(o)),s.content[r.index]=i}break}case"thinking_delta":{n?.type==="thinking"&&(s.content[r.index]={...n,thinking:n.thinking+r.delta.thinking});break}case"signature_delta":{n?.type==="thinking"&&(s.content[r.index]={...n,signature:r.delta.signature});break}default:r.delta}return s}case"content_block_stop":return s}},Symbol.asyncIterator)](){let e=[],r=[],s=!1;return this.on("streamEvent",n=>{let o=r.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(let n of r)n.resolve(void 0);r.length=0}),this.on("abort",n=>{s=!0;for(let o of r)o.reject(n);r.length=0}),this.on("error",n=>{s=!0;for(let o of r)o.reject(n);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Ft=class extends E{create(e,r){return this._client.post("/v1/messages/batches",{body:e,...r})}retrieve(e,r){return this._client.get(y`/v1/messages/batches/${e}`,r)}list(e={},r){return this._client.getAPIList("/v1/messages/batches",re,{query:e,...r})}delete(e,r){return this._client.delete(y`/v1/messages/batches/${e}`,r)}cancel(e,r){return this._client.post(y`/v1/messages/batches/${e}/cancel`,r)}async results(e,r){let s=await this.retrieve(e);if(!s.results_url)throw new w(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);return this._client.get(s.results_url,{...r,headers:m([{Accept:"application/binary"},r?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((n,o)=>It.fromResponse(o.response,o.controller))}};var Ce=class extends E{constructor(){super(...arguments),this.batches=new Ft(this._client)}create(e,r){e.model in ic&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${ic[e.model]}
|
|
67
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),Of.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 s=this._client._options.timeout;if(!e.stream&&s==null){let o=gs[e.model]??void 0;s=this._client.calculateNonstreamingTimeout(e.max_tokens,o)}let n=ms(e.tools,e.messages);return this._client.post("/v1/messages",{body:e,timeout:s??6e5,...r,headers:m([n,r?.headers]),stream:e.stream??!1})}parse(e,r){return this.create(e,r).then(s=>no(s,e,{logger:this._client.logger??console}))}stream(e,r){return Ms.createMessage(this,e,r,{logger:this._client.logger??console})}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},ic={"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"},Of=["claude-mythos-preview","claude-opus-4-6"];Ce.Batches=Ft;var Ze=class extends E{retrieve(e,r={},s){let{betas:n}=r??{};return this._client.get(y`/v1/models/${e}`,{...s,headers:m([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/models",re,{query:n,...r,headers:m([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},r?.headers])})}};var Ht=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0};var uo,fo,Cs,ac,cc="\\n\\nHuman:",lc="\\n\\nAssistant:",M=class{constructor({baseURL:e=Ht("ANTHROPIC_BASE_URL"),apiKey:r=Ht("ANTHROPIC_API_KEY")??null,authToken:s=Ht("ANTHROPIC_AUTH_TOKEN")??null,...n}={}){uo.add(this),Cs.set(this,void 0);let o={apiKey:r,authToken:s,...n,baseURL:e||"https://api.anthropic.com"};if(!o.dangerouslyAllowBrowser&&Ta())throw new w(`It looks like you're running in a browser-like environment.
|
|
68
68
|
|
|
69
69
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
70
70
|
If you understand the risks and have appropriate mitigations in place,
|
|
71
71
|
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
72
72
|
|
|
73
73
|
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
74
|
-
`);this.baseURL=o.baseURL,this.timeout=o.timeout??
|
|
75
|
-
`)){let u=l.indexOf(":");u>=0&&(c[l.substring(0,u).trim()]=l.substring(u+1).trim())}o.defaultHeaders={...c,...o.defaultHeaders}}this._options=o,this.apiKey=typeof r=="string"?r:null,this.authToken=s}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){if(!(e.get("x-api-key")||e.get("authorization"))&&!(this.apiKey&&e.get("x-api-key"))&&!r.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!r.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return m([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return m([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return m([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Ca(e)}getUserAgent(){return`${this.constructor.name}/JS ${Pe}`}defaultIdempotencyKey(){return`stainless-node-retry-${jn()}`}makeStatusError(e,r,s,n){return B.generate(e,r,s,n)}buildURL(e,r,s){let n=!f(this,fo,"m",ac).call(this)&&s||this.baseURL,o=xa(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),a=Object.fromEntries(o.searchParams);return(!Un(i)||!Un(a))&&(r={...a,...i,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new w("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:r,options:s}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,s){return this.request(Promise.resolve(s).then(n=>({method:e,path:r,...n})))}request(e,r=null){return new He(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,s){let n=await e,o=n.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(n);let{req:i,url:a,timeout:c}=await this.buildRequest(n,{retryCount:o-r});await this.prepareRequest(i,{url:a,options:n});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=s===void 0?"":`, retryOf: ${s}`,d=Date.now();if(D(this).debug(`[${l}] sending request`,ye({retryOfRequestLogID:s,method:n.method,url:a,options:n,headers:i.headers})),n.signal?.aborted)throw new F;let p=new AbortController,h=await this.fetchWithTimeout(a,i,c,p).catch(ir),g=Date.now();if(h instanceof globalThis.Error){let v=`retrying, ${r} attempts remaining`;if(n.signal?.aborted)throw new F;let k=me(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(r)return D(this).info(`[${l}] connection ${k?"timed out":"failed"} - ${v}`),D(this).debug(`[${l}] connection ${k?"timed out":"failed"} (${v})`,ye({retryOfRequestLogID:s,url:a,durationMs:g-d,message:h.message})),this.retryRequest(n,r,s??l);throw D(this).info(`[${l}] connection ${k?"timed out":"failed"} - error; no more retries left`),D(this).debug(`[${l}] connection ${k?"timed out":"failed"} (error; no more retries left)`,ye({retryOfRequestLogID:s,url:a,durationMs:g-d,message:h.message})),k?new pt:new Re({cause:h})}let b=[...h.headers.entries()].filter(([v])=>v==="request-id").map(([v,k])=>", "+v+": "+JSON.stringify(k)).join(""),S=`[${l}${u}${b}] ${i.method} ${a} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${g-d}ms`;if(!h.ok){let v=await this.shouldRetry(h);if(r&&v){let x=`retrying, ${r} attempts remaining`;return await Ia(h.body),D(this).info(`${S} - ${x}`),D(this).debug(`[${l}] response error (${x})`,ye({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:g-d})),this.retryRequest(n,r,s??l,h.headers)}let k=v?"error; no more retries left":"error; not retryable";D(this).info(`${S} - ${k}`);let U=await h.text().catch(x=>ir(x).message),N=is(U),V=N?void 0:U;throw D(this).debug(`[${l}] response error (${k})`,ye({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,message:V,durationMs:Date.now()-d})),this.makeStatusError(h.status,N,V,h.headers)}return D(this).info(S),D(this).debug(`[${l}] response start`,ye({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:g-d})),{response:h,options:n,controller:p,requestLogID:l,retryOfRequestLogID:s,startTime:d}}getAPIList(e,r,s){return this.requestAPIList(r,s&&"then"in s?s.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...s})}requestAPIList(e,r){let s=this.makeRequest(r,null,void 0);return new fr(this,s,e)}async fetchWithTimeout(e,r,s,n){let{signal:o,method:i,...a}=r||{},c=this._makeAbort(n);o&&o.addEventListener("abort",c,{once:!0});let l=setTimeout(c,s),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:n.signal,...u?{duplex:"half"}:{},method:"GET",...a};i&&(d.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,s,n){let o,i=n?.get("retry-after-ms");if(i){let c=parseFloat(i);Number.isNaN(c)||(o=c)}let a=n?.get("retry-after");if(a&&!o){let c=parseFloat(a);Number.isNaN(c)?o=Date.parse(a)-Date.now():o=c*1e3}if(o===void 0){let c=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,c)}return await Ea(o),this.makeRequest(e,r-1,s)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}calculateNonstreamingTimeout(e,r){if(36e5*e/128e3>6e5||r!=null&&e>r)throw new w("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:r=0}={}){let s={...e},{method:n,path:o,query:i,defaultBaseURL:a}=s,c=this.buildURL(o,i,a);"timeout"in s&&va("timeout",s.timeout),s.timeout=s.timeout??this.timeout;let{bodyHeaders:l,body:u}=this.buildBody({options:s}),d=await this.buildHeaders({options:e,method:n,bodyHeaders:l,retryCount:r});return{req:{method:n,headers:d,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...s.fetchOptions??{}},url:c,timeout:s.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:s,retryCount:n}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=m([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))}:{},...Aa(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(i),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let s=m([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:as(e)}:typeof e=="object"&&s.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:f(this,Cs,"f").call(this,{body:e,headers:s})}};ho=M,Cs=new WeakMap,fo=new WeakSet,ac=function(){return this.baseURL!=="https://api.anthropic.com"};M.Anthropic=ho;M.HUMAN_PROMPT=cc;M.AI_PROMPT=lc;M.DEFAULT_TIMEOUT=6e5;M.AnthropicError=w;M.APIError=B;M.APIConnectionError=Re;M.APIConnectionTimeoutError=pt;M.APIUserAbortError=F;M.NotFoundError=_t;M.ConflictError=bt;M.RateLimitError=xt;M.BadRequestError=mt;M.AuthenticationError=gt;M.InternalServerError=St;M.PermissionDeniedError=yt;M.UnprocessableEntityError=wt;M.toFile=hs;var ue=class extends M{constructor(){super(...arguments),this.completions=new Xe(this),this.messages=new Ce(this),this.models=new Ze(this),this.beta=new H(this)}};ue.Completions=Xe;ue.Messages=Ce;ue.Models=Ze;ue.Beta=H;function hc(t){return"generateStream"in t&&typeof t.generateStream=="function"}var Ns=class{#e;#t;#s;#o;#r;#n;constructor(e){this.#e=e.baseURL.replace(/\/+$/,""),this.#t=e.apiKey,this.#s=e.model,this.#o=e.temperature,this.#r=e.maxTokens,this.#n=e.fetch??fetch}async generate(e){try{let r=await this.#n(`${this.#e}/chat/completions`,{method:"POST",headers:this.#a(),body:JSON.stringify(this.#l(e))});if(!r.ok)return{type:"error",category:this.#c(r.status),message:`Provider request failed with status ${r.status}.`,recoverable:r.status===408||r.status===409||r.status===429||r.status>=500};let s=await r.json(),n=s.choices?.[0],o=n?.finish_reason,i=n?.message,a=i?.tool_calls;return o==="tool_calls"&&a!==void 0&&a.length>0?{type:"tool_calls",calls:a.map(c=>({id:c.id,name:c.function.name,input:po(c.function.arguments)})),...s.usage?{usage:this.#d(s.usage)}:{}}:{type:"message",content:i?.content??"",...s.usage?{usage:this.#d(s.usage)}:{}}}catch{return{type:"error",category:"network",message:"Provider network request failed.",recoverable:!0}}}async*generateStream(e){try{let r=await this.#n(`${this.#e}/chat/completions`,{method:"POST",headers:this.#a(),body:JSON.stringify({...this.#l(e),stream:!0})});if(!r.ok){yield{type:"error",category:this.#c(r.status),message:`Provider request failed with status ${r.status}.`,recoverable:r.status===408||r.status===409||r.status===429||r.status>=500};return}if(r.body===null){yield{type:"error",category:"network",message:"No response body for streaming request.",recoverable:!0};return}let s=new Map,n="",o,i=null;for await(let a of Mf(r.body)){if(a==="[DONE]")break;let c;try{c=JSON.parse(a)}catch{continue}let l=c.choices?.[0];if(l!==void 0){l.finish_reason!==null&&l.finish_reason!==void 0&&(i=l.finish_reason);let u=l.delta;if(u!==void 0&&(u.content&&(n+=u.content,yield{type:"token_delta",delta:u.content}),u.tool_calls))for(let d of u.tool_calls){s.has(d.index)||s.set(d.index,{id:"",name:"",arguments:""});let p=s.get(d.index);d.id&&(p.id=d.id),d.function?.name&&(p.name=d.function.name),d.function?.arguments&&(p.arguments+=d.function.arguments)}}c.usage&&(o=this.#d(c.usage))}i==="tool_calls"&&s.size>0?yield{type:"tool_calls",calls:Array.from(s.entries()).sort(([c],[l])=>c-l).map(([,c])=>({id:c.id,name:c.name,input:po(c.arguments)})),...o!==void 0?{usage:o}:{}}:yield{type:"message_done",content:n,...o!==void 0?{usage:o}:{}}}catch{yield{type:"error",category:"network",message:"Provider network request failed.",recoverable:!0}}}#a(){return{"content-type":"application/json",...this.#t?{authorization:`Bearer ${this.#t}`}:{}}}#l(e){return{model:this.#s,messages:e.messages.map(r=>this.#h(r)),...e.tools!==void 0&&e.tools.length>0?{tools:e.tools}:{},...this.#o===void 0?{}:{temperature:this.#o},...this.#r===void 0?{}:{max_tokens:this.#r}}}#h(e){return e.role==="tool"?{role:"tool",tool_call_id:e.toolCallId??"",content:e.content??""}:e.role==="assistant"&&e.toolCalls!==void 0&&e.toolCalls.length>0?{role:"assistant",content:e.content,tool_calls:e.toolCalls.map(r=>({id:r.id,type:"function",function:{name:r.name,arguments:typeof r.input=="string"?r.input:JSON.stringify(r.input)}}))}:{role:e.role,content:e.content}}#c(e){return e===401||e===403?"authentication":e===429?"rate_limit":e===400||e===422?"invalid_request":e===404||e===503?"model_unavailable":"unknown"}#d(e){return{...e.prompt_tokens===void 0?{}:{inputTokens:e.prompt_tokens},...e.completion_tokens===void 0?{}:{outputTokens:e.completion_tokens},...e.total_tokens===void 0?{}:{totalTokens:e.total_tokens}}}};async function*Mf(t){let e=t.getReader(),r=new TextDecoder,s="";try{for(;;){let{done:n,value:o}=await e.read();if(n)break;s+=r.decode(o,{stream:!0});let i=s.split(`
|
|
74
|
+
`);this.baseURL=o.baseURL,this.timeout=o.timeout??fo.DEFAULT_TIMEOUT,this.logger=o.logger??console;let i="warn";this.logLevel=i,this.logLevel=Fn(o.logLevel,"ClientOptions.logLevel",this)??Fn(Ht("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??i,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??Oa(),_(this,Cs,Ma,"f");let a=Ht("ANTHROPIC_CUSTOM_HEADERS");if(a){let c={};for(let l of a.split(`
|
|
75
|
+
`)){let u=l.indexOf(":");u>=0&&(c[l.substring(0,u).trim()]=l.substring(u+1).trim())}o.defaultHeaders={...c,...o.defaultHeaders}}this._options=o,this.apiKey=typeof r=="string"?r:null,this.authToken=s}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){if(!(e.get("x-api-key")||e.get("authorization"))&&!(this.apiKey&&e.get("x-api-key"))&&!r.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!r.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return m([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return m([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return m([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Ca(e)}getUserAgent(){return`${this.constructor.name}/JS ${Pe}`}defaultIdempotencyKey(){return`stainless-node-retry-${$n()}`}makeStatusError(e,r,s,n){return B.generate(e,r,s,n)}buildURL(e,r,s){let n=!f(this,uo,"m",ac).call(this)&&s||this.baseURL,o=xa(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),a=Object.fromEntries(o.searchParams);return(!Dn(i)||!Dn(a))&&(r={...a,...i,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new w("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:r,options:s}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,s){return this.request(Promise.resolve(s).then(n=>({method:e,path:r,...n})))}request(e,r=null){return new He(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,s){let n=await e,o=n.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(n);let{req:i,url:a,timeout:c}=await this.buildRequest(n,{retryCount:o-r});await this.prepareRequest(i,{url:a,options:n});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=s===void 0?"":`, retryOf: ${s}`,d=Date.now();if(D(this).debug(`[${l}] sending request`,ye({retryOfRequestLogID:s,method:n.method,url:a,options:n,headers:i.headers})),n.signal?.aborted)throw new F;let p=new AbortController,h=await this.fetchWithTimeout(a,i,c,p).catch(ir),g=Date.now();if(h instanceof globalThis.Error){let v=`retrying, ${r} attempts remaining`;if(n.signal?.aborted)throw new F;let k=me(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(r)return D(this).info(`[${l}] connection ${k?"timed out":"failed"} - ${v}`),D(this).debug(`[${l}] connection ${k?"timed out":"failed"} (${v})`,ye({retryOfRequestLogID:s,url:a,durationMs:g-d,message:h.message})),this.retryRequest(n,r,s??l);throw D(this).info(`[${l}] connection ${k?"timed out":"failed"} - error; no more retries left`),D(this).debug(`[${l}] connection ${k?"timed out":"failed"} (error; no more retries left)`,ye({retryOfRequestLogID:s,url:a,durationMs:g-d,message:h.message})),k?new pt:new Re({cause:h})}let b=[...h.headers.entries()].filter(([v])=>v==="request-id").map(([v,k])=>", "+v+": "+JSON.stringify(k)).join(""),S=`[${l}${u}${b}] ${i.method} ${a} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${g-d}ms`;if(!h.ok){let v=await this.shouldRetry(h);if(r&&v){let x=`retrying, ${r} attempts remaining`;return await Ia(h.body),D(this).info(`${S} - ${x}`),D(this).debug(`[${l}] response error (${x})`,ye({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:g-d})),this.retryRequest(n,r,s??l,h.headers)}let k=v?"error; no more retries left":"error; not retryable";D(this).info(`${S} - ${k}`);let U=await h.text().catch(x=>ir(x).message),N=is(U),V=N?void 0:U;throw D(this).debug(`[${l}] response error (${k})`,ye({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,message:V,durationMs:Date.now()-d})),this.makeStatusError(h.status,N,V,h.headers)}return D(this).info(S),D(this).debug(`[${l}] response start`,ye({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:g-d})),{response:h,options:n,controller:p,requestLogID:l,retryOfRequestLogID:s,startTime:d}}getAPIList(e,r,s){return this.requestAPIList(r,s&&"then"in s?s.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...s})}requestAPIList(e,r){let s=this.makeRequest(r,null,void 0);return new fr(this,s,e)}async fetchWithTimeout(e,r,s,n){let{signal:o,method:i,...a}=r||{},c=this._makeAbort(n);o&&o.addEventListener("abort",c,{once:!0});let l=setTimeout(c,s),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:n.signal,...u?{duplex:"half"}:{},method:"GET",...a};i&&(d.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,s,n){let o,i=n?.get("retry-after-ms");if(i){let c=parseFloat(i);Number.isNaN(c)||(o=c)}let a=n?.get("retry-after");if(a&&!o){let c=parseFloat(a);Number.isNaN(c)?o=Date.parse(a)-Date.now():o=c*1e3}if(o===void 0){let c=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,c)}return await Ea(o),this.makeRequest(e,r-1,s)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}calculateNonstreamingTimeout(e,r){if(36e5*e/128e3>6e5||r!=null&&e>r)throw new w("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:r=0}={}){let s={...e},{method:n,path:o,query:i,defaultBaseURL:a}=s,c=this.buildURL(o,i,a);"timeout"in s&&va("timeout",s.timeout),s.timeout=s.timeout??this.timeout;let{bodyHeaders:l,body:u}=this.buildBody({options:s}),d=await this.buildHeaders({options:e,method:n,bodyHeaders:l,retryCount:r});return{req:{method:n,headers:d,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...s.fetchOptions??{}},url:c,timeout:s.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:s,retryCount:n}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=m([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))}:{},...Aa(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(i),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let s=m([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:as(e)}:typeof e=="object"&&s.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:f(this,Cs,"f").call(this,{body:e,headers:s})}};fo=M,Cs=new WeakMap,uo=new WeakSet,ac=function(){return this.baseURL!=="https://api.anthropic.com"};M.Anthropic=fo;M.HUMAN_PROMPT=cc;M.AI_PROMPT=lc;M.DEFAULT_TIMEOUT=6e5;M.AnthropicError=w;M.APIError=B;M.APIConnectionError=Re;M.APIConnectionTimeoutError=pt;M.APIUserAbortError=F;M.NotFoundError=_t;M.ConflictError=bt;M.RateLimitError=xt;M.BadRequestError=mt;M.AuthenticationError=gt;M.InternalServerError=St;M.PermissionDeniedError=yt;M.UnprocessableEntityError=wt;M.toFile=hs;var ue=class extends M{constructor(){super(...arguments),this.completions=new Xe(this),this.messages=new Ce(this),this.models=new Ze(this),this.beta=new H(this)}};ue.Completions=Xe;ue.Messages=Ce;ue.Models=Ze;ue.Beta=H;function hc(t){return"generateStream"in t&&typeof t.generateStream=="function"}var Ns=class{#e;#t;#s;#o;#r;#n;constructor(e){this.#e=e.baseURL.replace(/\/+$/,""),this.#t=e.apiKey,this.#s=e.model,this.#o=e.temperature,this.#r=e.maxTokens,this.#n=e.fetch??fetch}async generate(e){try{let r=await this.#n(`${this.#e}/chat/completions`,{method:"POST",headers:this.#a(),body:JSON.stringify(this.#l(e))});if(!r.ok)return{type:"error",category:this.#c(r.status),message:`Provider request failed with status ${r.status}.`,recoverable:r.status===408||r.status===409||r.status===429||r.status>=500};let s=await r.json(),n=s.choices?.[0],o=n?.finish_reason,i=n?.message,a=i?.tool_calls;return o==="tool_calls"&&a!==void 0&&a.length>0?{type:"tool_calls",calls:a.map(c=>({id:c.id,name:c.function.name,input:ho(c.function.arguments)})),...s.usage?{usage:this.#d(s.usage)}:{}}:{type:"message",content:i?.content??"",...s.usage?{usage:this.#d(s.usage)}:{}}}catch{return{type:"error",category:"network",message:"Provider network request failed.",recoverable:!0}}}async*generateStream(e){try{let r=await this.#n(`${this.#e}/chat/completions`,{method:"POST",headers:this.#a(),body:JSON.stringify({...this.#l(e),stream:!0})});if(!r.ok){yield{type:"error",category:this.#c(r.status),message:`Provider request failed with status ${r.status}.`,recoverable:r.status===408||r.status===409||r.status===429||r.status>=500};return}if(r.body===null){yield{type:"error",category:"network",message:"No response body for streaming request.",recoverable:!0};return}let s=new Map,n="",o,i=null;for await(let a of Mf(r.body)){if(a==="[DONE]")break;let c;try{c=JSON.parse(a)}catch{continue}let l=c.choices?.[0];if(l!==void 0){l.finish_reason!==null&&l.finish_reason!==void 0&&(i=l.finish_reason);let u=l.delta;if(u!==void 0&&(u.content&&(n+=u.content,yield{type:"token_delta",delta:u.content}),u.tool_calls))for(let d of u.tool_calls){s.has(d.index)||s.set(d.index,{id:"",name:"",arguments:""});let p=s.get(d.index);d.id&&(p.id=d.id),d.function?.name&&(p.name=d.function.name),d.function?.arguments&&(p.arguments+=d.function.arguments)}}c.usage&&(o=this.#d(c.usage))}i==="tool_calls"&&s.size>0?yield{type:"tool_calls",calls:Array.from(s.entries()).sort(([c],[l])=>c-l).map(([,c])=>({id:c.id,name:c.name,input:ho(c.arguments)})),...o!==void 0?{usage:o}:{}}:yield{type:"message_done",content:n,...o!==void 0?{usage:o}:{}}}catch{yield{type:"error",category:"network",message:"Provider network request failed.",recoverable:!0}}}#a(){return{"content-type":"application/json",...this.#t?{authorization:`Bearer ${this.#t}`}:{}}}#l(e){return{model:this.#s,messages:e.messages.map(r=>this.#h(r)),...e.tools!==void 0&&e.tools.length>0?{tools:e.tools}:{},...this.#o===void 0?{}:{temperature:this.#o},...this.#r===void 0?{}:{max_tokens:this.#r}}}#h(e){return e.role==="tool"?{role:"tool",tool_call_id:e.toolCallId??"",content:e.content??""}:e.role==="assistant"&&e.toolCalls!==void 0&&e.toolCalls.length>0?{role:"assistant",content:e.content,tool_calls:e.toolCalls.map(r=>({id:r.id,type:"function",function:{name:r.name,arguments:typeof r.input=="string"?r.input:JSON.stringify(r.input)}}))}:{role:e.role,content:e.content}}#c(e){return e===401||e===403?"authentication":e===429?"rate_limit":e===400||e===422?"invalid_request":e===404||e===503?"model_unavailable":"unknown"}#d(e){return{...e.prompt_tokens===void 0?{}:{inputTokens:e.prompt_tokens},...e.completion_tokens===void 0?{}:{outputTokens:e.completion_tokens},...e.total_tokens===void 0?{}:{totalTokens:e.total_tokens}}}};async function*Mf(t){let e=t.getReader(),r=new TextDecoder,s="";try{for(;;){let{done:n,value:o}=await e.read();if(n)break;s+=r.decode(o,{stream:!0});let i=s.split(`
|
|
76
76
|
`);s=i.pop()??"";for(let a of i){let c=a.trim();c.startsWith("data: ")&&(yield c.slice(6))}}s+=r.decode();for(let n of s.split(`
|
|
77
|
-
`)){let o=n.trim();o.startsWith("data: ")&&(yield o.slice(6))}}finally{e.releaseLock()}}function
|
|
78
|
-
[truncated ${t.length-
|
|
79
|
-
[truncated ${t.length-
|
|
77
|
+
`)){let o=n.trim();o.startsWith("data: ")&&(yield o.slice(6))}}finally{e.releaseLock()}}function ho(t){try{return JSON.parse(t)}catch{return t}}var Cf={minimal:1024,low:2048,medium:4096,high:8192,max:16384},Ls=class{#e;#t;#s;#o;#r;#n;constructor(e){if(this.#s=e.model,this.#o=e.maxTokens??4096,this.#r=e.temperature,this.#n=e.thinkingBudget,e.client!==void 0||e.streamClient!==void 0)this.#e=e.client??{messages:{create:async()=>{throw new Error("No client provided.")}}},this.#t=e.streamClient;else{let r=new ue({apiKey:e.apiKey});this.#e=r,this.#t={messages:{stream:s=>r.messages.create({...s,stream:!0})}}}}#a(){let e=this.#n;return e===void 0||e==="off"?void 0:e==="adaptive"?{type:"adaptive"}:{type:"enabled",budget_tokens:Cf[e]}}async generate(e){try{let{system:r,messages:s}=uc(e.messages),n=r!==void 0?[{type:"text",text:r,cache_control:{type:"ephemeral"}}]:void 0,o=this.#a(),i=await this.#e.messages.create({model:this.#s,max_tokens:this.#o,...n!==void 0?{system:n}:{},messages:s,...e.tools!==void 0&&e.tools.length>0?{tools:dc(e.tools)}:{},...this.#r!==void 0?{temperature:this.#r}:{},...o!==void 0?{thinking:o}:{}}),a=i.content.filter(Nf);return i.stop_reason==="tool_use"&&a.length>0?{type:"tool_calls",calls:a.map(l=>({id:l.id,name:l.name,input:l.input})),usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}:{type:"message",content:i.content.find(Lf)?.text??"",usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}catch(r){return fc(r)}}async*generateStream(e){if(this.#t===void 0){let r=await this.generate(e);r.type==="message"?(yield{type:"token_delta",delta:r.content},yield{type:"message_done",content:r.content,...r.usage?{usage:r.usage}:{}}):r.type==="tool_calls"?yield{type:"tool_calls",calls:r.calls,...r.usage?{usage:r.usage}:{}}:yield{type:"error",category:r.category,message:r.message,recoverable:r.recoverable};return}try{let{system:r,messages:s}=uc(e.messages),n=r!==void 0?[{type:"text",text:r,cache_control:{type:"ephemeral"}}]:void 0,o=this.#a(),i={model:this.#s,max_tokens:this.#o,...n!==void 0?{system:n}:{},messages:s,...e.tools!==void 0&&e.tools.length>0?{tools:dc(e.tools)}:{},...this.#r!==void 0?{temperature:this.#r}:{},...o!==void 0?{thinking:o}:{}},a=await this.#t.messages.stream(i),c="",l=0,u=0,d=null,p=new Map;for await(let g of a)if(g.type==="message_start")l=g.message.usage.input_tokens;else if(g.type==="content_block_start")g.content_block.type==="tool_use"&&p.set(g.index,{id:g.content_block.id??"",name:g.content_block.name??"",inputJson:""});else if(g.type==="content_block_delta"){if(g.delta.type==="text_delta")c+=g.delta.text,yield{type:"token_delta",delta:g.delta.text};else if(g.delta.type==="input_json_delta"){let b=p.get(g.index);b!==void 0&&(b.inputJson+=g.delta.partial_json)}}else g.type==="message_delta"&&(u=g.usage.output_tokens,d=g.delta.stop_reason);let h={inputTokens:l,outputTokens:u};d==="tool_use"&&p.size>0?yield{type:"tool_calls",calls:Array.from(p.entries()).sort(([b],[S])=>b-S).map(([,b])=>({id:b.id,name:b.name,input:ho(b.inputJson)})),usage:h}:yield{type:"message_done",content:c,usage:h}}catch(r){yield fc(r)}}};function uc(t){let e,r=[],s=0;for(;s<t.length;){let n=t[s];if(n===void 0)break;if(n.role==="system"){e=n.content??void 0,s++;continue}if(n.role==="tool"){let o=[];for(;s<t.length;){let i=t[s];if(i===void 0||i.role!=="tool")break;o.push({type:"tool_result",tool_use_id:i.toolCallId??"",content:i.content??""}),s++}r.push({role:"user",content:o});continue}if(n.role==="assistant"){if(n.toolCalls!==void 0&&n.toolCalls.length>0){let o=[...n.content?[{type:"text",text:n.content}]:[],...n.toolCalls.map(i=>({type:"tool_use",id:i.id,name:i.name,input:i.input}))];r.push({role:"assistant",content:o})}else r.push({role:"assistant",content:n.content??""});s++;continue}r.push({role:"user",content:n.content??""}),s++}return{system:e,messages:r}}function dc(t){return t.map(e=>({name:e.function.name,description:e.function.description,input_schema:{type:"object",...e.function.parameters.properties!==void 0?{properties:e.function.parameters.properties}:{},...e.function.parameters.required!==void 0?{required:e.function.parameters.required}:{}}}))}function Nf(t){return t.type==="tool_use"&&typeof t.id=="string"&&typeof t.name=="string"}function Lf(t){return t.type==="text"&&typeof t.text=="string"}function fc(t){if(typeof t=="object"&&t!==null&&"status"in t&&typeof t.status=="number"){let e=t;return{type:"error",category:$f(e.status),message:e.message??`Anthropic API error ${e.status}.`,recoverable:e.status===429||e.status>=500}}return{type:"error",category:"network",message:"Provider network request failed.",recoverable:!0}}function $f(t){return t===401||t===403?"authentication":t===429?"rate_limit":t===400?"invalid_request":t===404?"model_unavailable":t===413||t===422?"context_length":"unknown"}var $s=class{evaluate(e){let r=e.action.risk;return r==="blocked"?{decision:"deny",risk:r,reason:"Blocked actions are denied."}:e.mode==="observe"?{decision:"ask",risk:r,reason:"Observe mode asks before external actions."}:e.mode==="auto"?r==="high"?{decision:"ask",risk:r,reason:"High-risk action requires approval in auto mode."}:{decision:"allow",risk:r,reason:"Low and medium-risk actions are allowed in auto mode."}:r==="low"?{decision:"allow",risk:r,reason:"Low-risk action is allowed in confirm mode."}:{decision:"ask",risk:r,reason:"Medium and high-risk actions require approval in confirm mode."}}};import{exec as jf}from"child_process";import{access as Bf,readdir as mc,readFile as go,stat as Vw,writeFile as Df,mkdir as Uf}from"fs/promises";import{resolve as Bs,relative as gc,basename as qf,extname as Ff,dirname as Hf,join as js}from"path";function yc(){return{name:"read_file",description:"Read a UTF-8 file inside the workspace.",inputSchema:{type:"object",properties:{path:{type:"string"}},required:["path"]},risk:"low",async execute(t,e){let r=bc(t);if(r===void 0)return Wt("Tool input must include a string path.");let s=yo(e.workspaceRoot,r);if(s===void 0)return _o();if(wc(s.absolutePath))return xc();try{return{ok:!0,content:await go(s.absolutePath,"utf8"),summary:`Read file ${s.displayPath}.`}}catch(n){return bo(n)}}}}function _c(){return{name:"list_directory",description:"List entries in a workspace directory.",inputSchema:{type:"object",properties:{path:{type:"string"}},required:["path"]},risk:"low",async execute(t,e){let r=bc(t);if(r===void 0)return Wt("Tool input must include a string path.");let s=yo(e.workspaceRoot,r);if(s===void 0)return _o();try{return{ok:!0,entries:(await mc(s.absolutePath,{withFileTypes:!0})).map(o=>({name:o.name,type:o.isDirectory()?"directory":o.isFile()?"file":"other"})).sort((o,i)=>o.name.localeCompare(i.name)),summary:`Listed directory ${s.displayPath}.`}}catch(n){return bo(n)}}}}function bc(t){if(typeof t!="object"||t===null||!("path"in t))return;let e=t.path;return typeof e=="string"?e:void 0}function yo(t,e){let r=Bs(t),s=Bs(r,e),n=gc(r,s);if(!(n.startsWith("..")||n===".."||s!==r&&n===""))return{absolutePath:s,displayPath:n===""?".":n}}function Wt(t){return{ok:!1,error:{code:"invalid_input",message:t}}}function _o(){return{ok:!1,error:{code:"path_outside_workspace",message:"Tool path must stay inside the workspace."}}}function bo(t){return{ok:!1,error:{code:typeof t=="object"&&t!==null&&"code"in t?String(t.code):"fs_error",message:"File system operation failed."}}}function wc(t){let e=qf(t).toLowerCase();if(e===".env"||e.startsWith(".env.")||e===".netrc")return!0;let r=Ff(e);return r===".key"||r===".pem"||r===".p12"||r===".pfx"?!0:e==="id_rsa"||e==="id_ed25519"||e==="id_ecdsa"||e==="id_dsa"}function xc(){return{ok:!1,error:{code:"path_not_permitted",message:"Tool path is not permitted."}}}function Wf(t){if(typeof t!="object"||t===null)return;let e=t.path,r=t.content;return typeof e=="string"&&typeof r=="string"?{path:e,content:r}:void 0}var Vf=3e4,po=4e3,Gf=[/\brm\b.*-[a-zA-Z]*r[a-zA-Z]*.*\s+\/\s*$/,/\brm\b.*-[a-zA-Z]*r[a-zA-Z]*.*\s+~\/?$/,/:\(\)\s*\{/,/[|>]\s*\/dev\/(sd|hd|nvme|vd)[a-z0-9]?/,/\b(mkfs(\.[a-z0-9]+)?|fdisk|parted|shred)\b/];function Kf(t){return Gf.some(e=>e.test(t))}function pc(t){return t.length<=po?t:`${t.slice(0,po)}
|
|
78
|
+
[truncated ${t.length-po} characters]`}function zf(t,e,r){return new Promise(s=>{let n=Date.now();jf(t,{cwd:e,timeout:r},(o,i,a)=>{let c=Date.now()-n;if(o?.killed===!0){s({completed:!1});return}let l=o===null?0:typeof o.code=="number"?o.code:1;s({completed:!0,exitCode:l,stdout:pc(i),stderr:pc(a),durationMs:c})})})}function Jf(t){if(typeof t!="object"||t===null)return;let e=t.command;if(typeof e!="string")return;let r=t.timeoutMs;return{command:e,...typeof r=="number"?{timeoutMs:r}:{}}}function Yf(){return{ok:!1,error:{code:"command_blocked",message:"Command matches a blocked pattern."}}}function Xf(){return{ok:!1,error:{code:"sandbox_rejected",message:"Command rejected: workspace sandbox prevents execution outside workspace."}}}var Qf=[/\/\.\.\//,/\bcd\s+\/(\s|$)/,/\bcd\s+~\/?(\s|$)/];function Zf(t){return Qf.some(e=>e.test(t))}function Sc(t){return{name:"run_shell",description:"Run a shell command in the workspace directory. Requires approval.",inputSchema:{type:"object",properties:{command:{type:"string"},timeoutMs:{type:"number"}},required:["command"]},risk:"high",async execute(e,r){let s=Jf(e);if(s===void 0)return Wt("Tool input must include a string command.");if(Kf(s.command))return Yf();if(t?.sandboxed===!0&&Zf(s.command))return Xf();let n=s.timeoutMs??Vf,o=await zf(s.command,r.workspaceRoot,n);return o.completed?{ok:!0,exitCode:o.exitCode,stdout:o.stdout,stderr:o.stderr,durationMs:o.durationMs,summary:`Ran command in ${o.durationMs}ms with exit code ${o.exitCode}.`}:{ok:!1,error:{code:"timeout",message:`Command exceeded ${n}ms timeout.`}}}}}function vc(){return{name:"write_file",description:"Write or overwrite a UTF-8 file inside the workspace. Requires approval.",inputSchema:{type:"object",properties:{path:{type:"string"},content:{type:"string"}},required:["path","content"]},risk:"medium",async execute(t,e){let r=Wf(t);if(r===void 0)return Wt("Tool input must include a string path and string content.");let s=yo(e.workspaceRoot,r.path);if(s===void 0)return _o();if(wc(s.absolutePath))return xc();try{return await Uf(Hf(s.absolutePath),{recursive:!0}),await Df(s.absolutePath,r.content,"utf8"),{ok:!0,summary:`Wrote file ${s.displayPath}.`}}catch(n){return bo(n)}}}}var mo=8e3;function eh(t){try{let e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"?e:void 0}catch{return}}function th(t){return t.replace(/<script[^>]*>[\s\S]*?<\/script>/gi," ").replace(/<style[^>]*>[\s\S]*?<\/style>/gi," ").replace(/<[^>]+>/g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/\s+/g," ").trim()}function rh(t){return t.length<=mo?t:`${t.slice(0,mo)}
|
|
79
|
+
[truncated ${t.length-mo} characters]`}function sh(t){if(typeof t!="object"||t===null)return;let e=t.url;return typeof e=="string"?e:void 0}function Ec(t=fetch){return{name:"read_web_page",description:"Read a public web page and return its text content.",inputSchema:{type:"object",properties:{url:{type:"string"}},required:["url"]},risk:"low",async execute(e,r){let s=sh(e);if(s===void 0)return Wt("Tool input must include a string url.");let n=eh(s);if(n===void 0)return Wt("Tool url must use http or https.");try{let o=await t(s);if(!o.ok)return{ok:!1,error:{code:"http_error",message:`Page request failed with status ${o.status}.`}};let i=await o.text(),a=rh(th(i));return{ok:!0,url:s,content:a,summary:`Read web page ${n.hostname}.`}}catch{return{ok:!1,error:{code:"network_error",message:"Web page request failed."}}}}}}function kc(t){return{name:"update_todos",description:"Update the task list to track progress on multi-step work. Call this when starting a complex task or after completing each step. At most one item may be in_progress at a time.",inputSchema:{type:"object",properties:{todos:{type:"array",items:{type:"object",properties:{content:{type:"string"},status:{type:"string",enum:["pending","in_progress","completed"]}},required:["content","status"]}}},required:["todos"]},risk:"low",async execute(e,r){let s=e;if(!Array.isArray(s.todos))return{ok:!1,error:{code:"invalid_input",message:"todos must be an array."}};let n=[];for(let i of s.todos){if(typeof i!="object"||i===null)return{ok:!1,error:{code:"invalid_input",message:"Each todo must be an object."}};let{content:a,status:c}=i;if(typeof a!="string"||a.length===0)return{ok:!1,error:{code:"invalid_input",message:"Each todo must have a non-empty content string."}};if(c!=="pending"&&c!=="in_progress"&&c!=="completed")return{ok:!1,error:{code:"invalid_input",message:`Invalid status "${String(c)}". Must be pending, in_progress, or completed.`}};n.push({content:a,status:c})}return n.filter(i=>i.status==="in_progress").length>1?{ok:!1,error:{code:"invalid_input",message:"At most one todo may be in_progress at a time."}}:(t?.(n),{ok:!0})}}}function Rc(t){return{name:"load_skill",description:"Load the full instructions for a named skill. Call this when you need to follow a skill's detailed guidance. Available skills are listed in the <skills> section.",risk:"low",inputSchema:{type:"object",properties:{name:{type:"string",description:"The exact skill name to load."}},required:["name"]},async execute(e){let{name:r}=e,s=t.get(r);if(s===void 0)return{ok:!1,error:`Skill "${r}" not found. Check the skills list for available names.`};try{let{readFile:n}=await import("fs/promises");return{ok:!0,content:await n(s,"utf-8")}}catch{return{ok:!1,error:`Could not read skill file for "${r}".`}}}}}function Pc(t){return{name:"memory_search",description:"Search over memory files (MEMORY.md, USER.md, memory/YYYY-MM-DD.md) for relevant content. Returns matching excerpts.",risk:"low",inputSchema:{type:"object",properties:{query:{type:"string"},maxResults:{type:"number"}},required:["query"]},async execute(e){let r=e,s=typeof r.query=="string"?r.query:"",n=typeof r.maxResults=="number"?r.maxResults:5,o=[],i=js(t,"MEMORY.md"),a=js(t,"USER.md"),c=js(t,"memory");for(let d of[i,a])try{await Bf(d),o.push(d)}catch{}try{let d=await mc(c,{recursive:!0,withFileTypes:!0});for(let p of d)if(p.isFile()&&p.name.endsWith(".md")){let h=typeof p.parentPath=="string"?p.parentPath:p.path;o.push(js(h,p.name))}}catch{}if(o.length===0)return{ok:!0,results:[],total:0};let l=s.toLowerCase().split(/\s+/).filter(d=>d.length>0),u=[];for(let d of o){let p;try{p=await go(d,"utf8")}catch{continue}let h=p.split(/\n\n+/),g=gc(t,d);for(let b of h){let S=b.toLowerCase();if(l.some(v=>S.includes(v))&&(u.push({file:g,excerpt:b.trim()}),u.length>=n))break}if(u.length>=n)break}return{ok:!0,results:u,total:u.length}}}}function Tc(t){return{name:"memory_get",description:"Read the full contents of a specific memory file. Valid paths: MEMORY.md, USER.md, memory/YYYY-MM-DD.md",risk:"low",inputSchema:{type:"object",properties:{path:{type:"string",description:"Relative path within the memory workspace, e.g. MEMORY.md or memory/2026-05-05.md"}},required:["path"]},async execute(e){let r=e,s=typeof r.path=="string"?r.path:"";if(s.includes(".."))return{ok:!0,error:"Path traversal is not permitted."};if(s.startsWith("/"))return{ok:!0,error:"Absolute paths are not permitted."};if(!s.endsWith(".md"))return{ok:!0,error:"Only .md files are permitted."};let n=Bs(t),o=Bs(n,s);if(!o.startsWith(n+"/")&&o!==n)return{ok:!0,error:"Path traversal is not permitted."};try{return{ok:!0,content:await go(o,"utf8")}}catch{return{ok:!0,error:`File not found: ${s}`}}}}}var Kw=512*1024;var Ds=class{#e=[];async append(e){this.#e.push(e)}async listRecent(e={}){return[...e.limit===void 0?this.#e:this.#e.slice(-e.limit)]}async listByRun(e){return this.#e.filter(r=>r.runId===e)}};var nh=12,oh=2,ih="Low-risk actions run automatically. Medium and high-risk actions require approval. Blocked actions are never permitted.",ah="Do not restate the plan. Act now: take the first concrete tool action you can.",Oc=/\b(?:i(?:'ll| will)|let me|i(?:'m| am)\s+going to|first[, ]+i(?:'ll| will)|next[, ]+i(?:'ll| will)|i can do that)\b/i,ch=/\b(?:done|finished|implemented|updated|fixed|changed|ran|verified|found|here(?:'s| is) what|blocked by|the blocker is)\b/i,lh=/^(?:plan|steps?|next steps?)\s*:/im,uh=/^(?:[-*•]\s+|\d+[.)]\s+)/u,dh=/\b(?:inspect|investigate|check|look(?:\s+into|\s+at)?|read|search|find|debug|fix|patch|update|change|edit|write|implement|run|test|verify|review|analy(?:s|z)e|summari(?:s|z)e|explain|answer|show|share|report|prepare|refactor|deploy)\b/i,fh=700,Us=class{#e;#t;#s;#o;#r;#n;#a;#l;#h;#c;#d;#p;#f;#u;#g;#x;#_;#b;#w;#y=[];constructor(e){this.#e=e.contextAssembler??new ss,this.#t=e.modelProvider,this.#s=e.permissionPolicy??new $s,this.#o=e.approvalResolver,this.#a=e.maxSteps??nh,this.#x=e.executionContract??"default",this.#l=e.executionContract==="strict-agentic"?e.maxPlanningStallRetries??3:e.maxPlanningStallRetries??oh,this.#n=e.skillIndex??[];let r=e.systemInstruction??"";this.#h=e.executionContract==="strict-agentic"?`${r}
|
|
80
80
|
|
|
81
81
|
Execution contract: strict-agentic. Act immediately. Do not narrate plans. Call tools now.`:r,this.#c=e.runtime,this.#d=e.preferStreaming??!1,this.#p=e.compaction,this.#f=e.promptMode,this.#u=e.hooks,this.#g=e.sessionMutex,this.#_=e.createRunId??Ac("run"),this.#b=e.createEventId??Ac("evt"),this.#w=e.now??(()=>new Date().toISOString());let s=kc(o=>{this.#y=o}),n=e.tools??[];this.#r=new Map([s,...n].map(o=>[o.name,o]))}async*runTurn(e){let r=this.#_(),s=e.sessionId?{runId:r,sessionId:e.sessionId}:{runId:r},n=[],o=this.#g?await this.#g.acquire(e.sessionId??"global"):void 0;try{if(this.#u?.beforeTurn!==void 0)try{await this.#u.beforeTurn(e)}catch(v){typeof process<"u"&&process.env.NODE_ENV!=="production"&&console.warn("[AgentRuntime] beforeTurn hook threw:",v)}let i=v=>(n.push(v),v);yield i(this.#i({...s,type:"run_started",userMessage:e.message}));let a=this.#S(),c=await this.#e.assemble({systemInstruction:this.#h,...this.#c?{runtime:this.#c}:{},...a.length>0?{tools:a}:{},permissionGuidance:ih,...this.#n.length>0?{skillIndex:this.#n}:{},...e.recentMessages?{recentMessages:e.recentMessages}:{},...this.#f!==void 0?{promptMode:this.#f}:{},userMessage:e.message});yield i(this.#i({...s,type:"context_assembled",messageCount:c.modelInput.messages.length,systemInstructionIncluded:c.report.includedSections.includes("identity")}));let l=this.#v(),u=c.modelInput.messages,d=0,p=0,h=!1;this.#y=[];let g=[],b=c.modelInput.messages.at(-1);for(b&&g.push({...b});d<this.#a;){if(e.signal?.aborted){yield i(this.#i({...s,type:"run_failed",error:{message:"Aborted by user.",recoverable:!1}})),await this.#m(n);return}if(this.#p!==void 0){let x=u.length;u=await wa(u,this.#t,this.#p);let $=u.length;if($<x){let R=u.find(T=>T.role==="system"&&typeof T.content=="string"&&T.content.startsWith(`Conversation summary:
|
|
82
82
|
`)),A=R&&typeof R.content=="string"?R.content.slice(22):"";yield i(this.#i({...s,type:"compaction_triggered",messagesBefore:x,messagesAfter:$,summary:A}))}if(this.#u?.onCompaction!==void 0)try{await this.#u.onCompaction(x,$)}catch(R){typeof process<"u"&&process.env.NODE_ENV!=="production"&&console.warn("[AgentRuntime] onCompaction hook threw:",R)}}yield i(this.#i({...s,type:"model_request_started",provider:"configured"}));let v={messages:u,...l.length>0?{tools:l}:{},...c.modelInput.options!==void 0?{options:c.modelInput.options}:{}},k;if(this.#d&&hc(this.#t)){let x="",$,R,A;for await(let T of this.#t.generateStream(v)){if(e.signal?.aborted)break;T.type==="token_delta"?yield i(this.#i({...s,type:"token_delta",delta:T.delta})):T.type==="message_done"?(x=T.content,R=T.usage):T.type==="tool_calls"?($=T.calls,R=T.usage):T.type==="error"&&(A={category:T.category,message:T.message,recoverable:T.recoverable})}A!==void 0?k={type:"error",category:A.category,message:A.message,recoverable:A.recoverable}:$!==void 0?k={type:"tool_calls",calls:$,...R!==void 0?{usage:R}:{}}:k={type:"message",content:x,...R!==void 0?{usage:R}:{}}}else k=await this.#t.generate(v);if(yield i(this.#i({...s,type:"model_request_completed",provider:"configured"})),d++,k.type==="error"){yield i(this.#i({...s,type:"run_failed",error:{message:k.message,recoverable:k.recoverable}})),await this.#m(n);return}if(k.type==="message"){if([...this.#r.keys()].some(R=>R!=="update_todos")&&!h&&gh(k.content)){if(p++,yield i(this.#i({...s,type:"planning_stall_detected",stallCount:p,maxRetries:this.#l})),p>=this.#l){yield i(this.#i({...s,type:"run_failed",error:{message:"Agent stopped after repeated plan-only turns without taking action.",recoverable:!1}})),await this.#m(n);return}u=[...u,{role:"assistant",content:k.content},{role:"user",content:ah}];continue}p=0,g.push({role:"assistant",content:k.content}),yield i(this.#i({...s,type:"assistant_message_created",message:{role:"assistant",content:k.content}})),yield i(this.#i({...s,type:"turn_complete",messages:[...g]})),yield i(this.#i({...s,type:"run_completed"})),await this.#m(n);return}p=0,k.calls.some(x=>x.name!=="update_todos")&&(h=!0);let U={role:"assistant",content:null,toolCalls:k.calls};u=[...u,U],g.push({...U});let N=[],V=!1,W="";for(let x of k.calls){yield i(this.#i({...s,type:"tool_call_requested",call:x}));let $=this.#r.get(x.name);if($===void 0){let q=`Tool "${x.name}" is not registered.`;yield i(this.#i({...s,type:"tool_failed",callId:x.id,toolName:x.name,error:{message:q}}));let G={role:"tool",toolCallId:x.id,content:`Error: ${q}`};N.push(G),g.push({...G});continue}let R=this.#s.evaluate({mode:ph(this.#c?.mode),action:hh(x,$.risk)});if(yield i(this.#i({...s,type:"tool_call_permission_evaluated",callId:x.id,toolName:x.name,decision:R})),R.decision==="deny"){V=!0,W=`Tool call ${x.name} was denied.`;break}if(R.decision==="ask"){yield i(this.#i({...s,type:"approval_requested",callId:x.id,toolName:x.name,decision:R}));let q=this.#o===void 0?{approved:!1,reason:"No approval resolver was configured."}:await this.#o.resolve({call:x,decision:R});if(yield i(this.#i({...s,type:"approval_resolved",callId:x.id,toolName:x.name,resolution:q})),!q.approved){V=!0,W=`Tool call ${x.name} was denied.`;break}}if(this.#u?.beforeToolCall!==void 0){let q;try{q=await this.#u.beforeToolCall(x)}catch(G){typeof process<"u"&&process.env.NODE_ENV!=="production"&&console.warn("[AgentRuntime] beforeToolCall hook threw:",G)}if(q==="abort"){let G="Tool call aborted by hook.";yield i(this.#i({...s,type:"tool_failed",callId:x.id,toolName:x.name,error:{message:G}}));let ie={role:"tool",toolCallId:x.id,content:`Error: ${G}`};N.push(ie),g.push({...ie});continue}}yield i(this.#i({...s,type:"tool_started",callId:x.id,toolName:x.name}));let A;try{A=await $.execute(x.input,{workspaceRoot:this.#c?.workspace??process.cwd()})}catch(q){let G=q instanceof Error?q.message:"Unknown tool execution error.";yield i(this.#i({...s,type:"tool_failed",callId:x.id,toolName:x.name,error:{message:G}}));let ie={role:"tool",toolCallId:x.id,content:`Error: ${G}`};N.push(ie),g.push({...ie});continue}yield i(this.#i({...s,type:"tool_completed",callId:x.id,toolName:x.name,result:A}));let T={role:"tool",toolCallId:x.id,content:JSON.stringify(A)};if(N.push(T),g.push({...T}),this.#u?.afterToolCall!==void 0)try{await this.#u.afterToolCall(x,A)}catch(q){typeof process<"u"&&process.env.NODE_ENV!=="production"&&console.warn("[AgentRuntime] afterToolCall hook threw:",q)}}if(V){yield i(this.#i({...s,type:"run_failed",error:{message:W,recoverable:!1}})),await this.#m(n);return}k.calls.some(x=>x.name==="update_todos")&&(yield i(this.#i({...s,type:"todos_updated",todos:[...this.#y]}))),u=[...u,...N]}yield i(this.#i({...s,type:"run_failed",error:{message:`Agent loop reached the step limit of ${this.#a}.`,recoverable:!1}})),await this.#m(n)}finally{o?.()}}async#m(e){if(this.#u?.afterTurn!==void 0)try{await this.#u.afterTurn(e)}catch(r){typeof process<"u"&&process.env.NODE_ENV!=="production"&&console.warn("[AgentRuntime] afterTurn hook threw:",r)}}#S(){return[...this.#r.values()].map(e=>({name:e.name,description:e.description,risk:e.risk}))}#v(){return[...this.#r.values()].map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.inputSchema}}))}#i(e){return{...e,eventId:this.#b(),timestamp:this.#w()}}};function Ac(t){return()=>`${t}_${crypto.randomUUID()}`}function hh(t,e){return{kind:"tool",name:t.name,summary:`Model requested tool ${t.name}.`,risk:e}}function ph(t){return t==="observe"||t==="auto"?t:"confirm"}function mh(t){let e=t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(e.length===0)return!1;let r=e.filter(o=>uh.test(o)).length,s=e.some(o=>Oc.test(o));return lh.test(e[0]??"")&&s||r>=2&&s}function gh(t){let e=t.trim();if(!e||e.length>fh||e.includes("```")||ch.test(e))return!1;let r=mh(e);return!(!Oc.test(e)&&!r||!r&&!dh.test(e))}var qs=class{#e=new Map;register(e){this.#e.set(e.id,e)}unregister(e){this.#e.delete(e)}touch(e){let r=this.#e.get(e);r!==void 0&&this.#e.set(e,{...r,lastActivityAt:new Date().toISOString()})}get(e){return this.#e.get(e)}list(){return Array.from(this.#e.values())}listByAdapter(e){return this.list().filter(r=>r.adapterName===e)}};import{mkdir as yh,readdir as _h,readFile as bh,writeFile as wh}from"fs/promises";import{join as xh}from"path";var Fs=class{#e;#t;#s;#o;constructor(e){this.#e=e.directory,this.#t=e.createSessionId??Cc("sess"),this.#s=e.createMessageId??Cc("msg"),this.#o=e.now??(()=>new Date().toISOString())}async createSession(e={}){let r=this.#o(),s={id:this.#t(),...e.title===void 0?{}:{title:e.title},createdAt:r,updatedAt:r};return await this.#r(s.id,{type:"session",session:s}),{...s}}async getSession(e){let r=await this.#n(e);return r.session===void 0?void 0:{...r.session}}async listSessions(e={}){let r=await this.#l(),s=[];for(let i of r){let a=await this.getSession(i);a!==void 0&&s.push(a)}let n=s.sort(vh);return(e.limit===void 0?n:n.slice(0,e.limit)).map(i=>({...i}))}async appendMessage(e){if((await this.#n(e.sessionId)).session===void 0)throw new Error(`Unknown session "${e.sessionId}".`);let s=this.#o(),n={id:this.#s(),sessionId:e.sessionId,role:e.role,content:e.content,createdAt:s,...e.toolCalls!==void 0?{toolCalls:e.toolCalls}:{},...e.toolCallId!==void 0?{toolCallId:e.toolCallId}:{}};return await this.#r(e.sessionId,{type:"message",message:n}),{...n}}async listMessages(e,r={}){let s=await this.#n(e);return(r.limit===void 0?s.messages:s.messages.slice(-r.limit)).map(o=>({...o}))}async appendTraceEvent(e){if((await this.#n(e.sessionId)).session===void 0)throw new Error(`Unknown session "${e.sessionId}".`);let s={sessionId:e.sessionId,event:e.event,createdAt:this.#o()};return await this.#r(e.sessionId,{type:"trace",traceEvent:s}),Mc(s)}async listTraceEvents(e,r={}){let s=await this.#n(e);return(r.limit===void 0?s.traceEvents:s.traceEvents.slice(-r.limit)).map(o=>Mc(o))}async appendCompactBoundary(e){if((await this.#n(e.sessionId)).session===void 0)throw new Error(`Unknown session "${e.sessionId}".`);let s=this.#o();await this.#r(e.sessionId,{type:"compact_boundary",summary:e.summary,messagesBefore:e.messagesBefore,messagesAfter:e.messagesAfter,createdAt:s})}async#r(e,r){await yh(this.#e,{recursive:!0}),await wh(this.#a(e),`${JSON.stringify(r)}
|
|
83
83
|
`,{flag:"a"})}async#n(e){let r="";try{r=await bh(this.#a(e),"utf8")}catch(i){if(Ic(i)&&i.code==="ENOENT")return{messages:[],traceEvents:[]};throw i}let s=[],n=[],o;for(let i of r.split(`
|
|
84
|
-
`)){if(i.trim()==="")continue;let a=JSON.parse(i);a.type==="session"?o=a.session:a.type==="compact_boundary"?(s=[],a.summary&&s.push({id:`cmpct_${a.createdAt}`,sessionId:o?.id??"",role:"system",content:a.summary,createdAt:a.createdAt}),o&&a.createdAt>o.updatedAt&&(o={...o,updatedAt:a.createdAt})):a.type==="message"?(s.push(a.message),o&&a.message.createdAt>o.updatedAt&&(o={...o,updatedAt:a.message.createdAt})):(n.push(a.traceEvent),o&&a.traceEvent.createdAt>o.updatedAt&&(o={...o,updatedAt:a.traceEvent.createdAt}))}return{...o===void 0?{}:{session:o},messages:s,traceEvents:n}}#a(e){return Sh(e),xh(this.#e,`${e}.jsonl`)}async#l(){try{return(await _h(this.#e)).filter(r=>r.endsWith(".jsonl")).map(r=>r.slice(0,-6)).filter(r=>/^[A-Za-z0-9_-]+$/.test(r))}catch(e){if(Ic(e)&&e.code==="ENOENT")return[];throw e}}};function Sh(t){if(!/^[A-Za-z0-9_-]+$/.test(t))throw new Error(`Unsafe session id "${t}".`)}function Ic(t){return t instanceof Error&&"code"in t}function vh(t,e){return e.updatedAt.localeCompare(t.updatedAt)}function Mc(t){return{...t,event:structuredClone(t.event)}}function Cc(t){return()=>`${t}_${crypto.randomUUID()}`}import{copyFile as
|
|
84
|
+
`)){if(i.trim()==="")continue;let a=JSON.parse(i);a.type==="session"?o=a.session:a.type==="compact_boundary"?(s=[],a.summary&&s.push({id:`cmpct_${a.createdAt}`,sessionId:o?.id??"",role:"system",content:a.summary,createdAt:a.createdAt}),o&&a.createdAt>o.updatedAt&&(o={...o,updatedAt:a.createdAt})):a.type==="message"?(s.push(a.message),o&&a.message.createdAt>o.updatedAt&&(o={...o,updatedAt:a.message.createdAt})):(n.push(a.traceEvent),o&&a.traceEvent.createdAt>o.updatedAt&&(o={...o,updatedAt:a.traceEvent.createdAt}))}return{...o===void 0?{}:{session:o},messages:s,traceEvents:n}}#a(e){return Sh(e),xh(this.#e,`${e}.jsonl`)}async#l(){try{return(await _h(this.#e)).filter(r=>r.endsWith(".jsonl")).map(r=>r.slice(0,-6)).filter(r=>/^[A-Za-z0-9_-]+$/.test(r))}catch(e){if(Ic(e)&&e.code==="ENOENT")return[];throw e}}};function Sh(t){if(!/^[A-Za-z0-9_-]+$/.test(t))throw new Error(`Unsafe session id "${t}".`)}function Ic(t){return t instanceof Error&&"code"in t}function vh(t,e){return e.updatedAt.localeCompare(t.updatedAt)}function Mc(t){return{...t,event:structuredClone(t.event)}}function Cc(t){return()=>`${t}_${crypto.randomUUID()}`}import{copyFile as o0,mkdir as i0,readFile as Nc,readdir as Eh,writeFile as a0}from"fs/promises";import{homedir as kh}from"os";import{basename as u0,join as Hs}from"path";var Rh=[{name:"research",description:"Use when investigating external information, comparing sources, or summarizing findings. Guides web search, source reading, source comparison, and citation-aware output.",body:"Search for relevant sources, read and compare at least two, and summarize findings with source links. Prefer primary sources. Flag conflicting evidence.",source:"built-in",filePath:""},{name:"project-inspector",description:"Use when understanding a codebase, identifying technologies, or summarizing module responsibilities. Guides project structure inspection and technology detection.",body:"Read README, list top-level directories, inspect package files, and summarize each module's role. Identify entry points and dependency boundaries.",source:"built-in",filePath:""},{name:"safe-shell",description:"Use when planning to run shell commands, especially destructive or irreversible ones. Guides shell command risk assessment and command purpose explanation.",body:"State the purpose before running. Prefer read-only commands. Avoid rm -rf, force flags, or piped untrusted input. Confirm intent before destructive operations.",source:"built-in",filePath:""}],Ws=class{async load(e={}){let r=new Set,s=[],n=a=>{r.has(a.name)||(r.add(a.name),s.push(a))};if(e.workspaceRoot!==void 0){let a=Hs(e.workspaceRoot,"skills");for(let c of await this.#e(a,"workspace",e))n(c)}let o=e.userSkillsDir??Hs(kh(),".vole","skills"),i=await Ph(o,e.readFile);for(let a of await this.#e(o,"user",e,i))n(a);for(let a of Rh)n(a);return s}async#e(e,r,s,n){let o=s.readDir??(l=>Eh(l)),i=s.readFile??(l=>Nc(l,"utf8")),a;try{a=await o(e)}catch(l){if(Ah(l)&&l.code==="ENOENT")return[];throw l}let c=[];for(let l of a){if(l==="skills-index.json")continue;let u=Hs(e,l,"SKILL.md");if(r==="user"&&n!==void 0){let d=n.skills.find(p=>p.name===l);if(d!==void 0&&d.enabled===!1)continue}try{let d=await i(u),p=Th(d);if(p!==null){let h,g;if(r==="user"){let S=n?.skills.find(v=>v.name===l);h=S?.trusted??!1,g=S?.enabled??!0}let b={...p,source:r,filePath:u,...h!==void 0?{trusted:h}:{},...g!==void 0?{enabled:g}:{}};c.push(b)}}catch{}}return c}};async function Ph(t,e){let r=e??(n=>Nc(n,"utf8")),s=Hs(t,"skills-index.json");try{let n=await r(s);return JSON.parse(n)}catch{return}}function Th(t){let e=t.split(`
|
|
85
85
|
`);if(e[0]?.trim()!=="---")return null;let r=e.findIndex((g,b)=>b>0&&g.trim()==="---");if(r===-1)return null;let s=e.slice(1,r),n=e.slice(r+1).join(`
|
|
86
|
-
`).trim(),o={},i={},a=null;for(let g of s){let b=/^\s+-\s+(.+)$/.exec(g);if(b!==null&&a!==null){let U=b[1]?.trim()??"";U.length>0&&(i[a]=[...i[a]??[],U]);continue}let S=g.indexOf(":");if(S===-1){a=null;continue}let v=g.slice(0,S).trim(),k=g.slice(S+1).trim();if(v.length===0){a=null;continue}k===""?a=v:(a=null,o[v]=k)}let{name:c,description:l,version:u,origin:d,permissions:p}=o;if(!c||!l)return null;let h;return p!==void 0&&p.length>0?h=p.split(",").map(g=>g.trim()).filter(g=>g.length>0):i.permissions!==void 0&&(h=i.permissions),{name:c,description:l,body:n,...u!==void 0?{version:u}:{},...d!==void 0?{origin:d}:{},...h!==void 0?{permissions:h}:{}}}function Lc(t){return{name:t.name,description:t.description,source:t.source}}function Ah(t){return t instanceof Error&&"code"in t}async function
|
|
86
|
+
`).trim(),o={},i={},a=null;for(let g of s){let b=/^\s+-\s+(.+)$/.exec(g);if(b!==null&&a!==null){let U=b[1]?.trim()??"";U.length>0&&(i[a]=[...i[a]??[],U]);continue}let S=g.indexOf(":");if(S===-1){a=null;continue}let v=g.slice(0,S).trim(),k=g.slice(S+1).trim();if(v.length===0){a=null;continue}k===""?a=v:(a=null,o[v]=k)}let{name:c,description:l,version:u,origin:d,permissions:p}=o;if(!c||!l)return null;let h;return p!==void 0&&p.length>0?h=p.split(",").map(g=>g.trim()).filter(g=>g.length>0):i.permissions!==void 0&&(h=i.permissions),{name:c,description:l,body:n,...u!==void 0?{version:u}:{},...d!==void 0?{origin:d}:{},...h!==void 0?{permissions:h}:{}}}function Lc(t){return{name:t.name,description:t.description,source:t.source}}function Ah(t){return t instanceof Error&&"code"in t}async function Ch(t=process.cwd()){let e=t;for(;;){try{return await Ih($c(e,".git")),e}catch{}let r=Mh(e);if(r===e)return;e=r}}async function et(){let t=ya({env:process.env});if(t.sessions.directory==="~/.vole/sessions"){let e=await Ch();e!==void 0&&(t.sessions.directory=$c(e,".vole","sessions"))}return t}var vo=new qs,xo=class{#e=new Map;resolve(e){return new Promise(r=>{this.#e.set(e.call.id,{request:e,resolve:r})})}settle(e,r){let s=this.#e.get(e);return s===void 0?!1:(this.#e.delete(e),s.resolve(r),!0)}pendingRequest(e){return this.#e.get(e)?.request}},wo,Ar=new Map,So=new Map;function Vt(t){if(wo===void 0){let e=ba(t,process.env);wo=new Fs({directory:e})}return wo}function Nh(t){return t.model.provider==="anthropic"?new Ls({...t.secrets.apiKey!==void 0?{apiKey:t.secrets.apiKey}:{},model:t.model.model,temperature:t.model.temperature,maxTokens:t.model.maxTokens,...t.model.thinkingBudget!==void 0?{thinkingBudget:t.model.thinkingBudget}:{}}):new Ns({baseURL:t.model.baseURL,...t.secrets.apiKey!==void 0?{apiKey:t.secrets.apiKey}:{},model:t.model.model,temperature:t.model.temperature,maxTokens:t.model.maxTokens})}async function jc(t,e){let r=Vt(t),s=new xo,n=new Ds,o=new Date().toISOString().slice(0,10),i=await new Ws().load({workspaceRoot:t.workspace.root}),a=i.map(Lc),c=new Map(i.map(b=>[b.name,b.filePath])),l=[yc(),_c(),vc(),Sc(t.runtime.sandboxed!==void 0?{sandboxed:t.runtime.sandboxed}:void 0),Ec()];(t.memory.longTermFiles==="read-only"||t.memory.longTermFiles==="write")&&(l.push(Pc(t.workspace.root)),l.push(Tc(t.workspace.root))),c.size>0&&l.push(Rc(c));let u=t.runtime.toolProfile!==void 0?ma(l,t.runtime.toolProfile):l,d=new Us({contextAssembler:new ns({workspacePromptFiles:["AGENTS.md","SOUL.md","TOOLS.md","IDENTITY.md","HEARTBEAT.md","BOOTSTRAP.md"]}),modelProvider:Nh(t),systemInstruction:"You are Vole, a personal general-purpose agent. You can use tools to read files, list directories, write files, run shell commands, and read web pages. You follow a permission policy that governs which actions require user approval.",runtime:{mode:t.runtime.defaultMode,workspace:t.workspace.root,currentDate:o},tools:u,skillIndex:a,preferStreaming:!0,approvalResolver:s,...t.runtime.promptMode!==void 0?{promptMode:t.runtime.promptMode}:{},...t.runtime.executionContract!==void 0?{executionContract:t.runtime.executionContract}:{}}),p;if(e!==void 0){if(await r.getSession(e)===void 0)throw new Error(`Session "${e}" not found in store.`);p=e}else p=(await r.createSession({title:`session_${crypto.randomUUID()}`})).id;let h={id:p,runtime:d,traceStore:n,approvalResolver:s};Ar.set(p,h);let g=new Date().toISOString();return vo.register({id:p,adapterName:"web",capabilities:pa,registeredAt:g,lastActivityAt:g}),h}var oe=new Cn;oe.use("/api/*",async(t,e)=>{await e(),t.res.headers.set("Access-Control-Allow-Origin","*"),t.res.headers.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),t.res.headers.set("Access-Control-Allow-Headers","Content-Type")});oe.options("/api/*",t=>t.text("",200));oe.post("/api/sessions",async t=>{let e;try{e=await et()}catch(n){return t.json({error:n instanceof Error?n.message:"Config error"},400)}let s=(await t.req.json().catch(()=>({sessionId:void 0}))).sessionId;try{let n=await jc(e,s);return t.json({sessionId:n.id})}catch(n){return t.json({error:n instanceof Error?n.message:"Failed to create session"},400)}});oe.get("/api/sessions",async t=>{let e;try{e=await et()}catch{return t.json({sessions:[]})}try{let n=(await Vt(e).listSessions()).map(o=>({id:o.id,title:o.title,createdAt:o.createdAt,updatedAt:o.updatedAt}));return t.json({sessions:n})}catch{return t.json({sessions:[]})}});oe.get("/api/sessions/:id",async t=>{let e;try{e=await et()}catch(s){return t.json({error:s instanceof Error?s.message:"Config error"},400)}let r=t.req.param("id");try{let n=await Vt(e).getSession(r);return n===void 0?t.json({error:"Session not found"},404):t.json({session:n})}catch(s){return t.json({error:s instanceof Error?s.message:"Store error"},500)}});oe.get("/api/sessions/:id/messages",async t=>{let e;try{e=await et()}catch(s){return t.json({error:s instanceof Error?s.message:"Config error"},400)}let r=t.req.param("id");try{let n=await Vt(e).listMessages(r);return t.json({messages:n})}catch(s){return t.json({error:s instanceof Error?s.message:"Store error"},500)}});oe.post("/api/sessions/:id/turns",async t=>{let e=t.req.param("id"),r=Ar.get(e);if(r===void 0){let d;try{d=await et()}catch(p){return t.json({error:p instanceof Error?p.message:"Config error"},400)}try{r=await jc(d,e)}catch{return t.json({error:"Session not found"},404)}}let s=r,o=(await t.req.json()).message?.trim()??"";if(o==="")return t.json({error:"Message is required"},400);let i;try{i=await et()}catch(d){return t.json({error:d instanceof Error?d.message:"Config error"},400)}if(i.secrets.apiKey===void 0)return t.json({error:"No API key configured. Add one to ~/.vole/config.json or set VOLE_API_KEY / ANTHROPIC_API_KEY / OPENROUTER_API_KEY in your shell."},400);let a=Vt(i),l=(await a.listMessages(e,{limit:12})).map(d=>({role:d.role,content:d.content})),u=new AbortController;return So.set(e,u),Ln(t,async d=>{let p="";try{for await(let h of s.runtime.runTurn({sessionId:e,recentMessages:l,message:o,signal:u.signal}))if(await s.traceStore.append(h),await a.appendTraceEvent({sessionId:e,event:h}),await d.writeSSE({event:h.type,data:JSON.stringify(h)}),h.type==="assistant_message_created"&&(p=h.message.content),h.type==="run_completed"||h.type==="run_failed")break}finally{So.delete(e)}u.signal.aborted||(await a.appendMessage({sessionId:e,role:"user",content:o}),p!==""&&await a.appendMessage({sessionId:e,role:"assistant",content:p})),vo.touch(e)})});oe.delete("/api/sessions/:id/turns",t=>{let e=t.req.param("id"),r=So.get(e);return r===void 0?t.json({ok:!1,reason:"no running turn"},404):(r.abort(),t.json({ok:!0}))});oe.get("/api/gateway/sessions",t=>t.json({sessions:vo.list()}));oe.post("/api/sessions/:id/approvals",async t=>{let e=t.req.param("id"),r=Ar.get(e);if(r===void 0)return t.json({error:"Session not found"},404);let s=await t.req.json(),n={approved:s.approved,reason:s.reason??(s.approved?"Approved.":"Denied.")};return r.approvalResolver.settle(s.callId,n)?t.json({success:!0}):t.json({error:"No pending approval with that callId"},404)});var Lh=Oh("./client")?"./client":"./dist/client";oe.use("/*",Uo({root:Lh}));var Bc=Number(process.env.PORT??3120);console.log(`Vole web server starting on http://localhost:${Bc}`);var $h=Lo({fetch:oe.fetch,port:Bc}),jh=new Sn.default({noServer:!0});$h.on("upgrade",(t,e,r)=>{let s=t.url??"",n=/^\/ws\/([^/?#]+)/.exec(s);if(n===null){e.destroy();return}jh.handleUpgrade(t,e,r,o=>{let i=n[1];if(Ar.get(i)===void 0){o.send(JSON.stringify({type:"error",message:"Session not found."})),o.close();return}o.send(JSON.stringify({type:"connected",sessionId:i})),o.on("message",c=>{(async()=>{let l=Ar.get(i);if(l===void 0){o.close();return}let u;try{u=JSON.parse(String(c))}catch{o.send(JSON.stringify({type:"error",message:"Invalid JSON."}));return}if(u.type==="turn"&&u.message!==void 0){let d=u.message,p;try{p=await et()}catch{o.send(JSON.stringify({type:"error",message:"Config error."}));return}let h=Vt(p),b=(await h.listMessages(i,{limit:12})).map(S=>({role:S.role,content:S.content}));for await(let S of l.runtime.runTurn({sessionId:i,recentMessages:b,message:d}))if(await l.traceStore.append(S),await h.appendTraceEvent({sessionId:i,event:S}),o.send(JSON.stringify(S)),S.type==="run_completed"||S.type==="run_failed")break;await h.appendMessage({sessionId:i,role:"user",content:d})}else u.type==="approval"&&u.callId!==void 0&&l.approvalResolver.settle(u.callId,{approved:u.approved??!1,reason:u.reason??(u.approved?"Approved.":"Denied.")})})()}),o.on("close",()=>{})})});
|