vole-agent 0.1.10 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -8
- package/README.zh-CN.md +35 -8
- package/dist/app.js +1 -1
- package/dist/chunk-OHRUXR5B.js +325 -0
- package/dist/index.js +1 -1
- package/dist/web/server.js +68 -31
- package/package.json +3 -1
- package/dist/chunk-EBLG3T72.js +0 -147
package/dist/web/server.js
CHANGED
|
@@ -1,46 +1,60 @@
|
|
|
1
1
|
import { createRequire } from "module"; const require = createRequire(import.meta.url);
|
|
2
|
-
var Fc=Object.create;var ko=Object.defineProperty;var qc=Object.getOwnPropertyDescriptor;var Hc=Object.getOwnPropertyNames;var Wc=Object.getPrototypeOf,Vc=Object.prototype.hasOwnProperty;var L=(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 Y=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Gc=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Hc(e))!Vc.call(t,n)&&n!==r&&ko(t,n,{get:()=>e[n],enumerable:!(s=qc(e,n))||s.enumerable});return t};var Se=(t,e,r)=>(r=t!=null?Fc(Wc(t)):{},Gc(e||!t||!t.__esModule?ko(r,"default",{value:t,enumerable:!0}):r,t));var de=Y((tp,Wo)=>{"use strict";var qo=["nodebuffer","arraybuffer","fragments"],Ho=typeof Blob<"u";Ho&&qo.push("blob");Wo.exports={BINARY_TYPES:qo,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ho,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Jt=Y((rp,Cr)=>{"use strict";var{EMPTY_BUFFER:kl}=de(),tn=Buffer[Symbol.species];function Rl(t,e){if(t.length===0)return kl;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 Vo(t,e,r,s,n){for(let o=0;o<n;o++)r[s+o]=t[o]^e[o&3]}function Go(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function Pl(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}Cr.exports={concat:Rl,mask:Vo,toArrayBuffer:Pl,toBuffer:rn,unmask:Go};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=L("bufferutil");Cr.exports.mask=function(e,r,s,n,o){o<48?Vo(e,r,s,n,o):t.mask(e,r,s,n,o)},Cr.exports.unmask=function(e,r){e.length<32?Go(e,r):t.unmask(e,r)}}catch{}});var Jo=Y((sp,zo)=>{"use strict";var Ko=Symbol("kDone"),sn=Symbol("kRun"),nn=class{constructor(e){this[Ko]=()=>{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[Ko])}}};zo.exports=nn});var at=Y((np,Zo)=>{"use strict";var Yt=L("zlib"),Yo=Jt(),Tl=Jo(),{kStatusCode:Xo}=de(),Al=Buffer[Symbol.species],Ol=Buffer.from([0,0,255,255]),Lr=Symbol("permessage-deflate"),fe=Symbol("total-length"),ot=Symbol("callback"),ve=Symbol("buffers"),it=Symbol("error"),Nr,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,!Nr){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Nr=new Tl(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){Nr.add(n=>{this._decompress(e,r,(o,i)=>{n(),s(o,i)})})}compress(e,r,s){Nr.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"?Yt.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=Yt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[Lr]=this,this._inflate[fe]=0,this._inflate[ve]=[],this._inflate.on("error",Ml),this._inflate.on("data",Qo)}this._inflate[ot]=s,this._inflate.write(e),r&&this._inflate.write(Ol),this._inflate.flush(()=>{let o=this._inflate[it];if(o){this._inflate.close(),this._inflate=null,s(o);return}let i=Yo.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"?Yt.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=Yt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[fe]=0,this._deflate[ve]=[],this._deflate.on("data",Il)}this._deflate[ot]=s,this._deflate.write(e),this._deflate.flush(Yt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=Yo.concat(this._deflate[ve],this._deflate[fe]);r&&(o=new Al(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)})}};Zo.exports=on;function Il(t){this[ve].push(t),this[fe]+=t.length}function Qo(t){if(this[fe]+=t.length,this[Lr]._maxPayload<1||this[fe]<=this[Lr]._maxPayload){this[ve].push(t);return}this[it]=new RangeError("Max payload size exceeded"),this[it].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[it][Xo]=1009,this.removeListener("data",Qo),this.reset()}function Ml(t){if(this[Lr]._inflate=null,this[it]){this[ot](this[it]);return}t[Xo]=1007,this[ot](t)}});var ct=Y((op,$r)=>{"use strict";var{isUtf8:ei}=L("buffer"),{hasBlob:Cl}=de(),Nl=[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 Ll(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 $l(t){return Cl&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}$r.exports={isBlob:$l,isValidStatusCode:Ll,isValidUTF8:an,tokenChars:Nl};if(ei)$r.exports.isValidUTF8=function(t){return t.length<24?an(t):ei(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=L("utf-8-validate");$r.exports.isValidUTF8=function(e){return e.length<32?an(e):t(e)}}catch{}});var fn=Y((ip,ai)=>{"use strict";var{Writable:jl}=L("stream"),ti=at(),{BINARY_TYPES:Bl,EMPTY_BUFFER:ri,kStatusCode:Dl,kWebSocket:Ul}=de(),{concat:cn,toArrayBuffer:Fl,unmask:ql}=Jt(),{isValidStatusCode:Hl,isValidUTF8:si}=ct(),jr=Buffer[Symbol.species],te=0,ni=1,oi=2,ii=3,ln=4,un=5,Br=6,dn=class extends jl{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Bl[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Ul]=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 jr(s.buffer,s.byteOffset+e,s.length-e),new jr(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 jr(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 ni:this.getPayloadLength16(e);break;case oi:this.getPayloadLength64(e);break;case ii:this.getMask();break;case ln:this.getData(e);break;case un:case Br: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[ti.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=ni:this._payloadLength===127?this._state=oi: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=ii:this._state=ln}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ln}getData(e){let r=ri;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&&ql(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[ti.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=Fl(cn(s,r)):this._binaryType==="blob"?n=new Blob(s):n=s,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=te):(this._state=Br,setImmediate(()=>{this.emit("message",n,!0),this._state=te,this.startLoop(e)}))}else{let n=cn(s,r);if(!this._skipUTF8Validation&&!si(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=Br,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,ri),this.end();else{let s=e.readUInt16BE(0);if(!Hl(s)){let o=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(o);return}let n=new jr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!si(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=Br,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[Dl]=n,i}};ai.exports=dn});var mn=Y((cp,ui)=>{"use strict";var{Duplex:ap}=L("stream"),{randomFillSync:Wl}=L("crypto"),ci=at(),{EMPTY_BUFFER:Vl,kWebSocket:Gl,NOOP:Kl}=de(),{isBlob:lt,isValidStatusCode:zl}=ct(),{mask:li,toBuffer:$e}=Jt(),re=Symbol("kByteLength"),Jl=Buffer.alloc(4),Dr=8*1024,je,ut=Dr,ae=0,Yl=1,Xl=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=Kl,this[Gl]=void 0}static frame(e,r){let s,n=!1,o=2,i=!1;r.mask&&(s=r.maskBuffer||Jl,r.generateMask?r.generateMask(s):(ut===Dr&&(je===void 0&&(je=Buffer.alloc(Dr)),Wl(je,0,Dr),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?(li(e,s,l,o,a),[l]):(li(e,s,e,0,a),[l,e])):[l,e]}close(e,r,s,n){let o;if(e===void 0)o=Vl;else{if(typeof e!="number"||!zl(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[ci.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=Xl,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(Ql,this,o,n)})}dispatch(e,r,s,n){if(!r){this.sendFrame(t.frame(e,s),n);return}let o=this._extensions[ci.extensionName];this._bufferedBytes+=s[re],this._state=Yl,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)}};ui.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 Ql(t,e,r){pn(t,e,r),t.onerror(e)}});var bi=Y((lp,_i)=>{"use strict";var{kForOnEventAttribute:Xt,kListener:gn}=de(),di=Symbol("kCode"),fi=Symbol("kData"),hi=Symbol("kError"),pi=Symbol("kMessage"),mi=Symbol("kReason"),dt=Symbol("kTarget"),gi=Symbol("kType"),yi=Symbol("kWasClean"),he=class{constructor(e){this[dt]=null,this[gi]=e}get target(){return this[dt]}get type(){return this[gi]}};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[di]=r.code===void 0?0:r.code,this[mi]=r.reason===void 0?"":r.reason,this[yi]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[di]}get reason(){return this[mi]}get wasClean(){return this[yi]}};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[hi]=r.error===void 0?null:r.error,this[pi]=r.message===void 0?"":r.message}get error(){return this[hi]}get message(){return this[pi]}};Object.defineProperty(ft.prototype,"error",{enumerable:!0});Object.defineProperty(ft.prototype,"message",{enumerable:!0});var Qt=class extends he{constructor(e,r={}){super(e),this[fi]=r.data===void 0?null:r.data}get data(){return this[fi]}};Object.defineProperty(Qt.prototype,"data",{enumerable:!0});var Zl={addEventListener(t,e,r={}){for(let n of this.listeners(t))if(!r[Xt]&&n[gn]===e&&!n[Xt])return;let s;if(t==="message")s=function(o,i){let a=new Qt("message",{data:i?o:o.toString()});a[dt]=this,Ur(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,Ur(e,this,a)};else if(t==="error")s=function(o){let i=new ft("error",{error:o,message:o.message});i[dt]=this,Ur(e,this,i)};else if(t==="open")s=function(){let o=new he("open");o[dt]=this,Ur(e,this,o)};else return;s[Xt]=!!r[Xt],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[Xt]){this.removeListener(t,r);break}}};_i.exports={CloseEvent:Be,ErrorEvent:ft,Event:he,EventTarget:Zl,MessageEvent:Qt};function Ur(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Fr=Y((up,wi)=>{"use strict";var{tokenChars:Zt}=ct();function ce(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function eu(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&&Zt[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&&Zt[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(Zt[l]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:s||(s=!0),n=!1}else if(o)if(Zt[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&&Zt[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 tu(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(", ")}wi.exports={format:tu,parse:eu}});var Vr=Y((hp,Mi)=>{"use strict";var ru=L("events"),su=L("https"),nu=L("http"),vi=L("net"),ou=L("tls"),{randomBytes:iu,createHash:au}=L("crypto"),{Duplex:dp,Readable:fp}=L("stream"),{URL:yn}=L("url"),Ee=at(),cu=fn(),lu=mn(),{isBlob:uu}=ct(),{BINARY_TYPES:xi,CLOSE_TIMEOUT:du,EMPTY_BUFFER:qr,GUID:fu,kForOnEventAttribute:_n,kListener:hu,kStatusCode:pu,kWebSocket:j,NOOP:Ei}=de(),{EventTarget:{addEventListener:mu,removeEventListener:gu}}=bi(),{format:yu,parse:_u}=Fr(),{toBuffer:bu}=Jt(),ki=Symbol("kAborted"),bn=[8,13],pe=["CONNECTING","OPEN","CLOSING","CLOSED"],wu=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,O=class t extends ru{constructor(e,r,s){super(),this._binaryType=xi[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]),Ri(this,e,r,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){xi.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 cu({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),o=new lu(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",vu),n.on("drain",Eu),n.on("error",ku),n.on("message",Ru),n.on("ping",Pu),n.on("pong",Tu),o.onerror=Au,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",Ai),e.on("data",Wr),e.on("end",Oi),e.on("error",Ii),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){X(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())}),Ti(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){X(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[hu];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=mu;O.prototype.removeEventListener=gu;Mi.exports=O;function Ri(t,e,r,s){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:du,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 y=new SyntaxError(c);if(t._redirects===0)throw y;Hr(t,y);return}let l=i?443:80,u=iu(16).toString("base64"),d=i?su.request:nu.request,p=new Set,h;if(n.createConnection=n.createConnection||(i?Su:xu),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"]=yu({[Ee.extensionName]:h.offer()})),r.length){for(let y of r){if(typeof y!="string"||!wu.test(y)||p.has(y))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(y)}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 y=n.path.split(":");n.socketPath=y[0],n.path=y[1]}let g;if(n.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=i,t._originalHostOrSocketPath=a?n.socketPath:o.host;let y=s&&s.headers;if(s={...s,headers:{}},y)for(let[x,E]of Object.entries(y))s.headers[x.toLowerCase()]=E}else if(t.listenerCount("redirect")===0){let y=a?t._originalIpc?n.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!y||t._originalSecure&&!i)&&(delete n.headers.authorization,delete n.headers.cookie,y||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",()=>{X(t,g,"Opening handshake has timed out")}),g.on("error",y=>{g===null||g[ki]||(g=t._req=null,Hr(t,y))}),g.on("response",y=>{let x=y.headers.location,E=y.statusCode;if(x&&n.followRedirects&&E>=300&&E<400){if(++t._redirects>n.maxRedirects){X(t,g,"Maximum redirects exceeded");return}g.abort();let k;try{k=new yn(x,e)}catch{let H=new SyntaxError(`Invalid URL: ${x}`);Hr(t,H);return}Ri(t,k,r,s)}else t.emit("unexpected-response",g,y)||X(t,g,`Unexpected server response: ${y.statusCode}`)}),g.on("upgrade",(y,x,E)=>{if(t.emit("upgrade",y),t.readyState!==O.CONNECTING)return;g=t._req=null;let k=y.headers.upgrade;if(k===void 0||k.toLowerCase()!=="websocket"){X(t,x,"Invalid Upgrade header");return}let R=au("sha1").update(u+fu).digest("base64");if(y.headers["sec-websocket-accept"]!==R){X(t,x,"Invalid Sec-WebSocket-Accept header");return}let H=y.headers["sec-websocket-protocol"],U;if(H!==void 0?p.size?p.has(H)||(U="Server sent an invalid subprotocol"):U="Server sent a subprotocol but none was requested":p.size&&(U="Server sent no subprotocol"),U){X(t,x,U);return}H&&(t._protocol=H);let W=y.headers["sec-websocket-extensions"];if(W!==void 0){if(!h){X(t,x,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let K;try{K=_u(W)}catch{X(t,x,"Invalid Sec-WebSocket-Extensions header");return}let S=Object.keys(K);if(S.length!==1||S[0]!==Ee.extensionName){X(t,x,"Server indicated an extension that was not requested");return}try{h.accept(K[Ee.extensionName])}catch{X(t,x,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Ee.extensionName]=h}t.setSocket(x,E,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(g,t):g.end()}function Hr(t,e){t._readyState=O.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function xu(t){return t.path=t.socketPath,vi.connect(t)}function Su(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=vi.isIP(t.host)?"":t.host),ou.connect(t)}function X(t,e,r){t._readyState=O.CLOSING;let s=new Error(r);Error.captureStackTrace(s,X),e.setHeader?(e[ki]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Hr,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=uu(e)?e.size:bu(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 vu(t,e){let r=this[j];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[j]!==void 0&&(r._socket.removeListener("data",Wr),process.nextTick(Pi,r._socket),t===1005?r.close():r.close(t,e))}function Eu(){let t=this[j];t.isPaused||t._socket.resume()}function ku(t){let e=this[j];e._socket[j]!==void 0&&(e._socket.removeListener("data",Wr),process.nextTick(Pi,e._socket),e.close(t[pu])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Si(){this[j].emitClose()}function Ru(t,e){this[j].emit("message",t,e)}function Pu(t){let e=this[j];e._autoPong&&e.pong(t,!this._isServer,Ei),e.emit("ping",t)}function Tu(t){this[j].emit("pong",t)}function Pi(t){t.resume()}function Au(t){let e=this[j];e.readyState!==O.CLOSED&&(e.readyState===O.OPEN&&(e._readyState=O.CLOSING,Ti(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Ti(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Ai(){let t=this[j];if(this.removeListener("close",Ai),this.removeListener("data",Wr),this.removeListener("end",Oi),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",Si),t._receiver.on("finish",Si))}function Wr(t){this[j]._receiver.write(t)||this.pause()}function Oi(){let t=this[j];t._readyState=O.CLOSING,t._receiver.end(),this.end()}function Ii(){let t=this[j];this.removeListener("error",Ii),this.on("error",Ei),t&&(t._readyState=O.CLOSING,this.destroy())}});var $i=Y((mp,Li)=>{"use strict";var pp=Vr(),{Duplex:Ou}=L("stream");function Ci(t){t.emit("close")}function Iu(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ni(t){this.removeListener("error",Ni),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Mu(t,e){let r=!0,s=new Ou({...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(Ci,s);return}let i=!1;t.once("error",function(c){i=!0,o(c)}),t.once("close",function(){i||o(n),process.nextTick(Ci,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",Iu),s.on("error",Ni),s}Li.exports=Mu});var xn=Y((gp,ji)=>{"use strict";var{tokenChars:Cu}=ct();function Nu(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&&Cu[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}ji.exports={parse:Nu}});var Wi=Y((_p,Hi)=>{"use strict";var Lu=L("events"),Gr=L("http"),{Duplex:yp}=L("stream"),{createHash:$u}=L("crypto"),Bi=Fr(),De=at(),ju=xn(),Bu=Vr(),{CLOSE_TIMEOUT:Du,GUID:Uu,kWebSocket:Fu}=de(),qu=/^[+/0-9A-Za-z]{22}==$/,Di=0,Ui=1,qi=2,Sn=class extends Lu{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Du,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Bu,...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=Gr.createServer((s,n)=>{let o=Gr.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=Hu(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=Di}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(er,this);return}if(e&&this.once("close",e),this._state!==Ui)if(this._state=Ui,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(er,this):process.nextTick(er,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{er(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",Fi);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||!qu.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)){tr(r,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=ju.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=Bi.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,y,x)=>{if(!h)return tr(r,g||401,y,x);this.completeUpgrade(d,o,l,e,r,s,n)});return}if(!this.options.verifyClient(p))return tr(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[Fu])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Di)return tr(o,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${$u("sha1").update(r+Uu).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=Bi.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 au=Object.create;var ni=Object.defineProperty;var cu=Object.getOwnPropertyDescriptor;var lu=Object.getOwnPropertyNames;var uu=Object.getPrototypeOf,du=Object.prototype.hasOwnProperty;var I=(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 O=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var fu=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of lu(e))!du.call(t,n)&&n!==r&&ni(t,n,{get:()=>e[n],enumerable:!(s=cu(e,n))||s.enumerable});return t};var de=(t,e,r)=>(r=t!=null?au(uu(t)):{},fu(e||!t||!t.__esModule?ni(r,"default",{value:t,enumerable:!0}):r,t));var ye=O((rg,xi)=>{"use strict";var Ei=["nodebuffer","arraybuffer","fragments"],Si=typeof Blob<"u";Si&&Ei.push("blob");xi.exports={BINARY_TYPES:Ei,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Si,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var or=O((sg,Gr)=>{"use strict";var{EMPTY_BUFFER:Vu}=ye(),vn=Buffer[Symbol.species];function Gu(t,e){if(t.length===0)return Vu;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 vn(r.buffer,r.byteOffset,s):r}function vi(t,e,r,s,n){for(let o=0;o<n;o++)r[s+o]=t[o]^e[o&3]}function ki(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function Ku(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function kn(t){if(kn.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new vn(t):ArrayBuffer.isView(t)?e=new vn(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),kn.readOnly=!1),e}Gr.exports={concat:Gu,mask:vi,toArrayBuffer:Ku,toBuffer:kn,unmask:ki};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=I("bufferutil");Gr.exports.mask=function(e,r,s,n,o){o<48?vi(e,r,s,n,o):t.mask(e,r,s,n,o)},Gr.exports.unmask=function(e,r){e.length<32?ki(e,r):t.unmask(e,r)}}catch{}});var Ai=O((ng,Ri)=>{"use strict";var Ti=Symbol("kDone"),Tn=Symbol("kRun"),Rn=class{constructor(e){this[Ti]=()=>{this.pending--,this[Tn]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Tn]()}[Tn](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ti])}}};Ri.exports=Rn});var gt=O((og,Mi)=>{"use strict";var ir=I("zlib"),Ii=or(),zu=Ai(),{kStatusCode:Pi}=ye(),Xu=Buffer[Symbol.species],Yu=Buffer.from([0,0,255,255]),zr=Symbol("permessage-deflate"),_e=Symbol("total-length"),pt=Symbol("callback"),Ie=Symbol("buffers"),mt=Symbol("error"),Kr,An=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,!Kr){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Kr=new zu(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[pt];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){Kr.add(n=>{this._decompress(e,r,(o,i)=>{n(),s(o,i)})})}compress(e,r,s){Kr.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"?ir.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=ir.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[zr]=this,this._inflate[_e]=0,this._inflate[Ie]=[],this._inflate.on("error",Qu),this._inflate.on("data",Oi)}this._inflate[pt]=s,this._inflate.write(e),r&&this._inflate.write(Yu),this._inflate.flush(()=>{let o=this._inflate[mt];if(o){this._inflate.close(),this._inflate=null,s(o);return}let i=Ii.concat(this._inflate[Ie],this._inflate[_e]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[_e]=0,this._inflate[Ie]=[],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"?ir.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=ir.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[_e]=0,this._deflate[Ie]=[],this._deflate.on("data",Ju)}this._deflate[pt]=s,this._deflate.write(e),this._deflate.flush(ir.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=Ii.concat(this._deflate[Ie],this._deflate[_e]);r&&(o=new Xu(o.buffer,o.byteOffset,o.length-4)),this._deflate[pt]=null,this._deflate[_e]=0,this._deflate[Ie]=[],r&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),s(null,o)})}};Mi.exports=An;function Ju(t){this[Ie].push(t),this[_e]+=t.length}function Oi(t){if(this[_e]+=t.length,this[zr]._maxPayload<1||this[_e]<=this[zr]._maxPayload){this[Ie].push(t);return}this[mt]=new RangeError("Max payload size exceeded"),this[mt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[mt][Pi]=1009,this.removeListener("data",Oi),this.reset()}function Qu(t){if(this[zr]._inflate=null,this[mt]){this[pt](this[mt]);return}t[Pi]=1007,this[pt](t)}});var yt=O((ig,Xr)=>{"use strict";var{isUtf8:Ci}=I("buffer"),{hasBlob:Zu}=ye(),ed=[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 td(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function In(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 rd(t){return Zu&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Xr.exports={isBlob:rd,isValidStatusCode:td,isValidUTF8:In,tokenChars:ed};if(Ci)Xr.exports.isValidUTF8=function(t){return t.length<24?In(t):Ci(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=I("utf-8-validate");Xr.exports.isValidUTF8=function(e){return e.length<32?In(e):t(e)}}catch{}});var Nn=O((ag,Ui)=>{"use strict";var{Writable:sd}=I("stream"),Ni=gt(),{BINARY_TYPES:nd,EMPTY_BUFFER:Li,kStatusCode:od,kWebSocket:id}=ye(),{concat:Pn,toArrayBuffer:ad,unmask:cd}=or(),{isValidStatusCode:ld,isValidUTF8:$i}=yt(),Yr=Buffer[Symbol.species],se=0,Di=1,ji=2,Bi=3,On=4,Mn=5,Jr=6,Cn=class extends sd{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||nd[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[id]=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=se}_write(e,r,s){if(this._opcode===8&&this._state==se)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 Yr(s.buffer,s.byteOffset+e,s.length-e),new Yr(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 Yr(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 se:this.getInfo(e);break;case Di:this.getPayloadLength16(e);break;case ji:this.getPayloadLength64(e);break;case Bi:this.getMask();break;case On:this.getData(e);break;case Mn: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[Ni.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=Di:this._payloadLength===127?this._state=ji: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=Bi:this._state=On}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=On}getData(e){let r=Li;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&&cd(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Mn,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[Ni.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===se&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=se;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=Pn(s,r):this._binaryType==="arraybuffer"?n=ad(Pn(s,r)):this._binaryType==="blob"?n=new Blob(s):n=s,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=se):(this._state=Jr,setImmediate(()=>{this.emit("message",n,!0),this._state=se,this.startLoop(e)}))}else{let n=Pn(s,r);if(!this._skipUTF8Validation&&!$i(n)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===Mn||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=se):(this._state=Jr,setImmediate(()=>{this.emit("message",n,!1),this._state=se,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Li),this.end();else{let s=e.readUInt16BE(0);if(!ld(s)){let o=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(o);return}let n=new Yr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!$i(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=se;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=se):(this._state=Jr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=se,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[od]=n,i}};Ui.exports=Cn});var Dn=O((lg,Hi)=>{"use strict";var{Duplex:cg}=I("stream"),{randomFillSync:ud}=I("crypto"),Fi=gt(),{EMPTY_BUFFER:dd,kWebSocket:fd,NOOP:hd}=ye(),{isBlob:_t,isValidStatusCode:pd}=yt(),{mask:qi,toBuffer:qe}=or(),ne=Symbol("kByteLength"),md=Buffer.alloc(4),Qr=8*1024,He,bt=Qr,le=0,gd=1,yd=2,Ln=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=le,this.onerror=hd,this[fd]=void 0}static frame(e,r){let s,n=!1,o=2,i=!1;r.mask&&(s=r.maskBuffer||md,r.generateMask?r.generateMask(s):(bt===Qr&&(He===void 0&&(He=Buffer.alloc(Qr)),ud(He,0,Qr),bt=0),s[0]=He[bt++],s[1]=He[bt++],s[2]=He[bt++],s[3]=He[bt++]),i=(s[0]|s[1]|s[2]|s[3])===0,o=6);let a;typeof e=="string"?(!r.mask||i)&&r[ne]!==void 0?a=r[ne]:(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?(qi(e,s,l,o,a),[l]):(qi(e,s,e,0,a),[l,e])):[l,e]}close(e,r,s,n){let o;if(e===void 0)o=dd;else{if(typeof e!="number"||!pd(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={[ne]:o.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==le?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):_t(e)?(n=e.size,o=!1):(e=qe(e),n=e.length,o=qe.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[ne]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};_t(e)?this._state!==le?this.enqueue([this.getBlobData,e,!1,i,s]):this.getBlobData(e,!1,i,s):this._state!==le?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):_t(e)?(n=e.size,o=!1):(e=qe(e),n=e.length,o=qe.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[ne]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};_t(e)?this._state!==le?this.enqueue([this.getBlobData,e,!1,i,s]):this.getBlobData(e,!1,i,s):this._state!==le?this.enqueue([this.dispatch,e,!1,i,s]):this.sendFrame(t.frame(e,i),s)}send(e,r,s){let n=this._extensions[Fi.extensionName],o=r.binary?2:1,i=r.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):_t(e)?(a=e.size,c=!1):(e=qe(e),a=e.length,c=qe.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={[ne]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:i};_t(e)?this._state!==le?this.enqueue([this.getBlobData,e,this._compress,l,s]):this.getBlobData(e,this._compress,l,s):this._state!==le?this.enqueue([this.dispatch,e,this._compress,l,s]):this.dispatch(e,this._compress,l,s)}getBlobData(e,r,s,n){this._bufferedBytes+=s[ne],this._state=yd,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick($n,this,a,n);return}this._bufferedBytes-=s[ne];let i=qe(o);r?this.dispatch(i,r,s,n):(this._state=le,this.sendFrame(t.frame(i,s),n),this.dequeue())}).catch(o=>{process.nextTick(_d,this,o,n)})}dispatch(e,r,s,n){if(!r){this.sendFrame(t.frame(e,s),n);return}let o=this._extensions[Fi.extensionName];this._bufferedBytes+=s[ne],this._state=gd,o.compress(e,s.fin,(i,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");$n(this,c,n);return}this._bufferedBytes-=s[ne],this._state=le,s.readOnly=!1,this.sendFrame(t.frame(a,s),n),this.dequeue()})}dequeue(){for(;this._state===le&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][ne],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ne],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)}};Hi.exports=Ln;function $n(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 _d(t,e,r){$n(t,e,r),t.onerror(e)}});var Qi=O((ug,Ji)=>{"use strict";var{kForOnEventAttribute:ar,kListener:jn}=ye(),Wi=Symbol("kCode"),Vi=Symbol("kData"),Gi=Symbol("kError"),Ki=Symbol("kMessage"),zi=Symbol("kReason"),wt=Symbol("kTarget"),Xi=Symbol("kType"),Yi=Symbol("kWasClean"),be=class{constructor(e){this[wt]=null,this[Xi]=e}get target(){return this[wt]}get type(){return this[Xi]}};Object.defineProperty(be.prototype,"target",{enumerable:!0});Object.defineProperty(be.prototype,"type",{enumerable:!0});var We=class extends be{constructor(e,r={}){super(e),this[Wi]=r.code===void 0?0:r.code,this[zi]=r.reason===void 0?"":r.reason,this[Yi]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Wi]}get reason(){return this[zi]}get wasClean(){return this[Yi]}};Object.defineProperty(We.prototype,"code",{enumerable:!0});Object.defineProperty(We.prototype,"reason",{enumerable:!0});Object.defineProperty(We.prototype,"wasClean",{enumerable:!0});var Et=class extends be{constructor(e,r={}){super(e),this[Gi]=r.error===void 0?null:r.error,this[Ki]=r.message===void 0?"":r.message}get error(){return this[Gi]}get message(){return this[Ki]}};Object.defineProperty(Et.prototype,"error",{enumerable:!0});Object.defineProperty(Et.prototype,"message",{enumerable:!0});var cr=class extends be{constructor(e,r={}){super(e),this[Vi]=r.data===void 0?null:r.data}get data(){return this[Vi]}};Object.defineProperty(cr.prototype,"data",{enumerable:!0});var bd={addEventListener(t,e,r={}){for(let n of this.listeners(t))if(!r[ar]&&n[jn]===e&&!n[ar])return;let s;if(t==="message")s=function(o,i){let a=new cr("message",{data:i?o:o.toString()});a[wt]=this,Zr(e,this,a)};else if(t==="close")s=function(o,i){let a=new We("close",{code:o,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[wt]=this,Zr(e,this,a)};else if(t==="error")s=function(o){let i=new Et("error",{error:o,message:o.message});i[wt]=this,Zr(e,this,i)};else if(t==="open")s=function(){let o=new be("open");o[wt]=this,Zr(e,this,o)};else return;s[ar]=!!r[ar],s[jn]=e,r.once?this.once(t,s):this.on(t,s)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[jn]===e&&!r[ar]){this.removeListener(t,r);break}}};Ji.exports={CloseEvent:We,ErrorEvent:Et,Event:be,EventTarget:bd,MessageEvent:cr};function Zr(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var es=O((dg,Zi)=>{"use strict";var{tokenChars:lr}=yt();function fe(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function wd(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&&lr[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?(fe(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&&lr[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),fe(r,t.slice(c,u),!0),l===44&&(fe(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(lr[l]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:s||(s=!0),n=!1}else if(o)if(lr[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&&lr[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),fe(r,a,h),l===44&&(fe(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?fe(e,p,r):(a===void 0?fe(r,p,!0):s?fe(r,a,p.replace(/\\/g,"")):fe(r,a,p),fe(e,i,r)),e}function Ed(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(", ")}Zi.exports={format:Ed,parse:wd}});var ns=O((pg,da)=>{"use strict";var Sd=I("events"),xd=I("https"),vd=I("http"),ra=I("net"),kd=I("tls"),{randomBytes:Td,createHash:Rd}=I("crypto"),{Duplex:fg,Readable:hg}=I("stream"),{URL:Bn}=I("url"),Pe=gt(),Ad=Nn(),Id=Dn(),{isBlob:Pd}=yt(),{BINARY_TYPES:ea,CLOSE_TIMEOUT:Od,EMPTY_BUFFER:ts,GUID:Md,kForOnEventAttribute:Un,kListener:Cd,kStatusCode:Nd,kWebSocket:q,NOOP:sa}=ye(),{EventTarget:{addEventListener:Ld,removeEventListener:$d}}=Qi(),{format:Dd,parse:jd}=es(),{toBuffer:Bd}=or(),na=Symbol("kAborted"),Fn=[8,13],we=["CONNECTING","OPEN","CLOSING","CLOSED"],Ud=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,N=class t extends Sd{constructor(e,r,s){super(),this._binaryType=ea[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ts,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]),oa(this,e,r,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ea.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 Ad({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),o=new Id(e,this._extensions,s.generateMask);this._receiver=n,this._sender=o,this._socket=e,n[q]=this,o[q]=this,e[q]=this,n.on("conclude",Hd),n.on("drain",Wd),n.on("error",Vd),n.on("message",Gd),n.on("ping",Kd),n.on("pong",zd),o.onerror=Xd,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",ca),e.on("data",ss),e.on("end",la),e.on("error",ua),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[Pe.extensionName]&&this._extensions[Pe.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){Z(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())}),aa(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){qn(this,e,s);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||ts,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){qn(this,e,s);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||ts,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){qn(this,e,s);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Pe.extensionName]||(n.compress=!1),this._sender.send(e||ts,n,s)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Z(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(N,"CONNECTING",{enumerable:!0,value:we.indexOf("CONNECTING")});Object.defineProperty(N.prototype,"CONNECTING",{enumerable:!0,value:we.indexOf("CONNECTING")});Object.defineProperty(N,"OPEN",{enumerable:!0,value:we.indexOf("OPEN")});Object.defineProperty(N.prototype,"OPEN",{enumerable:!0,value:we.indexOf("OPEN")});Object.defineProperty(N,"CLOSING",{enumerable:!0,value:we.indexOf("CLOSING")});Object.defineProperty(N.prototype,"CLOSING",{enumerable:!0,value:we.indexOf("CLOSING")});Object.defineProperty(N,"CLOSED",{enumerable:!0,value:we.indexOf("CLOSED")});Object.defineProperty(N.prototype,"CLOSED",{enumerable:!0,value:we.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(N.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(N.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Un])return e[Cd];return null},set(e){for(let r of this.listeners(t))if(r[Un]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Un]:!0})}})});N.prototype.addEventListener=Ld;N.prototype.removeEventListener=$d;da.exports=N;function oa(t,e,r,s){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Od,protocolVersion:Fn[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,!Fn.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${Fn.join(", ")})`);let o;if(e instanceof Bn)o=e;else try{o=new Bn(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 y=new SyntaxError(c);if(t._redirects===0)throw y;rs(t,y);return}let l=i?443:80,u=Td(16).toString("base64"),d=i?xd.request:vd.request,p=new Set,h;if(n.createConnection=n.createConnection||(i?qd:Fd),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 Pe({...n.perMessageDeflate,isServer:!1,maxPayload:n.maxPayload}),n.headers["Sec-WebSocket-Extensions"]=Dd({[Pe.extensionName]:h.offer()})),r.length){for(let y of r){if(typeof y!="string"||!Ud.test(y)||p.has(y))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(y)}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 y=n.path.split(":");n.socketPath=y[0],n.path=y[1]}let g;if(n.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=i,t._originalHostOrSocketPath=a?n.socketPath:o.host;let y=s&&s.headers;if(s={...s,headers:{}},y)for(let[w,k]of Object.entries(y))s.headers[w.toLowerCase()]=k}else if(t.listenerCount("redirect")===0){let y=a?t._originalIpc?n.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!y||t._originalSecure&&!i)&&(delete n.headers.authorization,delete n.headers.cookie,y||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",()=>{Z(t,g,"Opening handshake has timed out")}),g.on("error",y=>{g===null||g[na]||(g=t._req=null,rs(t,y))}),g.on("response",y=>{let w=y.headers.location,k=y.statusCode;if(w&&n.followRedirects&&k>=300&&k<400){if(++t._redirects>n.maxRedirects){Z(t,g,"Maximum redirects exceeded");return}g.abort();let A;try{A=new Bn(w,e)}catch{let v=new SyntaxError(`Invalid URL: ${w}`);rs(t,v);return}oa(t,A,r,s)}else t.emit("unexpected-response",g,y)||Z(t,g,`Unexpected server response: ${y.statusCode}`)}),g.on("upgrade",(y,w,k)=>{if(t.emit("upgrade",y),t.readyState!==N.CONNECTING)return;g=t._req=null;let A=y.headers.upgrade;if(A===void 0||A.toLowerCase()!=="websocket"){Z(t,w,"Invalid Upgrade header");return}let x=Rd("sha1").update(u+Md).digest("base64");if(y.headers["sec-websocket-accept"]!==x){Z(t,w,"Invalid Sec-WebSocket-Accept header");return}let v=y.headers["sec-websocket-protocol"],C;if(v!==void 0?p.size?p.has(v)||(C="Server sent an invalid subprotocol"):C="Server sent a subprotocol but none was requested":p.size&&(C="Server sent no subprotocol"),C){Z(t,w,C);return}v&&(t._protocol=v);let M=y.headers["sec-websocket-extensions"];if(M!==void 0){if(!h){Z(t,w,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let j;try{j=jd(M)}catch{Z(t,w,"Invalid Sec-WebSocket-Extensions header");return}let Y=Object.keys(j);if(Y.length!==1||Y[0]!==Pe.extensionName){Z(t,w,"Server indicated an extension that was not requested");return}try{h.accept(j[Pe.extensionName])}catch{Z(t,w,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Pe.extensionName]=h}t.setSocket(w,k,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(g,t):g.end()}function rs(t,e){t._readyState=N.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Fd(t){return t.path=t.socketPath,ra.connect(t)}function qd(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=ra.isIP(t.host)?"":t.host),kd.connect(t)}function Z(t,e,r){t._readyState=N.CLOSING;let s=new Error(r);Error.captureStackTrace(s,Z),e.setHeader?(e[na]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(rs,t,s)):(e.destroy(s),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function qn(t,e,r){if(e){let s=Pd(e)?e.size:Bd(e).length;t._socket?t._sender._bufferedBytes+=s:t._bufferedAmount+=s}if(r){let s=new Error(`WebSocket is not open: readyState ${t.readyState} (${we[t.readyState]})`);process.nextTick(r,s)}}function Hd(t,e){let r=this[q];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[q]!==void 0&&(r._socket.removeListener("data",ss),process.nextTick(ia,r._socket),t===1005?r.close():r.close(t,e))}function Wd(){let t=this[q];t.isPaused||t._socket.resume()}function Vd(t){let e=this[q];e._socket[q]!==void 0&&(e._socket.removeListener("data",ss),process.nextTick(ia,e._socket),e.close(t[Nd])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function ta(){this[q].emitClose()}function Gd(t,e){this[q].emit("message",t,e)}function Kd(t){let e=this[q];e._autoPong&&e.pong(t,!this._isServer,sa),e.emit("ping",t)}function zd(t){this[q].emit("pong",t)}function ia(t){t.resume()}function Xd(t){let e=this[q];e.readyState!==N.CLOSED&&(e.readyState===N.OPEN&&(e._readyState=N.CLOSING,aa(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function aa(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function ca(){let t=this[q];if(this.removeListener("close",ca),this.removeListener("data",ss),this.removeListener("end",la),t._readyState=N.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[q]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",ta),t._receiver.on("finish",ta))}function ss(t){this[q]._receiver.write(t)||this.pause()}function la(){let t=this[q];t._readyState=N.CLOSING,t._receiver.end(),this.end()}function ua(){let t=this[q];this.removeListener("error",ua),this.on("error",sa),t&&(t._readyState=N.CLOSING,this.destroy())}});var ma=O((gg,pa)=>{"use strict";var mg=ns(),{Duplex:Yd}=I("stream");function fa(t){t.emit("close")}function Jd(){!this.destroyed&&this._writableState.finished&&this.destroy()}function ha(t){this.removeListener("error",ha),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Qd(t,e){let r=!0,s=new Yd({...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(fa,s);return}let i=!1;t.once("error",function(c){i=!0,o(c)}),t.once("close",function(){i||o(n),process.nextTick(fa,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",Jd),s.on("error",ha),s}pa.exports=Qd});var Hn=O((yg,ga)=>{"use strict";var{tokenChars:Zd}=yt();function ef(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&&Zd[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}ga.exports={parse:ef}});var xa=O((bg,Sa)=>{"use strict";var tf=I("events"),os=I("http"),{Duplex:_g}=I("stream"),{createHash:rf}=I("crypto"),ya=es(),Ve=gt(),sf=Hn(),nf=ns(),{CLOSE_TIMEOUT:of,GUID:af,kWebSocket:cf}=ye(),lf=/^[+/0-9A-Za-z]{22}==$/,_a=0,ba=1,Ea=2,Wn=class extends tf{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:of,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:nf,...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=os.createServer((s,n)=>{let o=os.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=uf(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=_a}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===Ea){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ur,this);return}if(e&&this.once("close",e),this._state!==ba)if(this._state=ba,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(ur,this):process.nextTick(ur,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{ur(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",wa);let o=e.headers["sec-websocket-key"],i=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ge(this,e,r,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){Ge(this,e,r,400,"Invalid Upgrade header");return}if(o===void 0||!lf.test(o)){Ge(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Ge(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){dr(r,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=sf.parse(c)}catch{Ge(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 Ve({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=ya.parse(u);h[Ve.extensionName]&&(p.accept(h[Ve.extensionName]),d[Ve.extensionName]=p)}catch{Ge(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,y,w)=>{if(!h)return dr(r,g||401,y,w);this.completeUpgrade(d,o,l,e,r,s,n)});return}if(!this.options.verifyClient(p))return dr(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[cf])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>_a)return dr(o,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${rf("sha1").update(r+af).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[Ve.extensionName]){let d=e[Ve.extensionName].params,p=ya.format({[Ve.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",
|
|
4
|
+
`)),o.removeListener("error",wa),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(ur,this)})),a(u,n)}};Sa.exports=Wn;function uf(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 ur(t){t._state=Ea,t.emit("close")}function wa(){this.destroy()}function dr(t,e,r,s){r=r||os.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} ${os.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 tr(r,s,n,o)}});import{existsSync as Ih}from"fs";import{stat as Mh}from"fs/promises";import{dirname as Ch,join as Bc}from"path";import{createServer as Kc}from"http";import{Http2ServerRequest as To,constants as zc}from"http2";import{Http2ServerRequest as Gs}from"http2";import{Readable as Ro}from"stream";import ol from"crypto";var Ne=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},Jc=t=>t instanceof Ne?t:new Ne(t.message,{cause:t}),Yc=global.Request,Kt=class extends Yc{constructor(t,e){typeof t=="object"&&st in t&&(t=t[st]()),typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},Xc=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"),Qc=(t,e,r,s,n)=>{let o={method:t,headers:r,signal:n.signal};if(t==="TRACE"){o.method="GET";let i=new Kt(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 Kt(e,o)},st=Symbol("getRequestCache"),Oo=Symbol("requestCache"),Ir=Symbol("incomingKey"),Mr=Symbol("urlKey"),Zc=Symbol("headersKey"),rt=Symbol("abortControllerKey"),el=Symbol("getAbortController"),zt={get method(){return this[Ir].method||"GET"},get url(){return this[Mr]},get headers(){return this[Zc]||=Xc(this[Ir])},[el](){return this[st](),this[rt]},[st](){return this[rt]||=new AbortController,this[Oo]||=Qc(this.method,this[Mr],this.headers,this[Ir],this[rt])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(t=>{Object.defineProperty(zt,t,{get(){return this[st]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(zt,t,{value:function(){return this[st]()[t]()}})});Object.defineProperty(zt,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(zt,Kt.prototype);var tl=(t,e)=>{let r=Object.create(zt);r[Ir]=t;let s=t.url||"";if(s[0]!=="/"&&(s.startsWith("http://")||s.startsWith("https://"))){if(t instanceof Gs)throw new Ne("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(s);r[Mr]=a.href}catch(a){throw new Ne("Invalid absolute URL",{cause:a})}return r}let n=(t instanceof Gs?t.authority:t.headers.host)||e;if(!n)throw new Ne("Missing host header");let o;if(t instanceof Gs){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[Mr]=i.href,r},zs=Symbol("responseCache"),tt=Symbol("getResponseCache"),Le=Symbol("cache"),Xs=global.Response,nt=class Io{#e;#t;[tt](){return delete this[Le],this[zs]||=new Xs(this.#e,this.#t)}constructor(e,r){let s;if(this.#e=e,r instanceof Io){let n=r[zs];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[zs]};return`Response (lightweight) ${r(s,{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(nt,Xs);Object.setPrototypeOf(nt.prototype,Xs.prototype);async function rl(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 sl(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:Mo(t.getReader(),e)}var Js=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},nl="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=ol);var Qs=Symbol("outgoingEnded"),Po=Symbol("incomingDraining"),il=500,al=64*1024*1024,Ks=t=>{let e=t;if(t.destroyed||e[Po])return;if(e[Po]=!0,t instanceof To){try{t.stream?.close?.(zc.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,il);o.unref?.();let i=a=>{r+=a.length,r>al&&n()};t.on("data",i),t.on("end",s),t.on("error",s),t.resume()},cl=()=>new Response(null,{status:400}),Co=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),Ys=(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=Js(n);else if(Array.isArray(n)){let i=new Headers(n);o=i.has("content-length"),n=Js(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 sl(s,e)?.catch(i=>Ys(i,e))),e[Qs]?.()},ll=t=>typeof t.then=="function",ul=async(t,e,r={})=>{if(ll(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=Js(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 rl(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[nl]||(e.writeHead(t.status,s),e.end());e[Qs]?.()},dl=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==Kt&&(Object.defineProperty(global,"Request",{value:Kt}),Object.defineProperty(global,"Response",{value:nt})),async(s,n)=>{let o,i;try{i=tl(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[Qs]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{Ks(s)})})}),n.on("finish",()=>{a||Ks(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(()=>{Ks(s)})})}),o=t(i,{incoming:s,outgoing:n}),Le in o)return Lo(o,n)}catch(a){if(o)return Ys(a,n);if(e.errorHandler){if(o=await e.errorHandler(i?a:Jc(a)),!o)return}else i?o=Co(a):o=cl()}try{return await ul(o,n,e)}catch(a){return Ys(a,n)}}},fl=t=>{let e=t.fetch,r=dl(e,{hostname:t.hostname,overrideGlobalObjects:t.overrideGlobalObjects,autoCleanupIncoming:t.autoCleanupIncoming});return(t.createServer||Kc)(t.serverOptions||{},r)},$o=(t,e)=>{let r=fl(t);return r.listen(t?.port??3e3,t.hostname,()=>{let s=r.address();e&&e(s)}),r};var jo=(t,e=pl)=>{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 hl={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"},pl=hl;import{createReadStream as Bo,statSync as ml,existsSync as gl}from"fs";import{join as Do}from"path";import{versions as yl}from"process";import{Readable as _l}from"stream";var bl=/^\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,en={br:".br",zstd:".zst",gzip:".gz"},wl=Object.keys(en),xl=()=>{let[t,e]=yl.node.split(".").map(r=>parseInt(r));return t>=23||t===22&&e>=7||t===20&&e>=18},Sl=xl(),Uo=t=>Sl?_l.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()}}),Zs=t=>{let e;try{e=ml(t)}catch{}return e},vl=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},El=t=>vl(t,decodeURI),Fo=(t={root:""})=>{let e=t.root||"",r=t.path;return e!==""&&!gl(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=El(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=Zs(i);if(a&&a.isDirectory()){let p=t.index??"index.html";i=Do(i,p),a=Zs(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||bl.test(c))){let p=new Set(s.req.header("Accept-Encoding")?.split(",").map(h=>h.trim()));for(let h of wl){if(!p.has(h))continue;let g=Zs(i+en[h]);if(g){s.header("Content-Encoding",h),s.header("Vary","Accept-Encoding",{append:!0}),a=g,i=i+en[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 y=g-h+1,x=Bo(i,{start:h,end:g});s.header("Content-Length",y.toString()),s.header("Content-Range",`bytes ${h}-${g}/${a.size}`),l=s.body(Uo(x),206)}return await t.onFound?.(i,s),l}};var Wu=Se($i(),1),Vu=Se(Fr(),1),Gu=Se(at(),1),Ku=Se(fn(),1),zu=Se(mn(),1),Ju=Se(xn(),1),Yu=Se(Vr(),1),vn=Se(Wi(),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 Vi=Symbol();var Gi=async(t,e=Object.create(null))=>{let{all:r=!1,dot:s=!1}=e,o=(t instanceof Kr?t.raw.headers:t.headers).get("Content-Type");return o?.startsWith("multipart/form-data")||o?.startsWith("application/x-www-form-urlencoded")?Xu(t,{all:r,dot:s}):{}};async function Xu(t,e){let r=await t.formData();return r?Qu(r,e):{}}function Qu(t,e){let r=Object.create(null);return t.forEach((s,n)=>{e.all||n.endsWith("[]")?Zu(r,n,s):r[n]=s}),e.dot&&Object.entries(r).forEach(([s,n])=>{s.includes(".")&&(ed(r,s,n),delete r[s])}),r}var Zu=(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},ed=(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},Ki=t=>{let{groups:e,path:r}=td(t),s=Rn(r);return rd(s,e)},td=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,s)=>{let n=`@${s}`;return e.push([n,r]),n}),{groups:e,path:t}},rd=(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},zr={},zi=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let s=`${t}#${e}`;return zr[s]||(r[2]?zr[s]=e&&e[0]!==":"&&e[0]!=="*"?[s,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:zr[s]=[t,r[1],!0]),zr[s]}return null},Jr=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},sd=t=>Jr(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 sd(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(n===63||n===35)break}return e.slice(r,s)};var Ji=t=>{let e=Pn(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},Fe=(t,e,...r)=>(r.length&&(e=Fe(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),Yr=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?Jr(t,Tn):t):t,Yi=(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},Xi=Yi,Qi=(t,e)=>Yi(t,e,!0),Tn=decodeURIComponent;var Zi=t=>Jr(t,Tn),Kr=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)?Zi(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)?Zi(s):s)}return t}#r(t){return this.#t[1]?this.#t[1][t]:t}query(t){return Xi(this.url,t)}queries(t){return Qi(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 Gi(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[Vi](){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 Xr={Stringify:1,BeforeStream:2,Stream:3},nd=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r};var rr=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=>rr(c,e,!1,s,n))).then(()=>n[0]));return r?nd(await i,o):i};var ea="text/plain; charset=UTF-8",An=(t,e)=>({"Content-Type":t,...e}),sr=(t,e)=>new Response(t,e),ta=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 Kr(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||=sr(null,{headers:this.#c??=new Headers})}set res(t){if(this.#n&&t){t=sr(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=sr(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 sr(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(ea,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"?rr(t,Xr.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??=()=>sr(),this.#h(this))};var I="ALL",ra="all",sa=["get","post","put","delete","options","patch"],Qr="Can not add a route since the matcher is already built.",Zr=class extends Error{};var na="__COMPOSED_HANDLER";var od=t=>t.text("404 Not Found",404),oa=(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)},ia=class aa{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(e={}){[...sa,ra].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:Ji}#t(){let e=new aa({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#s=this.#s,e.routes=this.routes,e}#s=od;errorHandler=oa;route(e,r){let s=this.basePath(e);return r.routes.map(n=>{let o;r.errorHandler===oa?o=n.handler:(o=async(i,a)=>(await En([],r.errorHandler)(i,()=>n.handler(i,a))).res,o[na]=n.handler),s.#o(n.method,n.path,o)}),this}basePath(e){let r=this.#t();return r._basePath=Fe(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=Fe(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,Fe(e,"*"),a),this}#o(e,r,s){e=e.toUpperCase(),r=Fe(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 ta(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${Fe("/",e)}`,r),s,n));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#n(e.request,e,void 0,e.request.method))})}};var es=[];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[[],es];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=s,s(t,e)}var ts="[^/]+",nr=".*",or="(?:|/.*)",qe=Symbol(),id=new Set(".\\+*[^]$()");function ad(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===nr||t===or?1:e===nr||e===or?-1:t===ts?1:e===ts?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var ca=class In{#e;#t;#s=Object.create(null);insert(e,r,s,n,o){if(e.length===0){if(this.#e!==void 0)throw qe;if(o)return;this.#e=r;return}let[i,...a]=e,c=i==="*"?a.length===0?["","",nr]:["","",ts]:i==="/*"?["","",or]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],d=c[2]||ts;if(u&&c[2]&&(d===".*"||(d=d.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(d))))throw qe;if(l=this.#s[d],!l){if(Object.keys(this.#s).some(p=>p!==nr&&p!==or))throw qe;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!==nr&&u!==or))throw qe;if(o)return;l=this.#s[i]=new In}l.insert(a,r,s,n,o)}buildRegExpStr(){let r=Object.keys(this.#s).sort(ad).map(s=>{let n=this.#s[s];return(typeof n.#t=="number"?`(${s})@${n.#t}`:id.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 la=class{#e={varIndex:0};#t=new ca;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 cd=[/^$/,[],Object.create(null)],ua=Object.create(null);function da(t){return ua[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function ld(){ua=Object.create(null)}function ud(t){let e=new la,r=[];if(t.length===0)return cd;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(([x])=>[x,Object.create(null)]),es]:u++;let y;try{y=e.insert(h,u,p)}catch(x){throw x===qe?new Zr(h):x}p||(r[u]=g.map(([x,E])=>{let k=Object.create(null);for(E-=1;E>=0;E--){let[R,H]=y[E];k[R]=H}return[x,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 y=0,x=g.length;y<x;y++)h[g[y]]=a[h[g[y]]]}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(da(r).test(e))return[...t[r]]}}var rs=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(Qr);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=da(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=Yr(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,ld(),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?ud(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(Qr);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 Zr)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 ir=Object.create(null),dd=t=>{for(let e in t)return!0;return!1},fa=class ha{#e;#t;#s;#o=0;#r=ir;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=Ki(r),i=[];for(let a=0,c=o.length;a<c;a++){let l=o[a],u=o[a+1],d=zi(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 ha,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!==ir||o&&o!==ir))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=ir;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 y=0,x=o.length;y<x;y++){let E=o[y],k=E.#t[d];k&&(k.#r=E.#r,p?(k.#t["*"]&&this.#n(s,k.#t["*"],e,E.#r),this.#n(s,k,e,E.#r)):h.push(k));for(let R=0,H=E.#s.length;R<H;R++){let U=E.#s[R],W=E.#r===ir?{}:{...E.#r};if(U==="*"){let N=E.#t["*"];N&&(this.#n(s,N,e,E.#r),N.#r=W,h.push(N));continue}let[K,S,C]=U;if(!d&&!(C instanceof RegExp))continue;let T=E.#t[K];if(C instanceof RegExp){if(l===null){l=new Array(c);let P=r[0]==="/"?1:0;for(let G=0;G<c;G++)l[G]=P,P+=i[G].length+1}let N=r.substring(l[u]),V=C.exec(N);if(V){if(W[S]=V[0],this.#n(s,T,e,E.#r,W),dd(T.#t)){T.#r=W;let P=V[0].match(/\//)?.length??0;(a[P]||=[]).push(T)}continue}}(C===!0||C.test(d))&&(W[S]=d,p?(this.#n(s,T,e,W,E.#r),T.#t["*"]&&this.#n(s,T.#t["*"],e,W,E.#r)):(T.#r=W,h.push(T)))}}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 fa}add(t,e,r){let s=Yr(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 ia{constructor(t={}){super(t),this.router=t.router??new Mn({routers:[new rs,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
|
-
|
|
8
|
+
`+r)}function Ge(t,e,r,s,n,o){if(t.listenerCount("wsClientError")){let i=new Error(n);Error.captureStackTrace(i,Ge),t.emit("wsClientError",i,r,e)}else dr(r,s,n,o)}});var me=O(tn=>{"use strict";tn.getBooleanOption=(t,e)=>{let r=!1;if(e in t&&typeof(r=t[e])!="boolean")throw new TypeError(`Expected the "${e}" option to be a boolean`);return r};tn.cppdb=Symbol();tn.inspect=Symbol.for("nodejs.util.inspect.custom")});var Yo=O((kx,ul)=>{"use strict";var Xo={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function it(t,e){if(new.target!==it)return new it(t,e);if(typeof e!="string")throw new TypeError("Expected second argument to be a string");Error.call(this,t),Xo.value=""+t,Object.defineProperty(this,"message",Xo),Error.captureStackTrace(this,it),this.code=e}Object.setPrototypeOf(it,Error);Object.setPrototypeOf(it.prototype,Error.prototype);Object.defineProperty(it.prototype,"name",Xo);ul.exports=it});var fl=O((Tx,dl)=>{"use strict";var rn=I("path").sep||"/";dl.exports=Up;function Up(t){if(typeof t!="string"||t.length<=7||t.substring(0,7)!="file://")throw new TypeError("must pass in a file:// URI to convert to a file path");var e=decodeURI(t.substring(7)),r=e.indexOf("/"),s=e.substring(0,r),n=e.substring(r+1);return s=="localhost"&&(s=""),s&&(s=rn+rn+s),n=n.replace(/^(.+)\|/,"$1:"),rn=="\\"&&(n=n.replace(/\//g,"\\")),/^.+\:/.test(n)||(n=rn+n),s+n}});var gl=O((er,ml)=>{"use strict";var Jo=I("fs"),nn=I("path"),Fp=fl(),sn=nn.join,qp=nn.dirname,hl=Jo.accessSync&&function(t){try{Jo.accessSync(t)}catch{return!1}return!0}||Jo.existsSync||nn.existsSync,pl={arrow:process.env.NODE_BINDINGS_ARROW||" \u2192 ",compiled:process.env.NODE_BINDINGS_COMPILED_DIR||"compiled",platform:process.platform,arch:process.arch,nodePreGyp:"node-v"+process.versions.modules+"-"+process.platform+"-"+process.arch,version:process.versions.node,bindings:"bindings.node",try:[["module_root","build","bindings"],["module_root","build","Debug","bindings"],["module_root","build","Release","bindings"],["module_root","out","Debug","bindings"],["module_root","Debug","bindings"],["module_root","out","Release","bindings"],["module_root","Release","bindings"],["module_root","build","default","bindings"],["module_root","compiled","version","platform","arch","bindings"],["module_root","addon-build","release","install-root","bindings"],["module_root","addon-build","debug","install-root","bindings"],["module_root","addon-build","default","install-root","bindings"],["module_root","lib","binding","nodePreGyp","bindings"]]};function Hp(t){typeof t=="string"?t={bindings:t}:t||(t={}),Object.keys(pl).map(function(c){c in t||(t[c]=pl[c])}),t.module_root||(t.module_root=er.getRoot(er.getFileName())),nn.extname(t.bindings)!=".node"&&(t.bindings+=".node");for(var e=typeof __webpack_require__=="function"?__non_webpack_require__:I,r=[],s=0,n=t.try.length,o,i,a;s<n;s++){o=sn.apply(null,t.try[s].map(function(c){return t[c]||c})),r.push(o);try{return i=t.path?e.resolve(o):e(o),t.path||(i.path=o),i}catch(c){if(c.code!=="MODULE_NOT_FOUND"&&c.code!=="QUALIFIED_PATH_RESOLUTION_FAILED"&&!/not find/i.test(c.message))throw c}}throw a=new Error(`Could not locate the bindings file. Tried:
|
|
9
|
+
`+r.map(function(c){return t.arrow+c}).join(`
|
|
10
|
+
`)),a.tries=r,a}ml.exports=er=Hp;er.getFileName=function(e){var r=Error.prepareStackTrace,s=Error.stackTraceLimit,n={},o;Error.stackTraceLimit=10,Error.prepareStackTrace=function(a,c){for(var l=0,u=c.length;l<u;l++)if(o=c[l].getFileName(),o!==__filename)if(e){if(o!==e)return}else return},Error.captureStackTrace(n),n.stack,Error.prepareStackTrace=r,Error.stackTraceLimit=s;var i="file://";return o.indexOf(i)===0&&(o=Fp(o)),o};er.getRoot=function(e){for(var r=qp(e),s;;){if(r==="."&&(r=process.cwd()),hl(sn(r,"package.json"))||hl(sn(r,"node_modules")))return r;if(s===r)throw new Error('Could not find module root given file: "'+e+'". Do you have a `package.json` file? ');s=r,r=sn(r,"..")}}});var yl=O(Be=>{"use strict";var{cppdb:ue}=me();Be.prepare=function(e){return this[ue].prepare(e,this,!1)};Be.exec=function(e){return this[ue].exec(e),this};Be.close=function(){return this[ue].close(),this};Be.loadExtension=function(...e){return this[ue].loadExtension(...e),this};Be.defaultSafeIntegers=function(...e){return this[ue].defaultSafeIntegers(...e),this};Be.unsafeMode=function(...e){return this[ue].unsafeMode(...e),this};Be.getters={name:{get:function(){return this[ue].name},enumerable:!0},open:{get:function(){return this[ue].open},enumerable:!0},inTransaction:{get:function(){return this[ue].inTransaction},enumerable:!0},readonly:{get:function(){return this[ue].readonly},enumerable:!0},memory:{get:function(){return this[ue].memory},enumerable:!0}}});var wl=O((Ix,bl)=>{"use strict";var{cppdb:Wp}=me(),_l=new WeakMap;bl.exports=function(e){if(typeof e!="function")throw new TypeError("Expected first argument to be a function");let r=this[Wp],s=Vp(r,this),{apply:n}=Function.prototype,o={default:{value:on(n,e,r,s.default)},deferred:{value:on(n,e,r,s.deferred)},immediate:{value:on(n,e,r,s.immediate)},exclusive:{value:on(n,e,r,s.exclusive)},database:{value:this,enumerable:!0}};return Object.defineProperties(o.default.value,o),Object.defineProperties(o.deferred.value,o),Object.defineProperties(o.immediate.value,o),Object.defineProperties(o.exclusive.value,o),o.default.value};var Vp=(t,e)=>{let r=_l.get(t);if(!r){let s={commit:t.prepare("COMMIT",e,!1),rollback:t.prepare("ROLLBACK",e,!1),savepoint:t.prepare("SAVEPOINT ` _bs3. `",e,!1),release:t.prepare("RELEASE ` _bs3. `",e,!1),rollbackTo:t.prepare("ROLLBACK TO ` _bs3. `",e,!1)};_l.set(t,r={default:Object.assign({begin:t.prepare("BEGIN",e,!1)},s),deferred:Object.assign({begin:t.prepare("BEGIN DEFERRED",e,!1)},s),immediate:Object.assign({begin:t.prepare("BEGIN IMMEDIATE",e,!1)},s),exclusive:Object.assign({begin:t.prepare("BEGIN EXCLUSIVE",e,!1)},s)})}return r},on=(t,e,r,{begin:s,commit:n,rollback:o,savepoint:i,release:a,rollbackTo:c})=>function(){let u,d,p;r.inTransaction?(u=i,d=a,p=c):(u=s,d=n,p=o),u.run();try{let h=t.call(e,this,arguments);if(h&&typeof h.then=="function")throw new TypeError("Transaction function cannot return a promise");return d.run(),h}catch(h){throw r.inTransaction&&(p.run(),p!==o&&d.run()),h}}});var Sl=O((Px,El)=>{"use strict";var{getBooleanOption:Gp,cppdb:Kp}=me();El.exports=function(e,r){if(r==null&&(r={}),typeof e!="string")throw new TypeError("Expected first argument to be a string");if(typeof r!="object")throw new TypeError("Expected second argument to be an options object");let s=Gp(r,"simple"),n=this[Kp].prepare(`PRAGMA ${e}`,this,!0);return s?n.pluck().get():n.all()}});var kl=O((Ox,vl)=>{"use strict";var zp=I("fs"),Xp=I("path"),{promisify:Yp}=I("util"),{cppdb:Jp}=me(),xl=Yp(zp.access);vl.exports=async function(e,r){if(r==null&&(r={}),typeof e!="string")throw new TypeError("Expected first argument to be a string");if(typeof r!="object")throw new TypeError("Expected second argument to be an options object");e=e.trim();let s="attached"in r?r.attached:"main",n="progress"in r?r.progress:null;if(!e)throw new TypeError("Backup filename cannot be an empty string");if(e===":memory:")throw new TypeError('Invalid backup filename ":memory:"');if(typeof s!="string")throw new TypeError('Expected the "attached" option to be a string');if(!s)throw new TypeError('The "attached" option cannot be an empty string');if(n!=null&&typeof n!="function")throw new TypeError('Expected the "progress" option to be a function');await xl(Xp.dirname(e)).catch(()=>{throw new TypeError("Cannot save backup because the directory does not exist")});let o=await xl(e).then(()=>!1,()=>!0);return Qp(this[Jp].backup(this,s,e,o),n||null)};var Qp=(t,e)=>{let r=0,s=!0;return new Promise((n,o)=>{setImmediate(function i(){try{let a=t.transfer(r);if(!a.remainingPages){t.close(),n(a);return}if(s&&(s=!1,r=100),e){let c=e(a);if(c!==void 0)if(typeof c=="number"&&c===c)r=Math.max(0,Math.min(2147483647,Math.round(c)));else throw new TypeError("Expected progress callback to return a number or undefined")}setImmediate(i)}catch(a){t.close(),o(a)}})})}});var Rl=O((Mx,Tl)=>{"use strict";var{cppdb:Zp}=me();Tl.exports=function(e){if(e==null&&(e={}),typeof e!="object")throw new TypeError("Expected first argument to be an options object");let r="attached"in e?e.attached:"main";if(typeof r!="string")throw new TypeError('Expected the "attached" option to be a string');if(!r)throw new TypeError('The "attached" option cannot be an empty string');return this[Zp].serialize(r)}});var Il=O((Cx,Al)=>{"use strict";var{getBooleanOption:an,cppdb:em}=me();Al.exports=function(e,r,s){if(r==null&&(r={}),typeof r=="function"&&(s=r,r={}),typeof e!="string")throw new TypeError("Expected first argument to be a string");if(typeof s!="function")throw new TypeError("Expected last argument to be a function");if(typeof r!="object")throw new TypeError("Expected second argument to be an options object");if(!e)throw new TypeError("User-defined function name cannot be an empty string");let n="safeIntegers"in r?+an(r,"safeIntegers"):2,o=an(r,"deterministic"),i=an(r,"directOnly"),a=an(r,"varargs"),c=-1;if(!a){if(c=s.length,!Number.isInteger(c)||c<0)throw new TypeError("Expected function.length to be a positive integer");if(c>100)throw new RangeError("User-defined functions cannot have more than 100 arguments")}return this[em].function(s,e,c,n,o,i),this}});var Ml=O((Nx,Ol)=>{"use strict";var{getBooleanOption:cn,cppdb:tm}=me();Ol.exports=function(e,r){if(typeof e!="string")throw new TypeError("Expected first argument to be a string");if(typeof r!="object"||r===null)throw new TypeError("Expected second argument to be an options object");if(!e)throw new TypeError("User-defined function name cannot be an empty string");let s="start"in r?r.start:null,n=Qo(r,"step",!0),o=Qo(r,"inverse",!1),i=Qo(r,"result",!1),a="safeIntegers"in r?+cn(r,"safeIntegers"):2,c=cn(r,"deterministic"),l=cn(r,"directOnly"),u=cn(r,"varargs"),d=-1;if(!u&&(d=Math.max(Pl(n),o?Pl(o):0),d>0&&(d-=1),d>100))throw new RangeError("User-defined functions cannot have more than 100 arguments");return this[tm].aggregate(s,n,o,i,e,d,a,c,l),this};var Qo=(t,e,r)=>{let s=e in t?t[e]:null;if(typeof s=="function")return s;if(s!=null)throw new TypeError(`Expected the "${e}" option to be a function`);if(r)throw new TypeError(`Missing required option "${e}"`);return null},Pl=({length:t})=>{if(Number.isInteger(t)&&t>=0)return t;throw new TypeError("Expected function.length to be a positive integer")}});var $l=O((Lx,Ll)=>{"use strict";var{cppdb:rm}=me();Ll.exports=function(e,r){if(typeof e!="string")throw new TypeError("Expected first argument to be a string");if(!e)throw new TypeError("Virtual table module name cannot be an empty string");let s=!1;if(typeof r=="object"&&r!==null)s=!0,r=um(Nl(r,"used",e));else{if(typeof r!="function")throw new TypeError("Expected second argument to be a function or a table definition object");r=sm(r)}return this[rm].table(r,e,s),this};function sm(t){return function(r,s,n,...o){let i={module:r,database:s,table:n},a=cm.call(t,i,o);if(typeof a!="object"||a===null)throw new TypeError(`Virtual table module "${r}" did not return a table definition object`);return Nl(a,"returned",r)}}function Nl(t,e,r){if(!qr.call(t,"rows"))throw new TypeError(`Virtual table module "${r}" ${e} a table definition without a "rows" property`);if(!qr.call(t,"columns"))throw new TypeError(`Virtual table module "${r}" ${e} a table definition without a "columns" property`);let s=t.rows;if(typeof s!="function"||Object.getPrototypeOf(s)!==lm)throw new TypeError(`Virtual table module "${r}" ${e} a table definition with an invalid "rows" property (should be a generator function)`);let n=t.columns;if(!Array.isArray(n)||!(n=[...n]).every(l=>typeof l=="string"))throw new TypeError(`Virtual table module "${r}" ${e} a table definition with an invalid "columns" property (should be an array of strings)`);if(n.length!==new Set(n).size)throw new TypeError(`Virtual table module "${r}" ${e} a table definition with duplicate column names`);if(!n.length)throw new RangeError(`Virtual table module "${r}" ${e} a table definition with zero columns`);let o;if(qr.call(t,"parameters")){if(o=t.parameters,!Array.isArray(o)||!(o=[...o]).every(l=>typeof l=="string"))throw new TypeError(`Virtual table module "${r}" ${e} a table definition with an invalid "parameters" property (should be an array of strings)`)}else o=am(s);if(o.length!==new Set(o).size)throw new TypeError(`Virtual table module "${r}" ${e} a table definition with duplicate parameter names`);if(o.length>32)throw new RangeError(`Virtual table module "${r}" ${e} a table definition with more than the maximum number of 32 parameters`);for(let l of o)if(n.includes(l))throw new TypeError(`Virtual table module "${r}" ${e} a table definition with column "${l}" which was ambiguously defined as both a column and parameter`);let i=2;if(qr.call(t,"safeIntegers")){let l=t.safeIntegers;if(typeof l!="boolean")throw new TypeError(`Virtual table module "${r}" ${e} a table definition with an invalid "safeIntegers" property (should be a boolean)`);i=+l}let a=!1;if(qr.call(t,"directOnly")&&(a=t.directOnly,typeof a!="boolean"))throw new TypeError(`Virtual table module "${r}" ${e} a table definition with an invalid "directOnly" property (should be a boolean)`);return[`CREATE TABLE x(${[...o.map(Cl).map(l=>`${l} HIDDEN`),...n.map(Cl)].join(", ")});`,nm(s,new Map(n.map((l,u)=>[l,o.length+u])),r),o,i,a]}function nm(t,e,r){return function*(...n){let o=n.map(i=>Buffer.isBuffer(i)?Buffer.from(i):i);for(let i=0;i<e.size;++i)o.push(null);for(let i of t(...n))if(Array.isArray(i))om(i,o,e.size,r),yield o;else if(typeof i=="object"&&i!==null)im(i,o,e,r),yield o;else throw new TypeError(`Virtual table module "${r}" yielded something that isn't a valid row object`)}}function om(t,e,r,s){if(t.length!==r)throw new TypeError(`Virtual table module "${s}" yielded a row with an incorrect number of columns`);let n=e.length-r;for(let o=0;o<r;++o)e[o+n]=t[o]}function im(t,e,r,s){let n=0;for(let o of Object.keys(t)){let i=r.get(o);if(i===void 0)throw new TypeError(`Virtual table module "${s}" yielded a row with an undeclared column "${o}"`);e[i]=t[o],n+=1}if(n!==r.size)throw new TypeError(`Virtual table module "${s}" yielded a row with missing columns`)}function am({length:t}){if(!Number.isInteger(t)||t<0)throw new TypeError("Expected function.length to be a positive integer");let e=[];for(let r=0;r<t;++r)e.push(`$${r+1}`);return e}var{hasOwnProperty:qr}=Object.prototype,{apply:cm}=Function.prototype,lm=Object.getPrototypeOf(function*(){}),Cl=t=>`"${t.replace(/"/g,'""')}"`,um=t=>()=>t});var jl=O(($x,Dl)=>{"use strict";var dm=function(){};Dl.exports=function(e,r){return Object.assign(new dm,this)}});var ql=O((Dx,Fl)=>{"use strict";var fm=I("fs"),Bl=I("path"),ln=me(),hm=Yo(),Ul;function z(t,e){if(new.target==null)return new z(t,e);let r;if(Buffer.isBuffer(t)&&(r=t,t=":memory:"),t==null&&(t=""),e==null&&(e={}),typeof t!="string")throw new TypeError("Expected first argument to be a string");if(typeof e!="object")throw new TypeError("Expected second argument to be an options object");if("readOnly"in e)throw new TypeError('Misspelled option "readOnly" should be "readonly"');if("memory"in e)throw new TypeError('Option "memory" was removed in v7.0.0 (use ":memory:" filename instead)');let s=t.trim(),n=s===""||s===":memory:",o=ln.getBooleanOption(e,"readonly"),i=ln.getBooleanOption(e,"fileMustExist"),a="timeout"in e?e.timeout:5e3,c="verbose"in e?e.verbose:null,l="nativeBinding"in e?e.nativeBinding:null;if(o&&n&&!r)throw new TypeError("In-memory/temporary databases cannot be readonly");if(!Number.isInteger(a)||a<0)throw new TypeError('Expected the "timeout" option to be a positive integer');if(a>2147483647)throw new RangeError('Option "timeout" cannot be greater than 2147483647');if(c!=null&&typeof c!="function")throw new TypeError('Expected the "verbose" option to be a function');if(l!=null&&typeof l!="string"&&typeof l!="object")throw new TypeError('Expected the "nativeBinding" option to be a string or addon object');let u;if(l==null?u=Ul||(Ul=gl()("better_sqlite3.node")):typeof l=="string"?u=(typeof __non_webpack_require__=="function"?__non_webpack_require__:I)(Bl.resolve(l).replace(/(\.node)?$/,".node")):u=l,u.isInitialized||(u.setErrorConstructor(hm),u.isInitialized=!0),!n&&!s.startsWith("file:")&&!fm.existsSync(Bl.dirname(s)))throw new TypeError("Cannot open database because the directory does not exist");Object.defineProperties(this,{[ln.cppdb]:{value:new u.Database(s,t,n,o,i,a,c||null,r||null)},...at.getters})}var at=yl();z.prototype.prepare=at.prepare;z.prototype.transaction=wl();z.prototype.pragma=Sl();z.prototype.backup=kl();z.prototype.serialize=Rl();z.prototype.function=Il();z.prototype.aggregate=Ml();z.prototype.table=$l();z.prototype.loadExtension=at.loadExtension;z.prototype.exec=at.exec;z.prototype.close=at.close;z.prototype.defaultSafeIntegers=at.defaultSafeIntegers;z.prototype.unsafeMode=at.unsafeMode;z.prototype[ln.inspect]=jl();Fl.exports=z});var ei=O((Bx,Zo)=>{"use strict";Zo.exports=ql();Zo.exports.SqliteError=Yo()});import{existsSync as Mm}from"fs";import{stat as Cm}from"fs/promises";import{dirname as Nm,join as nu}from"path";import{createServer as hu}from"http";import{Http2ServerRequest as ai,constants as pu}from"http2";import{Http2ServerRequest as mn}from"http2";import{Readable as oi}from"stream";import ku from"crypto";var Ue=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},mu=t=>t instanceof Ue?t:new Ue(t.message,{cause:t}),gu=global.Request,sr=class extends gu{constructor(t,e){typeof t=="object"&&ft in t&&(t=t[ft]()),typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},yu=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)},ci=Symbol("wrapBodyStream"),_u=(t,e,r,s,n)=>{let o={method:t,headers:r,signal:n.signal};if(t==="TRACE"){o.method="GET";let i=new sr(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[ci]){let i;o.body=new ReadableStream({async pull(a){try{i||=oi.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=oi.toWeb(s);return new sr(e,o)},ft=Symbol("getRequestCache"),li=Symbol("requestCache"),Wr=Symbol("incomingKey"),Vr=Symbol("urlKey"),bu=Symbol("headersKey"),dt=Symbol("abortControllerKey"),wu=Symbol("getAbortController"),nr={get method(){return this[Wr].method||"GET"},get url(){return this[Vr]},get headers(){return this[bu]||=yu(this[Wr])},[wu](){return this[ft](),this[dt]},[ft](){return this[dt]||=new AbortController,this[li]||=_u(this.method,this[Vr],this.headers,this[Wr],this[dt])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(t=>{Object.defineProperty(nr,t,{get(){return this[ft]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(nr,t,{value:function(){return this[ft]()[t]()}})});Object.defineProperty(nr,Symbol.for("nodejs.util.inspect.custom"),{value:function(t,e,r){let s={method:this.method,url:this.url,headers:this.headers,nativeRequest:this[li]};return`Request (lightweight) ${r(s,{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(nr,sr.prototype);var Eu=(t,e)=>{let r=Object.create(nr);r[Wr]=t;let s=t.url||"";if(s[0]!=="/"&&(s.startsWith("http://")||s.startsWith("https://"))){if(t instanceof mn)throw new Ue("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(s);r[Vr]=a.href}catch(a){throw new Ue("Invalid absolute URL",{cause:a})}return r}let n=(t instanceof mn?t.authority:t.headers.host)||e;if(!n)throw new Ue("Missing host header");let o;if(t instanceof mn){if(o=t.scheme,!(o==="http"||o==="https"))throw new Ue("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 Ue("Invalid host header");return r[Vr]=i.href,r},yn=Symbol("responseCache"),ut=Symbol("getResponseCache"),Fe=Symbol("cache"),wn=global.Response,ht=class ui{#e;#t;[ut](){return delete this[Fe],this[yn]||=new wn(this.#e,this.#t)}constructor(e,r){let s;if(this.#e=e,r instanceof ui){let n=r[yn];if(n){this.#t=n,this[ut]();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[Fe]=[r?.status||200,e,s||r?.headers])}get headers(){let e=this[Fe];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":"text/plain; charset=UTF-8"})),e[2]):this[ut]().headers}get status(){return this[Fe]?.[0]??this[ut]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(ht.prototype,t,{get(){return this[ut]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(ht.prototype,t,{value:function(){return this[ut]()[t]()}})});Object.defineProperty(ht.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[yn]};return`Response (lightweight) ${r(s,{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(ht,wn);Object.setPrototypeOf(ht.prototype,wn.prototype);async function Su(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function di(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 xu(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:di(t.getReader(),e)}var _n=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},vu="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=ku);var En=Symbol("outgoingEnded"),ii=Symbol("incomingDraining"),Tu=500,Ru=64*1024*1024,gn=t=>{let e=t;if(t.destroyed||e[ii])return;if(e[ii]=!0,t instanceof ai){try{t.stream?.close?.(pu.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,Tu);o.unref?.();let i=a=>{r+=a.length,r>Ru&&n()};t.on("data",i),t.on("end",s),t.on("error",s),t.resume()},Au=()=>new Response(null,{status:400}),fi=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),bn=(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))},hi=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},pi=async(t,e)=>{let[r,s,n]=t[Fe],o=!1;if(!n)n={"content-type":"text/plain; charset=UTF-8"};else if(n instanceof Headers)o=n.has("content-length"),n=_n(n);else if(Array.isArray(n)){let i=new Headers(n);o=i.has("content-length"),n=_n(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())):(hi(e),await xu(s,e)?.catch(i=>bn(i,e))),e[En]?.()},Iu=t=>typeof t.then=="function",Pu=async(t,e,r={})=>{if(Iu(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(fi);if(Fe in t)return pi(t,e);let s=_n(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 Su(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&&hi(e),await di(n,e,a))}else s[vu]||(e.writeHead(t.status,s),e.end());e[En]?.()},Ou=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==sr&&(Object.defineProperty(global,"Request",{value:sr}),Object.defineProperty(global,"Response",{value:ht})),async(s,n)=>{let o,i;try{i=Eu(s,e.hostname);let a=!r||s.method==="GET"||s.method==="HEAD";if(a||(s[ci]=!0,s.on("end",()=>{a=!0}),s instanceof ai&&(n[En]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{gn(s)})})}),n.on("finish",()=>{a||gn(s)})),n.on("close",()=>{i[dt]&&(s.errored?i[dt].abort(s.errored.toString()):n.writableFinished||i[dt].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{gn(s)})})}),o=t(i,{incoming:s,outgoing:n}),Fe in o)return pi(o,n)}catch(a){if(o)return bn(a,n);if(e.errorHandler){if(o=await e.errorHandler(i?a:mu(a)),!o)return}else i?o=fi(a):o=Au()}try{return await Pu(o,n,e)}catch(a){return bn(a,n)}}},Mu=t=>{let e=t.fetch,r=Ou(e,{hostname:t.hostname,overrideGlobalObjects:t.overrideGlobalObjects,autoCleanupIncoming:t.autoCleanupIncoming});return(t.createServer||hu)(t.serverOptions||{},r)},mi=(t,e)=>{let r=Mu(t);return r.listen(t?.port??3e3,t.hostname,()=>{let s=r.address();e&&e(s)}),r};var gi=(t,e=Nu)=>{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 Cu={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"},Nu=Cu;import{createReadStream as yi,statSync as Lu,existsSync as $u}from"fs";import{join as _i}from"path";import{versions as Du}from"process";import{Readable as ju}from"stream";var Bu=/^\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,xn={br:".br",zstd:".zst",gzip:".gz"},Uu=Object.keys(xn),Fu=()=>{let[t,e]=Du.node.split(".").map(r=>parseInt(r));return t>=23||t===22&&e>=7||t===20&&e>=18},qu=Fu(),bi=t=>qu?ju.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()}}),Sn=t=>{let e;try{e=Lu(t)}catch{}return e},Hu=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},Wu=t=>Hu(t,decodeURI),wi=(t={root:""})=>{let e=t.root||"",r=t.path;return e!==""&&!$u(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=Wu(s.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}/.test(o))throw new Error}catch{return await t.onNotFound?.(s.req.path,s),n()}let i=_i(e,!r&&t.rewriteRequestPath?t.rewriteRequestPath(o,s):o),a=Sn(i);if(a&&a.isDirectory()){let p=t.index??"index.html";i=_i(i,p),a=Sn(i)}if(!a)return await t.onNotFound?.(i,s),n();let c=gi(i);if(s.header("Content-Type",c||"application/octet-stream"),t.precompressed&&(!c||Bu.test(c))){let p=new Set(s.req.header("Accept-Encoding")?.split(",").map(h=>h.trim()));for(let h of Uu){if(!p.has(h))continue;let g=Sn(i+xn[h]);if(g){s.header("Content-Encoding",h),s.header("Vary","Accept-Encoding",{append:!0}),a=g,i=i+xn[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(bi(yi(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 y=g-h+1,w=yi(i,{start:h,end:g});s.header("Content-Length",y.toString()),s.header("Content-Range",`bytes ${h}-${g}/${a.size}`),l=s.body(bi(w),206)}return await t.onFound?.(i,s),l}};var df=de(ma(),1),ff=de(es(),1),hf=de(gt(),1),pf=de(Nn(),1),mf=de(Dn(),1),gf=de(Hn(),1),yf=de(ns(),1),Vn=de(xa(),1);var Gn=(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 va=Symbol();var ka=async(t,e=Object.create(null))=>{let{all:r=!1,dot:s=!1}=e,o=(t instanceof is?t.raw.headers:t.headers).get("Content-Type");return o?.startsWith("multipart/form-data")||o?.startsWith("application/x-www-form-urlencoded")?_f(t,{all:r,dot:s}):{}};async function _f(t,e){let r=await t.formData();return r?bf(r,e):{}}function bf(t,e){let r=Object.create(null);return t.forEach((s,n)=>{e.all||n.endsWith("[]")?wf(r,n,s):r[n]=s}),e.dot&&Object.entries(r).forEach(([s,n])=>{s.includes(".")&&(Ef(r,s,n),delete r[s])}),r}var wf=(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},Ef=(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 zn=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},Ta=t=>{let{groups:e,path:r}=Sf(t),s=zn(r);return xf(s,e)},Sf=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,s)=>{let n=`@${s}`;return e.push([n,r]),n}),{groups:e,path:t}},xf=(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},as={},Ra=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let s=`${t}#${e}`;return as[s]||(r[2]?as[s]=e&&e[0]!==":"&&e[0]!=="*"?[s,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:as[s]=[t,r[1],!0]),as[s]}return null},cs=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},vf=t=>cs(t,decodeURI),Xn=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 vf(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(n===63||n===35)break}return e.slice(r,s)};var Aa=t=>{let e=Xn(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},Ke=(t,e,...r)=>(r.length&&(e=Ke(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),ls=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?cs(t,Yn):t):t,Ia=(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},Pa=Ia,Oa=(t,e)=>Ia(t,e,!0),Yn=decodeURIComponent;var Ma=t=>cs(t,Yn),is=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.#r(t):this.#o()}#r(t){let e=this.#t[0][this.routeIndex][1][t],r=this.#s(e);return r&&/\%/.test(r)?Ma(r):r}#o(){let t={},e=Object.keys(this.#t[0][this.routeIndex][1]);for(let r of e){let s=this.#s(this.#t[0][this.routeIndex][1][r]);s!==void 0&&(t[r]=/\%/.test(s)?Ma(s):s)}return t}#s(t){return this.#t[1]?this.#t[1][t]:t}query(t){return Pa(this.url,t)}queries(t){return Oa(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 ka(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[va](){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 us={Stringify:1,BeforeStream:2,Stream:3},kf=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r};var fr=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=>fr(c,e,!1,s,n))).then(()=>n[0]));return r?kf(await i,o):i};var Ca="text/plain; charset=UTF-8",Jn=(t,e)=>({"Content-Type":t,...e}),hr=(t,e)=>new Response(t,e),Na=class{#e;#t;env={};#r;finalized=!1;error;#o;#s;#n;#l;#a;#u;#c;#f;#p;constructor(t,e){this.#e=t,e&&(this.#s=e.executionCtx,this.env=e.env,this.#u=e.notFoundHandler,this.#p=e.path,this.#f=e.matchResult)}get req(){return this.#t??=new is(this.#e,this.#p,this.#f),this.#t}get event(){if(this.#s&&"respondWith"in this.#s)return this.#s;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#s)return this.#s;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=hr(null,{headers:this.#c??=new Headers})}set res(t){if(this.#n&&t){t=hr(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.#a??=e=>this.html(e),this.#a(...t));setLayout=t=>this.#l=t;getLayout=()=>this.#l;setRenderer=t=>{this.#a=t};header=(t,e,r)=>{this.finalized&&(this.#n=hr(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.#r??=new Map,this.#r.set(t,e)};get=t=>this.#r?this.#r.get(t):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#h(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 hr(t,{status:n,headers:s})}newResponse=(...t)=>this.#h(...t);body=(t,e,r)=>this.#h(t,e,r);text=(t,e,r)=>!this.#c&&!this.#o&&!e&&!r&&!this.finalized?new Response(t):this.#h(t,e,Jn(Ca,r));json=(t,e,r)=>this.#h(JSON.stringify(t),e,Jn("application/json",r));html=(t,e,r)=>{let s=n=>this.#h(n,e,Jn("text/html; charset=UTF-8",r));return typeof t=="object"?fr(t,us.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.#u??=()=>hr(),this.#u(this))};var L="ALL",La="all",$a=["get","post","put","delete","options","patch"],ds="Can not add a route since the matcher is already built.",fs=class extends Error{};var Da="__COMPOSED_HANDLER";var Tf=t=>t.text("404 Not Found",404),ja=(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)},Ba=class Ua{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(e={}){[...$a,La].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(L,this.#e,a)}),this);let{strict:s,...n}=e;Object.assign(this,n),this.getPath=s??!0?e.getPath??Xn:Aa}#t(){let e=new Ua({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=Tf;errorHandler=ja;route(e,r){let s=this.basePath(e);return r.routes.map(n=>{let o;r.errorHandler===ja?o=n.handler:(o=async(i,a)=>(await Gn([],r.errorHandler)(i,()=>n.handler(i,a))).res,o[Da]=n.handler),s.#o(n.method,n.path,o)}),this}basePath(e){let r=this.#t();return r._basePath=Ke(this._basePath,e),r}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#r=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=Ke(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(L,Ke(e,"*"),a),this}#o(e,r,s){e=e.toUpperCase(),r=Ke(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)}#s(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 Na(e,{path:o,matchResult:i,env:s,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#s(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#s(u,a)):l??this.#r(a)}let c=Gn(i[0],this.errorHandler,this.#r);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.#s(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${Ke("/",e)}`,r),s,n));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#n(e.request,e,void 0,e.request.method))})}};var hs=[];function Qn(t,e){let r=this.buildAllMatchers(),s=((n,o)=>{let i=r[n]||r[L],a=i[2][o];if(a)return a;let c=o.match(i[0]);if(!c)return[[],hs];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=s,s(t,e)}var ps="[^/]+",pr=".*",mr="(?:|/.*)",ze=Symbol(),Rf=new Set(".\\+*[^]$()");function Af(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===pr||t===mr?1:e===pr||e===mr?-1:t===ps?1:e===ps?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var Fa=class Zn{#e;#t;#r=Object.create(null);insert(e,r,s,n,o){if(e.length===0){if(this.#e!==void 0)throw ze;if(o)return;this.#e=r;return}let[i,...a]=e,c=i==="*"?a.length===0?["","",pr]:["","",ps]:i==="/*"?["","",mr]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],d=c[2]||ps;if(u&&c[2]&&(d===".*"||(d=d.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(d))))throw ze;if(l=this.#r[d],!l){if(Object.keys(this.#r).some(p=>p!==pr&&p!==mr))throw ze;if(o)return;l=this.#r[d]=new Zn,u!==""&&(l.#t=n.varIndex++)}!o&&u!==""&&s.push([u,l.#t])}else if(l=this.#r[i],!l){if(Object.keys(this.#r).some(u=>u.length>1&&u!==pr&&u!==mr))throw ze;if(o)return;l=this.#r[i]=new Zn}l.insert(a,r,s,n,o)}buildRegExpStr(){let r=Object.keys(this.#r).sort(Af).map(s=>{let n=this.#r[s];return(typeof n.#t=="number"?`(${s})@${n.#t}`:Rf.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 qa=class{#e={varIndex:0};#t=new Fa;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 If=[/^$/,[],Object.create(null)],Ha=Object.create(null);function Wa(t){return Ha[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function Pf(){Ha=Object.create(null)}function Of(t){let e=new qa,r=[];if(t.length===0)return If;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(([w])=>[w,Object.create(null)]),hs]:u++;let y;try{y=e.insert(h,u,p)}catch(w){throw w===ze?new fs(h):w}p||(r[u]=g.map(([w,k])=>{let A=Object.create(null);for(k-=1;k>=0;k--){let[x,v]=y[k];A[x]=v}return[w,A]}))}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 y=0,w=g.length;y<w;y++)h[g[y]]=a[h[g[y]]]}let c=[];for(let l in i)c[l]=r[i[l]];return[o,c,n]}function St(t,e){if(t){for(let r of Object.keys(t).sort((s,n)=>n.length-s.length))if(Wa(r).test(e))return[...t[r]]}}var ms=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[L]:Object.create(null)},this.#t={[L]:Object.create(null)}}add(t,e,r){let s=this.#e,n=this.#t;if(!s||!n)throw new Error(ds);s[t]||[s,n].forEach(a=>{a[t]=Object.create(null),Object.keys(a[L]).forEach(c=>{a[t][c]=[...a[L][c]]})}),e==="/*"&&(e="*");let o=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=Wa(e);t===L?Object.keys(s).forEach(c=>{s[c][e]||=St(s[c],e)||St(s[L],e)||[]}):s[t][e]||=St(s[t],e)||St(s[L],e)||[],Object.keys(s).forEach(c=>{(t===L||t===c)&&Object.keys(s[c]).forEach(l=>{a.test(l)&&s[c][l].push([r,o])})}),Object.keys(n).forEach(c=>{(t===L||t===c)&&Object.keys(n[c]).forEach(l=>a.test(l)&&n[c][l].push([r,o]))});return}let i=ls(e)||[e];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(n).forEach(u=>{(t===L||t===u)&&(n[u][l]||=[...St(s[u],l)||St(s[L],l)||[]],n[u][l].push([r,o-c+a+1]))})}}match=Qn;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach(e=>{t[e]||=this.#r(e)}),this.#e=this.#t=void 0,Pf(),t}#r(t){let e=[],r=t===L;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!==L&&e.push(...Object.keys(s[L]).map(o=>[o,s[L][o]]))}),r?Of(e):null}};var eo=class{name="SmartRouter";#e=[];#t=[];constructor(t){this.#e=t.routers}add(t,e,r){if(!this.#t)throw new Error(ds);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 fs)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 gr=Object.create(null),Mf=t=>{for(let e in t)return!0;return!1},Va=class Ga{#e;#t;#r;#o=0;#s=gr;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.#r=[]}insert(e,r,s){this.#o=++this.#o;let n=this,o=Ta(r),i=[];for(let a=0,c=o.length;a<c;a++){let l=o[a],u=o[a+1],d=Ra(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 Ga,d&&(n.#r.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[L],u={};if(l!==void 0&&(l.params=Object.create(null),e.push(l),n!==gr||o&&o!==gr))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.#s=gr;let o=[this],i=zn(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 y=0,w=o.length;y<w;y++){let k=o[y],A=k.#t[d];A&&(A.#s=k.#s,p?(A.#t["*"]&&this.#n(s,A.#t["*"],e,k.#s),this.#n(s,A,e,k.#s)):h.push(A));for(let x=0,v=k.#r.length;x<v;x++){let C=k.#r[x],M=k.#s===gr?{}:{...k.#s};if(C==="*"){let B=k.#t["*"];B&&(this.#n(s,B,e,k.#s),B.#s=M,h.push(B));continue}let[j,Y,S]=C;if(!d&&!(S instanceof RegExp))continue;let $=k.#t[j];if(S instanceof RegExp){if(l===null){l=new Array(c);let V=r[0]==="/"?1:0;for(let R=0;R<c;R++)l[R]=V,V+=i[R].length+1}let B=r.substring(l[u]),U=S.exec(B);if(U){if(M[Y]=U[0],this.#n(s,$,e,k.#s,M),Mf($.#t)){$.#s=M;let V=U[0].match(/\//)?.length??0;(a[V]||=[]).push($)}continue}}(S===!0||S.test(d))&&(M[Y]=d,p?(this.#n(s,$,e,M,k.#s),$.#t["*"]&&this.#n(s,$.#t["*"],e,M,k.#s)):($.#s=M,h.push($)))}}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 to=class{name="TrieRouter";#e;constructor(){this.#e=new Va}add(t,e,r){let s=ls(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 ro=class extends Ba{constructor(t={}){super(t),this.router=t.router??new eo({routers:[new ms,new to]})}};var so=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+`
|
|
11
|
+
`),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 gs=()=>{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 gs=()=>e,e};var Ka=class extends so{constructor(t,e){super(t,e)}async writeSSE(t){let r=(await fr(t.data,us.Stringify,!1,{})).split(/\r\n|\r|\n/).map(n=>`data: ${n}`).join(`
|
|
10
12
|
`);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
13
|
`)+`
|
|
12
14
|
|
|
13
|
-
`;await this.write(s)}},
|
|
15
|
+
`;await this.write(s)}},Cf=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()}},Nf=new WeakMap,no=(t,e,r)=>{let{readable:s,writable:n}=new TransformStream,o=new Ka(n,s);return gs()&&t.req.raw.signal.addEventListener("abort",()=>{o.closed||o.abort()}),Nf.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"),Cf(o,e,r),t.newResponse(o.responseReadable)};var za={streaming:!0,approvalPrompts:!0,background:!1};var $f={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","subagents"]},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 Xa(t,e){let r=$f[e];return r.allowedTools.length===0?t:t.filter(s=>r.allowedTools.includes(s.name))}import{existsSync as i_,mkdirSync as a_,readdirSync as c_,readFileSync as l_,renameSync as u_,statSync as d_,writeFileSync as f_}from"fs";import{join as Df,resolve as p_}from"path";var jf={baseURL:"https://openrouter.ai/api/v1"},Bf={model:"claude-haiku-4-5-20251001"},J=class extends Error{constructor(e){super(e),this.name="ConfigValidationError"}},Uf={model:{provider:"openai-compatible",baseURL:"https://api.openai.com/v1",model:"gpt-4.1-mini",temperature:.2,maxTokens:4096},workspace:{root:"."},agents:{},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 Ja(t={}){let e=Ff(Uf);return Ya(e,t.userConfig),Ya(e,t.projectConfig),qf(e,t.env??{}),Hf(e),e}function Ff(t){return{model:{...t.model},workspace:{...t.workspace},agents:{...t.agents},runtime:{...t.runtime},trace:{...t.trace},tools:{...t.tools},permissions:{...t.permissions},sessions:{...t.sessions},memory:{...t.memory},secrets:{...t.secrets}}}function Ya(t,e){if(e!==void 0){if(!Qa(e))throw new J("Configuration must be an object.");Ee(t.model,e.model),Ee(t.workspace,e.workspace),Ee(t.agents,e.agents),Ee(t.runtime,e.runtime),Ee(t.trace,e.trace),Ee(t.tools,e.tools),Ee(t.permissions,e.permissions),Ee(t.sessions,e.sessions),Ee(t.memory,e.memory)}}function Ee(t,e){if(e!==void 0){if(!Qa(e))throw new J("Configuration sections must be objects.");for(let[r,s]of Object.entries(e))r in t&&(t[r]=s)}}function qf(t,e){e.OPENROUTER_API_KEY!==void 0&&(t.model.provider="openai-compatible",t.model.baseURL=jf.baseURL,t.model.model="",t.secrets.apiKey=e.OPENROUTER_API_KEY),e.ANTHROPIC_API_KEY!==void 0&&(t.model.provider="anthropic",t.model.model=Bf.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_AGENT!==void 0&&(t.agents.default=e.VOLE_AGENT),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 Hf(t){if(t.model.provider!=="openai-compatible"&&t.model.provider!=="anthropic")throw new J(`Invalid model.provider "${String(t.model.provider)}". Expected openai-compatible or anthropic.`);if(t.model.model.trim().length===0)throw new J("No model configured. Set VOLE_MODEL=<model-name> (e.g. VOLE_MODEL=openai/gpt-4o for OpenRouter).");if(!Wf(t.runtime.defaultMode))throw new J(`Invalid runtime.defaultMode "${String(t.runtime.defaultMode)}". Expected observe, confirm, or auto.`);if(!Vf(t.trace.verbosity))throw new J(`Invalid trace.verbosity "${String(t.trace.verbosity)}". Expected explainable or debug.`);if(!Gf(t.memory.longTermFiles))throw new J(`Invalid memory.longTermFiles "${String(t.memory.longTermFiles)}". Expected disabled or read-only.`);if(t.memory.writes!=="disabled")throw new J(`Invalid memory.writes "${String(t.memory.writes)}". Only disabled is supported.`);if(t.runtime.promptMode!==void 0&&!Kf(t.runtime.promptMode))throw new J(`Invalid runtime.promptMode "${String(t.runtime.promptMode)}". Expected full, minimal, or none.`);if(t.runtime.executionContract!==void 0&&!zf(t.runtime.executionContract))throw new J(`Invalid runtime.executionContract "${String(t.runtime.executionContract)}". Expected default or strict-agentic.`);if(t.runtime.toolProfile!==void 0&&!Xf(t.runtime.toolProfile))throw new J(`Invalid runtime.toolProfile "${String(t.runtime.toolProfile)}". Expected coding, full, messaging, or background.`);if(t.model.thinkingBudget!==void 0&&!Yf(t.model.thinkingBudget))throw new J(`Invalid model.thinkingBudget "${String(t.model.thinkingBudget)}". Expected off, minimal, low, medium, high, max, or adaptive.`)}function Qa(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Wf(t){return t==="observe"||t==="confirm"||t==="auto"}function Vf(t){return t==="explainable"||t==="debug"}function Gf(t){return t==="disabled"||t==="read-only"||t==="write"}function Kf(t){return t==="full"||t==="minimal"||t==="none"}function zf(t){return t==="default"||t==="strict-agentic"}function Xf(t){return t==="coding"||t==="full"||t==="messaging"||t==="background"}function Yf(t){return t==="off"||t==="minimal"||t==="low"||t==="medium"||t==="high"||t==="max"||t==="adaptive"}function Za(t,e){let r=t.sessions.directory;if(!r.startsWith("~/"))return r;let s=e?.HOME??process.env.HOME;return s===void 0?r:Df(s,r.slice(2))}import{readFile as Jf}from"fs/promises";import{join as Qf}from"path";var ys=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:[]}}}},_s=class{#e;#t;constructor(e={}){this.#e=e.workspacePromptFiles??[],this.#t=e.readWorkspaceFile??(r=>Jf(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
16
|
${e.systemInstruction}
|
|
15
17
|
</identity>`),s.push({name:"identity",included:!0}),r==="full"){if(e.runtime?(n.push("",`<runtime>
|
|
16
18
|
- Mode: ${e.runtime.mode}
|
|
17
19
|
- Workspace: ${e.runtime.workspace}
|
|
18
20
|
- Date: ${e.runtime.currentDate}
|
|
19
|
-
</runtime>`),s.push({name:"runtime",included:!0})):s.push({name:"runtime",included:!1,reason:"No runtime metadata provided."}),e.
|
|
21
|
+
</runtime>`),s.push({name:"runtime",included:!0})):s.push({name:"runtime",included:!1,reason:"No runtime metadata provided."}),e.currentDateTime!==void 0&&e.currentDateTime.length>0?(n.push("",`<current-date>
|
|
22
|
+
${e.currentDateTime}
|
|
23
|
+
</current-date>`),s.push({name:"current_date",included:!0})):s.push({name:"current_date",included:!1,reason:"No currentDateTime provided."}),e.tools!==void 0&&e.tools.length>0){let l=e.tools.map(u=>`- ${u.name} [${u.risk}]: ${u.description}`).join(`
|
|
20
24
|
`);n.push("",`<tooling>
|
|
21
25
|
${l}
|
|
22
|
-
</tooling>`),s.push({name:"tooling",included:!0})}else s.push({name:"tooling",included:!1,reason:"No tools registered."});if(e.
|
|
26
|
+
</tooling>`),s.push({name:"tooling",included:!0})}else s.push({name:"tooling",included:!1,reason:"No tools registered."});if(e.executionBias!==void 0&&e.executionBias.length>0?(n.push("",`<execution-bias>
|
|
27
|
+
${e.executionBias}
|
|
28
|
+
</execution-bias>`),s.push({name:"execution_bias",included:!0})):s.push({name:"execution_bias",included:!1,reason:"No executionBias provided."}),e.permissionGuidance!==void 0&&e.permissionGuidance.length>0?(n.push("",`<safety>
|
|
23
29
|
${e.permissionGuidance}
|
|
24
|
-
</safety>`),s.push({name:"safety",included:!0})):s.push({name:"safety",included:!1,reason:"No permission guidance provided."}),e.
|
|
30
|
+
</safety>`),s.push({name:"safety",included:!0})):s.push({name:"safety",included:!1,reason:"No permission guidance provided."}),e.reasoningPolicy!==void 0&&e.reasoningPolicy.length>0?(n.push("",`<reasoning>
|
|
31
|
+
${e.reasoningPolicy}
|
|
32
|
+
</reasoning>`),s.push({name:"reasoning",included:!0})):s.push({name:"reasoning",included:!1,reason:"No reasoningPolicy provided."}),e.replyTagsPolicy!==void 0&&e.replyTagsPolicy.length>0?(n.push("",`<reply-tags>
|
|
33
|
+
${e.replyTagsPolicy}
|
|
34
|
+
</reply-tags>`),s.push({name:"reply_tags",included:!0})):s.push({name:"reply_tags",included:!1,reason:"No replyTagsPolicy provided."}),e.skillIndex!==void 0&&e.skillIndex.length>0){let l=e.skillIndex.map(u=>`- ${u.name}: ${u.description}`).join(`
|
|
25
35
|
`);n.push("",`<skills>
|
|
26
36
|
${l}
|
|
27
|
-
</skills>`),s.push({name:"skills",included:!0})}else s.push({name:"skills",included:!1,reason:"No skills loaded."});let c=await this.#
|
|
37
|
+
</skills>`),s.push({name:"skills",included:!0})}else s.push({name:"skills",included:!1,reason:"No skills loaded."});let c=await this.#r(e.runtime?.workspace);c.length>0?(n.push("",`<workspace>${c.join(`
|
|
28
38
|
`)}
|
|
29
|
-
</workspace>`),s.push({name:"workspace",included:!0})):this.#e.length>0&&s.push({name:"workspace",included:!1,reason:"No workspace prompt files found."})
|
|
30
|
-
|
|
39
|
+
</workspace>`),s.push({name:"workspace",included:!0})):this.#e.length>0&&s.push({name:"workspace",included:!1,reason:"No workspace prompt files found."}),e.documentationPolicy!==void 0&&e.documentationPolicy.length>0?(n.push("",`<documentation>
|
|
40
|
+
${e.documentationPolicy}
|
|
41
|
+
</documentation>`),s.push({name:"documentation",included:!0})):s.push({name:"documentation",included:!1,reason:"No documentationPolicy provided."}),e.selfUpdatePolicy!==void 0&&e.selfUpdatePolicy.length>0?(n.push("",`<self-update>
|
|
42
|
+
${e.selfUpdatePolicy}
|
|
43
|
+
</self-update>`),s.push({name:"self_update",included:!0})):s.push({name:"self_update",included:!1,reason:"No selfUpdatePolicy provided."})}let o=e.recentMessages??[];o.length>0&&s.push({name:"conversation_history",included:!0}),s.push({name:"user_message",included:!0});let i=s.filter(c=>c.included).map(c=>c.name),a=s.filter(c=>!c.included).map(c=>c.name);return{modelInput:{messages:[{role:"system",content:n.join(`
|
|
44
|
+
`)},...o.map(c=>({...c})),{role:"user",content:e.userMessage}]},report:{includedSections:i,omittedSections:a,sections:s}}}async#r(e){if(e===void 0||this.#e.length===0)return[];let r=[];for(let s of this.#e)try{let o=(await this.#t(Qf(e,s))).trim();o.length>0&&r.push("",`### ${s}`,o)}catch(n){if(Zf(n)&&n.code==="ENOENT")continue;throw n}return r}};function Zf(t){return t instanceof Error&&"code"in t}var oo="Before this conversation is compressed, take this opportunity to record any durable facts the user will care about across sessions. Prefer the append_daily_memory tool when it is available. Skip if there is nothing worth preserving.",io={maxTokens:6e4,maxMessages:400,keepRecent:12,summarySystemPrompt:"You are a context distiller for an AI agent. The conversation history has grown too long and must be reduced. Extract only what the agent needs to continue working: tools called and their key outcomes, decisions reached, important facts discovered, files created or modified, errors encountered, and the current task state. Discard pleasantries, repetition, and details that no longer affect the agent's ability to proceed. Output concise factual statements only.",memoryFlush:{enabled:!0,prompt:oo}};function ao(t){let e=0;for(let r of t)typeof r.content=="string"&&(e+=r.content.length),r.toolCalls!==void 0&&(e+=JSON.stringify(r.toolCalls).length),r.toolCallId!==void 0&&(e+=r.toolCallId.length);return Math.ceil(e/4)}async function ec(t,e,r){let s={...io,...r};if(!(ao(t)>s.maxTokens||t.length>s.maxMessages))return t;let o=t[0]?.role==="system"?t[0]:void 0,i=o!==void 0?t.slice(1):t,a=i.slice(0,i.length-s.keepRecent),c=i.slice(-s.keepRecent);if(a.length===0)return t;let l=a.map(eh),u=[...o!==void 0?[o]:[],...l,...c],d=l.map(p=>`${p.role.toUpperCase()}: ${p.content??"(tool call)"}`).join(`
|
|
31
45
|
`);try{let p=await e.generate({messages:[{role:"system",content:s.summarySystemPrompt},{role:"user",content:`Conversation to distil:
|
|
32
46
|
|
|
33
47
|
${d}`}]});return p.type!=="message"||!p.content?u:[...o!==void 0?[o]:[],{role:"system",content:`Conversation summary:
|
|
34
|
-
${p.content}`},...c]}catch{return u}}function
|
|
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 b(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
|
|
36
|
-
`):[]}};
|
|
37
|
-
`,"\r"]);
|
|
38
|
-
`);s.enqueue(i)}catch(n){s.error(n)}},async cancel(){await r.return?.()}})}};async function*
|
|
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]=
|
|
48
|
+
${p.content}`},...c]}catch{return u}}function eh(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)}
|
|
49
|
+
[${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 b(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 co=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return co=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 Se(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var yr=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 E=class extends Error{},H=class t extends E{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 Oe({message:s,cause:yr(r)});let o=r,i=o?.error?.type;return e===400?new vt(e,o,s,n,i):e===401?new kt(e,o,s,n,i):e===403?new Tt(e,o,s,n,i):e===404?new Rt(e,o,s,n,i):e===409?new At(e,o,s,n,i):e===422?new It(e,o,s,n,i):e===429?new Pt(e,o,s,n,i):e>=500?new Ot(e,o,s,n,i):new t(e,o,s,n,i)}},G=class extends H{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Oe=class extends H{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},xt=class extends Oe{constructor({message:e}={}){super({message:e??"Request timed out."})}},vt=class extends H{},kt=class extends H{},Tt=class extends H{},Rt=class extends H{},At=class extends H{},It=class extends H{},Pt=class extends H{},Ot=class extends H{};var rh=/^[a-z][a-z0-9+.-]*:/i,tc=t=>rh.test(t),lo=t=>(lo=Array.isArray,lo(t)),uo=lo;function bs(t){return typeof t!="object"?{}:t??{}}function fo(t){if(!t)return!0;for(let e in t)return!1;return!0}function rc(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var sc=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new E(`${t} must be an integer`);if(e<0)throw new E(`${t} must be a positive integer`);return e};var ws=t=>{try{return JSON.parse(t)}catch{return}};var nc=t=>new Promise(e=>setTimeout(e,t));var Me="0.92.0";var cc=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function sh(){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 nh=()=>{let t=sh();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Me,"X-Stainless-OS":ic(Deno.build.os),"X-Stainless-Arch":oc(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":Me,"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":Me,"X-Stainless-OS":ic(globalThis.process.platform??"unknown"),"X-Stainless-Arch":oc(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=oh();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Me,"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":Me,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function oh(){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 oc=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",ic=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"),ac,lc=()=>ac??(ac=nh());function uc(){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 ho(...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 Es(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return ho({start(){},async pull(r){let{done:s,value:n}=await e.next();s?r.close():r.enqueue(n)},async cancel(){await e.return?.()}})}function _r(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 dc(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 fc=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function hc(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 E(`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 gc(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 pc;function br(t){let e;return(pc??(e=new globalThis.TextEncoder,pc=e.encode.bind(e)))(t)}var mc;function po(t){let e;return(mc??(e=new globalThis.TextDecoder,mc=e.decode.bind(e)))(t)}var ee,te,xe=class{constructor(){ee.set(this,void 0),te.set(this,void 0),b(this,ee,new Uint8Array,"f"),b(this,te,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?br(e):e;b(this,ee,gc([f(this,ee,"f"),r]),"f");let s=[],n;for(;(n=ch(f(this,ee,"f"),f(this,te,"f")))!=null;){if(n.carriage&&f(this,te,"f")==null){b(this,te,n.index,"f");continue}if(f(this,te,"f")!=null&&(n.index!==f(this,te,"f")+1||n.carriage)){s.push(po(f(this,ee,"f").subarray(0,f(this,te,"f")-1))),b(this,ee,f(this,ee,"f").subarray(f(this,te,"f")),"f"),b(this,te,null,"f");continue}let o=f(this,te,"f")!==null?n.preceding-1:n.preceding,i=po(f(this,ee,"f").subarray(0,o));s.push(i),b(this,ee,f(this,ee,"f").subarray(n.index),"f"),b(this,te,null,"f")}return s}flush(){return f(this,ee,"f").length?this.decode(`
|
|
50
|
+
`):[]}};ee=new WeakMap,te=new WeakMap;xe.NEWLINE_CHARS=new Set([`
|
|
51
|
+
`,"\r"]);xe.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function ch(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 yc(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 xs={off:0,error:200,warn:300,info:400,debug:500},mo=(t,e,r)=>{if(t){if(rc(xs,t))return t;W(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(xs))}`)}};function wr(){}function Ss(t,e,r){return!e||xs[t]>xs[r]?wr:e[t].bind(e)}var lh={error:wr,warn:wr,info:wr,debug:wr},_c=new WeakMap;function W(t){let e=t.logger,r=t.logLevel??"off";if(!e)return lh;let s=_c.get(e);if(s&&s[0]===r)return s[1];let n={error:Ss("error",e,r),warn:Ss("warn",e,r),info:Ss("info",e,r),debug:Ss("debug",e,r)};return _c.set(e,[r,n]),n}var ve=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 Er,he=class t{constructor(e,r,s){this.iterator=e,Er.set(this,void 0),this.controller=r,b(this,Er,s,"f")}static fromSSEResponse(e,r,s){let n=!1,o=s?W(s):console;async function*i(){if(n)throw new E("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(let c of uh(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=ws(c.data)??c.data,u=l?.error?.type;throw new H(void 0,l,void 0,e.headers,u)}}a=!0}catch(c){if(Se(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 xe,c=_r(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 E("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(Se(c))return;throw c}finally{a||r.abort()}}return new t(i,r,s)}[(Er=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,Er,"f")),new t(()=>n(r),this.controller,f(this,Er,"f"))]}toReadableStream(){let e=this,r;return ho({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=br(JSON.stringify(n)+`
|
|
52
|
+
`);s.enqueue(i)}catch(n){s.error(n)}},async cancel(){await r.return?.()}})}};async function*uh(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new E("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 E("Attempted to iterate over a response with no body");let r=new go,s=new xe,n=_r(t.body);for await(let o of dh(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*dh(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"?br(r):r,n=new Uint8Array(e.length+s.length);n.set(e),n.set(s,e.length),e=n;let o;for(;(o=yc(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var go=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(`
|
|
53
|
+
`),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]=fh(e,":");return n.startsWith(" ")&&(n=n.substring(1)),r==="event"?this.event=n:r==="data"&&this.data.push(n),null}};function fh(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function vs(t,e){let{response:r,requestLogID:s,retryOfRequestLogID:n,startTime:o}=e,i=await(async()=>{if(e.options.stream)return W(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller):he.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 yo(p,r)}return await r.text()})();return W(t).debug(`[${s}] response parsed`,ve({retryOfRequestLogID:n,url:r.url,status:r.status,body:i,durationMs:Date.now()-o})),i}function yo(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 Sr,Xe=class t extends Promise{constructor(e,r,s=vs){super(n=>{n(null)}),this.responsePromise=r,this.parseResponse=s,Sr.set(this,void 0),b(this,Sr,e,"f")}_thenUnwrap(e){return new t(f(this,Sr,"f"),this.responsePromise,async(r,s)=>yo(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,Sr,"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)}};Sr=new WeakMap;var ks,Ts=class{constructor(e,r,s,n){ks.set(this,void 0),b(this,ks,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 E("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await f(this,ks,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ks=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},xr=class extends Xe{constructor(e,r,s){super(e,r,async(n,o)=>new s(n,o.response,await vs(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},oe=class extends Ts{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:{...bs(this.options.query),before_id:r}}:null}let e=this.last_id;return e?{...this.options,query:{...bs(this.options.query),after_id:e}}:null}};var P=class extends Ts{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:{...bs(this.options.query),page:e}}:null}};var bo=()=>{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 Ye(t,e,r){return bo(),new File(t,e??"unknown_file",r)}function vr(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 wo=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function";var Mt=async(t,e,r=!0)=>({...t,body:await mh(t.body,e,r)}),bc=new WeakMap;function ph(t){let e=typeof t=="function"?t:t.fetch,r=bc.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 bc.set(e,s),s}var mh=async(t,e,r=!0)=>{if(!await ph(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])=>_o(s,n,o,r))),s},gh=t=>t instanceof Blob&&"name"in t;var _o=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,Ye([await r.blob()],vr(r,s),n))}else if(wo(r))t.append(e,Ye([await new Response(Es(r)).blob()],vr(r,s)));else if(gh(r))t.append(e,Ye([r],vr(r,s),{type:r.type}));else if(Array.isArray(r))await Promise.all(r.map(n=>_o(t,e+"[]",n,s)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>_o(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 wc=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",yh=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&wc(t),_h=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function Rs(t,e,r){if(bo(),t=await t,e||(e=vr(t,!0)),yh(t))return t instanceof File&&e==null&&r==null?t:Ye([await t.arrayBuffer()],e??t.name,{type:t.type,lastModified:t.lastModified,...r});if(_h(t)){let n=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Ye(await Eo(n),e,r)}let s=await Eo(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 Ye(s,e,r)}async function Eo(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(wc(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(wo(t))for await(let r of t)e.push(...await Eo(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${bh(t)}`)}return e}function bh(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var T=class{constructor(e){this._client=e}};var Ec=Symbol.for("brand.privateNullableHeaders");function*Eh(t){if(!t)return;if(Ec 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():uo(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=uo(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 Eh(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{[Ec]:!0,values:e,nulls:r}};function xc(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Sc=Object.freeze(Object.create(null)),Sh=(t=xc)=>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??Sc)??Sc)?.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),y="^".repeat(h.length);return u=h.start+h.length,p+g+y},"");throw new E(`Path parameters result in path with invalid segments:
|
|
40
54
|
${o.map(p=>p.error).join(`
|
|
41
55
|
`)}
|
|
42
56
|
${i}
|
|
43
|
-
${d}`)}return i},_=sf(Wa);var Et=class extends v{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(_`/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(_`/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",A,{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(_`/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(_`/v1/environments/${e}/archive?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};var mr=Symbol("anthropic.sdk.stainlessHelper");function ms(t){return typeof t=="object"&&t!==null&&mr in t}function Yn(t,e){let r=new Set;if(t)for(let s of t)ms(s)&&r.add(s[mr]);if(e){for(let s of e)if(ms(s)&&r.add(s[mr]),Array.isArray(s.content))for(let n of s.content)ms(n)&&r.add(n[mr])}return Array.from(r)}function gs(t,e){let r=Yn(t,e);return r.length===0?{}:{"x-stainless-helper":r.join(", ")}}function Va(t){return ms(t)?{"x-stainless-helper":t[mr]}:{}}var kt=class extends v{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(_`/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(_`/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(_`/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()},Va(n.file),r?.headers])},this._client))}};var Rt=class extends v{retrieve(e,r={},s){let{betas:n}=r??{};return this._client.get(_`/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 v{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(_`/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(_`/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",A,{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(_`/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 v{list(e,r={},s){let{betas:n,...o}=r??{};return this._client.getAPIList(_`/v1/agents/${e}/versions?beta=true`,A,{query:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};var Ve=class extends v{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(_`/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(_`/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",A,{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(_`/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 v{create(e,r,s){let{view:n,betas:o,...i}=r;return this._client.post(_`/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(_`/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(_`/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(_`/v1/memory_stores/${e}/memories?beta=true`,A,{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(_`/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 v{retrieve(e,r,s){let{memory_store_id:n,betas:o,...i}=r;return this._client.get(_`/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(_`/v1/memory_stores/${e}/memory_versions?beta=true`,A,{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(_`/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 v{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(_`/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(_`/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",A,{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(_`/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(_`/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(cr(e.body),r)}};var Mt=class extends v{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(_`/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(_`/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(_`/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 ys={"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 Ga(t){return t?.output_format??t?.output_config?.format}function Xn(t,e,r){let s=Ga(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=mf(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 mf(t,e){let r=Ga(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 gf=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},yf=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},_f=t=>{let e="";return t.map(r=>{r.type==="string"?e+='"'+r.value+'"':e+=r.value}),e},_s=t=>JSON.parse(_f(yf(Ct(gf(t)))));var ne,Ae,Nt,gr,bs,yr,_r,ws,br,_e,wr,xs,Ss,Ge,vs,Es,xr,Zn,Ka,ks,eo,to,ro,za,Ja="__json_buf";function Ya(t){return t.type==="tool_use"||t.type==="server_tool_use"||t.type==="mcp_tool_use"}var Rs=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,gr.set(this,void 0),bs.set(this,()=>{}),yr.set(this,()=>{}),_r.set(this,void 0),ws.set(this,()=>{}),br.set(this,()=>{}),_e.set(this,{}),wr.set(this,!1),xs.set(this,!1),Ss.set(this,!1),Ge.set(this,!1),vs.set(this,void 0),Es.set(this,void 0),xr.set(this,void 0),ks.set(this,s=>{if(b(this,xs,!0,"f"),me(s)&&(s=new F),s instanceof F)return b(this,Ss,!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)))}),b(this,gr,new Promise((s,n)=>{b(this,bs,s,"f"),b(this,yr,n,"f")}),"f"),b(this,_r,new Promise((s,n)=>{b(this,ws,s,"f"),b(this,br,n,"f")}),"f"),f(this,gr,"f").catch(()=>{}),f(this,_r,"f").catch(()=>{}),b(this,Nt,e,"f"),b(this,xr,r?.logger??console,"f")}get response(){return f(this,vs,"f")}get request_id(){return f(this,Es,"f")}async withResponse(){b(this,Ge,!0,"f");let e=await f(this,gr,"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 b(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,ks,"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||(b(this,vs,e,"f"),b(this,Es,e?.headers.get("request-id"),"f"),f(this,bs,"f").call(this,e),this._emit("connect"))}get ended(){return f(this,wr,"f")}get errored(){return f(this,xs,"f")}get aborted(){return f(this,Ss,"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)=>{b(this,Ge,!0,"f"),e!=="error"&&this.once("error",s),this.once(e,r)})}async done(){b(this,Ge,!0,"f"),await f(this,_r,"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",Ka).call(this)}_emit(e,...r){if(f(this,wr,"f"))return;e==="end"&&(b(this,wr,!0,"f"),f(this,ws,"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,yr,"f").call(this,n),f(this,br,"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,yr,"f").call(this,n),f(this,br,"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,gr=new WeakMap,bs=new WeakMap,yr=new WeakMap,_r=new WeakMap,ws=new WeakMap,br=new WeakMap,_e=new WeakMap,wr=new WeakMap,xs=new WeakMap,Ss=new WeakMap,Ge=new WeakMap,vs=new WeakMap,Es=new WeakMap,xr=new WeakMap,ks=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)},Ka=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||b(this,Ae,void 0,"f")},to=function(r){if(this.ended)return;let s=f(this,ne,"m",za).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":{Ya(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,xr,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",s.content.at(-1));break}case"message_start":{b(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 b(this,Ae,void 0,"f"),Xn(r,f(this,Nt,"f"),{logger:f(this,xr,"f")})},za=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&&Ya(n)){let o=n[Ja]||"";o+=r.delta.partial_json;let i={...n};if(Object.defineProperty(i,Ja,{value:o,enumerable:!1,writable:!0}),o)try{i.input=_s(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,ks,"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 Xa=`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:
|
|
57
|
+
${d}`)}return i},_=Sh(xc);var Ct=class extends T{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(_`/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(_`/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(_`/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(_`/v1/environments/${e}/archive?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};var kr=Symbol("anthropic.sdk.stainlessHelper");function As(t){return typeof t=="object"&&t!==null&&kr in t}function So(t,e){let r=new Set;if(t)for(let s of t)As(s)&&r.add(s[kr]);if(e){for(let s of e)if(As(s)&&r.add(s[kr]),Array.isArray(s.content))for(let n of s.content)As(n)&&r.add(n[kr])}return Array.from(r)}function Is(t,e){let r=So(t,e);return r.length===0?{}:{"x-stainless-helper":r.join(", ")}}function vc(t){return As(t)?{"x-stainless-helper":t[kr]}:{}}var Nt=class extends T{list(e={},r){let{betas:s,...n}=e??{};return this._client.getAPIList("/v1/files?beta=true",oe,{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(_`/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(_`/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(_`/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",Mt({body:n,...r,headers:m([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},vc(n.file),r?.headers])},this._client))}};var Lt=class extends T{retrieve(e,r={},s){let{betas:n}=r??{};return this._client.get(_`/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",oe,{query:n,...r,headers:m([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},r?.headers])})}};var $t=class extends T{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(_`/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(_`/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(_`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"user-profiles-2026-03-24"].toString()},s?.headers])})}};var Dt=class extends T{list(e,r={},s){let{betas:n,...o}=r??{};return this._client.getAPIList(_`/v1/agents/${e}/versions?beta=true`,P,{query:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};var Je=class extends T{constructor(){super(...arguments),this.versions=new Dt(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(_`/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(_`/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(_`/v1/agents/${e}/archive?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};Je.Versions=Dt;var jt=class extends T{create(e,r,s){let{view:n,betas:o,...i}=r;return this._client.post(_`/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(_`/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(_`/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(_`/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(_`/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 Bt=class extends T{retrieve(e,r,s){let{memory_store_id:n,betas:o,...i}=r;return this._client.get(_`/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(_`/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(_`/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 Ce=class extends T{constructor(){super(...arguments),this.memories=new jt(this._client),this.memoryVersions=new Bt(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(_`/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(_`/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(_`/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(_`/v1/memory_stores/${e}/archive?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};Ce.Memories=jt;Ce.MemoryVersions=Bt;var Ut=class t{constructor(e,r){this.iterator=e,this.controller=r}async*decoder(){let e=new xe;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 E("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 E("Attempted to iterate over a response with no body");return new t(_r(e.body),r)}};var Ft=class extends T{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(_`/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",oe,{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(_`/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(_`/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 E(`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)=>Ut.fromResponse(a.response,a.controller))}};var Ps={"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 kc(t){return t?.output_format??t?.output_config?.format}function xo(t,e,r){let s=kc(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}:vo(t,e,r)}function vo(t,e,r){let s=null,n=t.content.map(o=>{if(o.type==="text"){let i=Ch(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 Ch(t,e){let r=kc(t);if(r?.type!=="json_schema")return null;try{return"parse"in r?r.parse(e):JSON.parse(e)}catch(s){throw new E(`Failed to parse structured output: ${s}`)}}var Nh=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},qt=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),qt(t);break;case"number":let r=e.value[e.value.length-1];if(r==="."||r==="-")return t=t.slice(0,t.length-1),qt(t);case"string":let s=t[t.length-2];if(s?.type==="delimiter")return t=t.slice(0,t.length-1),qt(t);if(s?.type==="brace"&&s.value==="{")return t=t.slice(0,t.length-1),qt(t);break;case"delimiter":return t=t.slice(0,t.length-1),qt(t);break}return t},Lh=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},$h=t=>{let e="";return t.map(r=>{r.type==="string"?e+='"'+r.value+'"':e+=r.value}),e},Os=t=>JSON.parse($h(Lh(qt(Nh(t)))));var ie,Ne,Ht,Tr,Ms,Rr,Ar,Cs,Ir,ke,Pr,Ns,Ls,Qe,$s,Ds,Or,ko,Tc,js,To,Ro,Ao,Rc,Ac="__json_buf";function Ic(t){return t.type==="tool_use"||t.type==="server_tool_use"||t.type==="mcp_tool_use"}var Bs=class t{constructor(e,r){ie.add(this),this.messages=[],this.receivedMessages=[],Ne.set(this,void 0),Ht.set(this,null),this.controller=new AbortController,Tr.set(this,void 0),Ms.set(this,()=>{}),Rr.set(this,()=>{}),Ar.set(this,void 0),Cs.set(this,()=>{}),Ir.set(this,()=>{}),ke.set(this,{}),Pr.set(this,!1),Ns.set(this,!1),Ls.set(this,!1),Qe.set(this,!1),$s.set(this,void 0),Ds.set(this,void 0),Or.set(this,void 0),js.set(this,s=>{if(b(this,Ns,!0,"f"),Se(s)&&(s=new G),s instanceof G)return b(this,Ls,!0,"f"),this._emit("abort",s);if(s instanceof E)return this._emit("error",s);if(s instanceof Error){let n=new E(s.message);return n.cause=s,this._emit("error",n)}return this._emit("error",new E(String(s)))}),b(this,Tr,new Promise((s,n)=>{b(this,Ms,s,"f"),b(this,Rr,n,"f")}),"f"),b(this,Ar,new Promise((s,n)=>{b(this,Cs,s,"f"),b(this,Ir,n,"f")}),"f"),f(this,Tr,"f").catch(()=>{}),f(this,Ar,"f").catch(()=>{}),b(this,Ht,e,"f"),b(this,Or,r?.logger??console,"f")}get response(){return f(this,$s,"f")}get request_id(){return f(this,Ds,"f")}async withResponse(){b(this,Qe,!0,"f");let e=await f(this,Tr,"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 b(o,Ht,{...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,js,"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,ie,"m",To).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,ie,"m",Ro).call(this,c);if(a.controller.signal?.aborted)throw new G;f(this,ie,"m",Ao).call(this)}finally{n&&o&&n.removeEventListener("abort",o)}}_connected(e){this.ended||(b(this,$s,e,"f"),b(this,Ds,e?.headers.get("request-id"),"f"),f(this,Ms,"f").call(this,e),this._emit("connect"))}get ended(){return f(this,Pr,"f")}get errored(){return f(this,Ns,"f")}get aborted(){return f(this,Ls,"f")}abort(){this.controller.abort()}on(e,r){return(f(this,ke,"f")[e]||(f(this,ke,"f")[e]=[])).push({listener:r}),this}off(e,r){let s=f(this,ke,"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,ke,"f")[e]||(f(this,ke,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,s)=>{b(this,Qe,!0,"f"),e!=="error"&&this.once("error",s),this.once(e,r)})}async done(){b(this,Qe,!0,"f"),await f(this,Ar,"f")}get currentMessage(){return f(this,Ne,"f")}async finalMessage(){return await this.done(),f(this,ie,"m",ko).call(this)}async finalText(){return await this.done(),f(this,ie,"m",Tc).call(this)}_emit(e,...r){if(f(this,Pr,"f"))return;e==="end"&&(b(this,Pr,!0,"f"),f(this,Cs,"f").call(this));let s=f(this,ke,"f")[e];if(s&&(f(this,ke,"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,Rr,"f").call(this,n),f(this,Ir,"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,Rr,"f").call(this,n),f(this,Ir,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",f(this,ie,"m",ko).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,ie,"m",To).call(this),this._connected(null);let o=he.fromReadableStream(e,this.controller);for await(let i of o)f(this,ie,"m",Ro).call(this,i);if(o.controller.signal?.aborted)throw new G;f(this,ie,"m",Ao).call(this)}finally{s&&n&&s.removeEventListener("abort",n)}}[(Ne=new WeakMap,Ht=new WeakMap,Tr=new WeakMap,Ms=new WeakMap,Rr=new WeakMap,Ar=new WeakMap,Cs=new WeakMap,Ir=new WeakMap,ke=new WeakMap,Pr=new WeakMap,Ns=new WeakMap,Ls=new WeakMap,Qe=new WeakMap,$s=new WeakMap,Ds=new WeakMap,Or=new WeakMap,js=new WeakMap,ie=new WeakSet,ko=function(){if(this.receivedMessages.length===0)throw new E("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Tc=function(){if(this.receivedMessages.length===0)throw new E("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 E("stream ended without producing a content block with type=text");return r.join(" ")},To=function(){this.ended||b(this,Ne,void 0,"f")},Ro=function(r){if(this.ended)return;let s=f(this,ie,"m",Rc).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":{Ic(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(xo(s,f(this,Ht,"f"),{logger:f(this,Or,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",s.content.at(-1));break}case"message_start":{b(this,Ne,s,"f");break}case"content_block_start":case"message_delta":break}},Ao=function(){if(this.ended)throw new E("stream has ended, this shouldn't happen");let r=f(this,Ne,"f");if(!r)throw new E("request ended without sending any chunks");return b(this,Ne,void 0,"f"),xo(r,f(this,Ht,"f"),{logger:f(this,Or,"f")})},Rc=function(r){let s=f(this,Ne,"f");if(r.type==="message_start"){if(s)throw new E(`Unexpected event order, got ${r.type} before receiving "message_stop"`);return r.message}if(!s)throw new E(`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&&Ic(n)){let o=n[Ac]||"";o+=r.delta.partial_json;let i={...n};if(Object.defineProperty(i,Ac,{value:o,enumerable:!1,writable:!0}),o)try{i.input=Os(o)}catch(a){let c=new E(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${a}. JSON: ${o}`);f(this,js,"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 he(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Ze=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 Pc=`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
58
|
1. Task Overview
|
|
45
59
|
The user's core request and success criteria
|
|
46
60
|
Any clarifications or constraints they specified
|
|
@@ -62,25 +76,48 @@ User preferences or style requirements
|
|
|
62
76
|
Domain-specific details that aren't obvious
|
|
63
77
|
Any promises made to the user
|
|
64
78
|
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
|
|
66
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),xf.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=ys[o.model]??void 0;i=this._client.calculateNonstreamingTimeout(o.max_tokens,c)}let a=gs(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 Rs.createMessage(this,e,r)}countTokens(e,r){let s=tc(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 tc(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 v{list(e,r={},s){let{betas:n,...o}=r??{};return this._client.getAPIList(_`/v1/sessions/${e}/events?beta=true`,A,{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(_`/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(_`/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 v{retrieve(e,r,s){let{session_id:n,betas:o}=r;return this._client.get(_`/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(_`/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(_`/v1/sessions/${e}/resources?beta=true`,A,{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(_`/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(_`/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 v{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(_`/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(_`/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",A,{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(_`/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(_`/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 v{create(e,r={},s){let{betas:n,...o}=r??{};return this._client.post(_`/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(_`/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(_`/v1/skills/${e}/versions?beta=true`,A,{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(_`/v1/skills/${n}/versions/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},s?.headers])})}};var Je=class extends v{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(_`/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",A,{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(_`/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 v{create(e,r,s){let{betas:n,...o}=r;return this._client.post(_`/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(_`/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(_`/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(_`/v1/vaults/${e}/credentials?beta=true`,A,{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(_`/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(_`/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 v{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(_`/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(_`/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",A,{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(_`/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(_`/v1/vaults/${e}/archive?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};Ye.Credentials=Ut;var q=class extends v{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)}};q.Models=Rt;q.Messages=we;q.Agents=Ve;q.Environments=Et;q.Sessions=Ie;q.Vaults=Ye;q.MemoryStores=Te;q.Files=kt;q.Skills=Je;q.UserProfiles=Pt;var Xe=class extends v{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 rc(t){return t?.output_config?.format}function no(t,e,r){let s=rc(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=Of(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 Of(t,e){let r=rc(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,Ft,Er,Ps,kr,Rr,Ts,Pr,xe,Tr,As,Os,Qe,Is,Ms,Ar,io,sc,ao,co,lo,uo,nc,oc="__json_buf";function ic(t){return t.type==="tool_use"||t.type==="server_tool_use"}var Cs=class t{constructor(e,r){oe.add(this),this.messages=[],this.receivedMessages=[],Me.set(this,void 0),Ft.set(this,null),this.controller=new AbortController,Er.set(this,void 0),Ps.set(this,()=>{}),kr.set(this,()=>{}),Rr.set(this,void 0),Ts.set(this,()=>{}),Pr.set(this,()=>{}),xe.set(this,{}),Tr.set(this,!1),As.set(this,!1),Os.set(this,!1),Qe.set(this,!1),Is.set(this,void 0),Ms.set(this,void 0),Ar.set(this,void 0),ao.set(this,s=>{if(b(this,As,!0,"f"),me(s)&&(s=new F),s instanceof F)return b(this,Os,!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)))}),b(this,Er,new Promise((s,n)=>{b(this,Ps,s,"f"),b(this,kr,n,"f")}),"f"),b(this,Rr,new Promise((s,n)=>{b(this,Ts,s,"f"),b(this,Pr,n,"f")}),"f"),f(this,Er,"f").catch(()=>{}),f(this,Rr,"f").catch(()=>{}),b(this,Ft,e,"f"),b(this,Ar,r?.logger??console,"f")}get response(){return f(this,Is,"f")}get request_id(){return f(this,Ms,"f")}async withResponse(){b(this,Qe,!0,"f");let e=await f(this,Er,"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 b(o,Ft,{...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||(b(this,Is,e,"f"),b(this,Ms,e?.headers.get("request-id"),"f"),f(this,Ps,"f").call(this,e),this._emit("connect"))}get ended(){return f(this,Tr,"f")}get errored(){return f(this,As,"f")}get aborted(){return f(this,Os,"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)=>{b(this,Qe,!0,"f"),e!=="error"&&this.once("error",s),this.once(e,r)})}async done(){b(this,Qe,!0,"f"),await f(this,Rr,"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",sc).call(this)}_emit(e,...r){if(f(this,Tr,"f"))return;e==="end"&&(b(this,Tr,!0,"f"),f(this,Ts,"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,kr,"f").call(this,n),f(this,Pr,"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,kr,"f").call(this,n),f(this,Pr,"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,Ft=new WeakMap,Er=new WeakMap,Ps=new WeakMap,kr=new WeakMap,Rr=new WeakMap,Ts=new WeakMap,Pr=new WeakMap,xe=new WeakMap,Tr=new WeakMap,As=new WeakMap,Os=new WeakMap,Qe=new WeakMap,Is=new WeakMap,Ms=new WeakMap,Ar=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)},sc=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||b(this,Me,void 0,"f")},lo=function(r){if(this.ended)return;let s=f(this,oe,"m",nc).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":{ic(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,Ft,"f"),{logger:f(this,Ar,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",s.content.at(-1));break}case"message_start":{b(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 b(this,Me,void 0,"f"),no(r,f(this,Ft,"f"),{logger:f(this,Ar,"f")})},nc=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&&ic(n)){let o=n[oc]||"";o+=r.delta.partial_json;let i={...n};Object.defineProperty(i,oc,{value:o,enumerable:!1,writable:!0}),o&&(i.input=_s(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 qt=class extends v{create(e,r){return this._client.post("/v1/messages/batches",{body:e,...r})}retrieve(e,r){return this._client.get(_`/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(_`/v1/messages/batches/${e}`,r)}cancel(e,r){return this._client.post(_`/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 v{constructor(){super(...arguments),this.batches=new qt(this._client)}create(e,r){e.model in ac&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${ac[e.model]}
|
|
67
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),
|
|
79
|
+
Wrap your summary in <summary></summary> tags.`;var Mr,Wt,et,F,Q,re,Te,Le,Cr,Oc,Io;function Mc(){let t,e;return{promise:new Promise((s,n)=>{t=s,e=n}),resolve:t,reject:e}}var Vt=class{constructor(e,r,s){Mr.add(this),this.client=e,Wt.set(this,!1),et.set(this,!1),F.set(this,void 0),Q.set(this,void 0),re.set(this,void 0),Te.set(this,void 0),Le.set(this,void 0),Cr.set(this,0),b(this,F,{params:{...r,messages:structuredClone(r.messages)}},"f");let o=["BetaToolRunner",...So(r.tools,r.messages)].join(", ");b(this,Q,{...s,headers:m([{"x-stainless-helper":o},s?.headers])},"f"),b(this,Le,Mc(),"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*[(Wt=new WeakMap,et=new WeakMap,F=new WeakMap,Q=new WeakMap,re=new WeakMap,Te=new WeakMap,Le=new WeakMap,Cr=new WeakMap,Mr=new WeakSet,Oc=async function(){let r=f(this,F,"f").params.compactionControl;if(!r||!r.enabled)return!1;let s=0;if(f(this,re,"f")!==void 0)try{let l=await f(this,re,"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,F,"f").params.model,i=r.summaryPrompt??Pc,a=f(this,F,"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,F,"f").params.max_tokens},{signal:f(this,Q,"f").signal,headers:m([f(this,Q,"f").headers,{"x-stainless-helper":"compaction"}])});if(c.content[0]?.type!=="text")throw new E("Expected text response for compaction");return f(this,F,"f").params.messages=[{role:"user",content:c.content}],!0},Symbol.asyncIterator)](){var e;if(f(this,Wt,"f"))throw new E("Cannot iterate over a consumed stream");b(this,Wt,!0,"f"),b(this,et,!0,"f"),b(this,Te,void 0,"f");try{for(;;){let r;try{if(f(this,F,"f").params.max_iterations&&f(this,Cr,"f")>=f(this,F,"f").params.max_iterations)break;b(this,et,!1,"f"),b(this,Te,void 0,"f"),b(this,Cr,(e=f(this,Cr,"f"),e++,e),"f"),b(this,re,void 0,"f");let{max_iterations:s,compactionControl:n,...o}=f(this,F,"f").params;if(o.stream?(r=this.client.beta.messages.stream({...o},f(this,Q,"f")),b(this,re,r.finalMessage(),"f"),f(this,re,"f").catch(()=>{}),yield r):(b(this,re,this.client.beta.messages.create({...o,stream:!1},f(this,Q,"f")),"f"),yield f(this,re,"f")),!await f(this,Mr,"m",Oc).call(this)){if(!f(this,et,"f")){let{role:c,content:l}=await f(this,re,"f");f(this,F,"f").params.messages.push({role:c,content:l})}let a=await f(this,Mr,"m",Io).call(this,f(this,F,"f").params.messages.at(-1));if(a)f(this,F,"f").params.messages.push(a);else if(!f(this,et,"f"))break}}finally{r&&r.abort()}}if(!f(this,re,"f"))throw new E("ToolRunner concluded without a message from the server");f(this,Le,"f").resolve(await f(this,re,"f"))}catch(r){throw b(this,Wt,!1,"f"),f(this,Le,"f").promise.catch(()=>{}),f(this,Le,"f").reject(r),b(this,Le,Mc(),"f"),r}}setMessagesParams(e){typeof e=="function"?f(this,F,"f").params=e(f(this,F,"f").params):f(this,F,"f").params=e,b(this,et,!0,"f"),b(this,Te,void 0,"f")}setRequestOptions(e){typeof e=="function"?b(this,Q,e(f(this,Q,"f")),"f"):b(this,Q,{...f(this,Q,"f"),...e},"f")}async generateToolResponse(e=f(this,Q,"f").signal){let r=await f(this,re,"f")??this.params.messages.at(-1);return r?f(this,Mr,"m",Io).call(this,r,e):null}done(){return f(this,Le,"f").promise}async runUntilDone(){if(!f(this,Wt,"f"))for await(let e of this);return this.done()}get params(){return f(this,F,"f").params}pushMessages(...e){this.setMessagesParams(r=>({...r,messages:[...r.messages,...e]}))}then(e,r){return this.runUntilDone().then(e,r)}};Io=async function(e,r=f(this,Q,"f").signal){return f(this,Te,"f")!==void 0?f(this,Te,"f"):(b(this,Te,jh(f(this,F,"f").params,e,{...f(this,Q,"f"),signal:r}),"f"),f(this,Te,"f"))};async function jh(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 Ze?a.content:`Error: ${a instanceof Error?a.message:String(a)}`,is_error:!0}}}))}}var Cc={"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"},Bh=["claude-mythos-preview","claude-opus-4-6"],Re=class extends T{constructor(){super(...arguments),this.batches=new Ft(this._client)}create(e,r){let s=Nc(e),{betas:n,...o}=s;o.model in Cc&&console.warn(`The model '${o.model}' is deprecated and will reach end-of-life on ${Cc[o.model]}
|
|
80
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),Bh.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=Ps[o.model]??void 0;i=this._client.calculateNonstreamingTimeout(o.max_tokens,c)}let a=Is(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=>vo(s,e,{logger:this._client.logger??console}))}stream(e,r){return Bs.createMessage(this,e,r)}countTokens(e,r){let s=Nc(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 Vt(this._client,e,r)}};function Nc(t){if(!t.output_format)return t;if(t.output_config?.format)throw new E("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}}}Re.Batches=Ft;Re.BetaToolRunner=Vt;Re.ToolError=Ze;var Gt=class extends T{list(e,r={},s){let{betas:n,...o}=r??{};return this._client.getAPIList(_`/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(_`/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(_`/v1/sessions/${e}/events/stream?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers]),stream:!0})}};var Kt=class extends T{retrieve(e,r,s){let{session_id:n,betas:o}=r;return this._client.get(_`/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(_`/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(_`/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(_`/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(_`/v1/sessions/${e}/resources?beta=true`,{body:o,...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};var $e=class extends T{constructor(){super(...arguments),this.events=new Gt(this._client),this.resources=new Kt(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(_`/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(_`/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(_`/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(_`/v1/sessions/${e}/archive?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};$e.Events=Gt;$e.Resources=Kt;var zt=class extends T{create(e,r={},s){let{betas:n,...o}=r??{};return this._client.post(_`/v1/skills/${e}/versions?beta=true`,Mt({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(_`/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(_`/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(_`/v1/skills/${n}/versions/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},s?.headers])})}};var tt=class extends T{constructor(){super(...arguments),this.versions=new zt(this._client)}create(e={},r){let{betas:s,...n}=e??{};return this._client.post("/v1/skills?beta=true",Mt({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(_`/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(_`/v1/skills/${e}?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},s?.headers])})}};tt.Versions=zt;var Xt=class extends T{create(e,r,s){let{betas:n,...o}=r;return this._client.post(_`/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(_`/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(_`/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(_`/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(_`/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(_`/v1/vaults/${n}/credentials/${e}/archive?beta=true`,{...s,headers:m([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};var rt=class extends T{constructor(){super(...arguments),this.credentials=new Xt(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(_`/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(_`/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(_`/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(_`/v1/vaults/${e}/archive?beta=true`,{...s,headers:m([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},s?.headers])})}};rt.Credentials=Xt;var K=class extends T{constructor(){super(...arguments),this.models=new Lt(this._client),this.messages=new Re(this._client),this.agents=new Je(this._client),this.environments=new Ct(this._client),this.sessions=new $e(this._client),this.vaults=new rt(this._client),this.memoryStores=new Ce(this._client),this.files=new Nt(this._client),this.skills=new tt(this._client),this.userProfiles=new $t(this._client)}};K.Models=Lt;K.Messages=Re;K.Agents=Je;K.Environments=Ct;K.Sessions=$e;K.Vaults=rt;K.MemoryStores=Ce;K.Files=Nt;K.Skills=tt;K.UserProfiles=$t;var st=class extends T{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 Lc(t){return t?.output_config?.format}function Po(t,e,r){let s=Lc(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=zh(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 zh(t,e){let r=Lc(t);if(r?.type!=="json_schema")return null;try{return"parse"in r?r.parse(e):JSON.parse(e)}catch(s){throw new E(`Failed to parse structured output: ${s}`)}}var ae,De,Yt,Nr,Us,Lr,$r,Fs,Dr,Ae,jr,qs,Hs,nt,Ws,Vs,Br,Mo,$c,Co,No,Lo,$o,Dc,jc="__json_buf";function Bc(t){return t.type==="tool_use"||t.type==="server_tool_use"}var Gs=class t{constructor(e,r){ae.add(this),this.messages=[],this.receivedMessages=[],De.set(this,void 0),Yt.set(this,null),this.controller=new AbortController,Nr.set(this,void 0),Us.set(this,()=>{}),Lr.set(this,()=>{}),$r.set(this,void 0),Fs.set(this,()=>{}),Dr.set(this,()=>{}),Ae.set(this,{}),jr.set(this,!1),qs.set(this,!1),Hs.set(this,!1),nt.set(this,!1),Ws.set(this,void 0),Vs.set(this,void 0),Br.set(this,void 0),Co.set(this,s=>{if(b(this,qs,!0,"f"),Se(s)&&(s=new G),s instanceof G)return b(this,Hs,!0,"f"),this._emit("abort",s);if(s instanceof E)return this._emit("error",s);if(s instanceof Error){let n=new E(s.message);return n.cause=s,this._emit("error",n)}return this._emit("error",new E(String(s)))}),b(this,Nr,new Promise((s,n)=>{b(this,Us,s,"f"),b(this,Lr,n,"f")}),"f"),b(this,$r,new Promise((s,n)=>{b(this,Fs,s,"f"),b(this,Dr,n,"f")}),"f"),f(this,Nr,"f").catch(()=>{}),f(this,$r,"f").catch(()=>{}),b(this,Yt,e,"f"),b(this,Br,r?.logger??console,"f")}get response(){return f(this,Ws,"f")}get request_id(){return f(this,Vs,"f")}async withResponse(){b(this,nt,!0,"f");let e=await f(this,Nr,"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 b(o,Yt,{...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,Co,"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,ae,"m",No).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,ae,"m",Lo).call(this,c);if(a.controller.signal?.aborted)throw new G;f(this,ae,"m",$o).call(this)}finally{n&&o&&n.removeEventListener("abort",o)}}_connected(e){this.ended||(b(this,Ws,e,"f"),b(this,Vs,e?.headers.get("request-id"),"f"),f(this,Us,"f").call(this,e),this._emit("connect"))}get ended(){return f(this,jr,"f")}get errored(){return f(this,qs,"f")}get aborted(){return f(this,Hs,"f")}abort(){this.controller.abort()}on(e,r){return(f(this,Ae,"f")[e]||(f(this,Ae,"f")[e]=[])).push({listener:r}),this}off(e,r){let s=f(this,Ae,"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,Ae,"f")[e]||(f(this,Ae,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,s)=>{b(this,nt,!0,"f"),e!=="error"&&this.once("error",s),this.once(e,r)})}async done(){b(this,nt,!0,"f"),await f(this,$r,"f")}get currentMessage(){return f(this,De,"f")}async finalMessage(){return await this.done(),f(this,ae,"m",Mo).call(this)}async finalText(){return await this.done(),f(this,ae,"m",$c).call(this)}_emit(e,...r){if(f(this,jr,"f"))return;e==="end"&&(b(this,jr,!0,"f"),f(this,Fs,"f").call(this));let s=f(this,Ae,"f")[e];if(s&&(f(this,Ae,"f")[e]=s.filter(n=>!n.once),s.forEach(({listener:n})=>n(...r))),e==="abort"){let n=r[0];!f(this,nt,"f")&&!s?.length&&Promise.reject(n),f(this,Lr,"f").call(this,n),f(this,Dr,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=r[0];!f(this,nt,"f")&&!s?.length&&Promise.reject(n),f(this,Lr,"f").call(this,n),f(this,Dr,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",f(this,ae,"m",Mo).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,ae,"m",No).call(this),this._connected(null);let o=he.fromReadableStream(e,this.controller);for await(let i of o)f(this,ae,"m",Lo).call(this,i);if(o.controller.signal?.aborted)throw new G;f(this,ae,"m",$o).call(this)}finally{s&&n&&s.removeEventListener("abort",n)}}[(De=new WeakMap,Yt=new WeakMap,Nr=new WeakMap,Us=new WeakMap,Lr=new WeakMap,$r=new WeakMap,Fs=new WeakMap,Dr=new WeakMap,Ae=new WeakMap,jr=new WeakMap,qs=new WeakMap,Hs=new WeakMap,nt=new WeakMap,Ws=new WeakMap,Vs=new WeakMap,Br=new WeakMap,Co=new WeakMap,ae=new WeakSet,Mo=function(){if(this.receivedMessages.length===0)throw new E("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},$c=function(){if(this.receivedMessages.length===0)throw new E("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 E("stream ended without producing a content block with type=text");return r.join(" ")},No=function(){this.ended||b(this,De,void 0,"f")},Lo=function(r){if(this.ended)return;let s=f(this,ae,"m",Dc).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":{Bc(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(Po(s,f(this,Yt,"f"),{logger:f(this,Br,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",s.content.at(-1));break}case"message_start":{b(this,De,s,"f");break}case"content_block_start":case"message_delta":break}},$o=function(){if(this.ended)throw new E("stream has ended, this shouldn't happen");let r=f(this,De,"f");if(!r)throw new E("request ended without sending any chunks");return b(this,De,void 0,"f"),Po(r,f(this,Yt,"f"),{logger:f(this,Br,"f")})},Dc=function(r){let s=f(this,De,"f");if(r.type==="message_start"){if(s)throw new E(`Unexpected event order, got ${r.type} before receiving "message_stop"`);return r.message}if(!s)throw new E(`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&&Bc(n)){let o=n[jc]||"";o+=r.delta.partial_json;let i={...n};Object.defineProperty(i,jc,{value:o,enumerable:!1,writable:!0}),o&&(i.input=Os(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 he(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Jt=class extends T{create(e,r){return this._client.post("/v1/messages/batches",{body:e,...r})}retrieve(e,r){return this._client.get(_`/v1/messages/batches/${e}`,r)}list(e={},r){return this._client.getAPIList("/v1/messages/batches",oe,{query:e,...r})}delete(e,r){return this._client.delete(_`/v1/messages/batches/${e}`,r)}cancel(e,r){return this._client.post(_`/v1/messages/batches/${e}/cancel`,r)}async results(e,r){let s=await this.retrieve(e);if(!s.results_url)throw new E(`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)=>Ut.fromResponse(o.response,o.controller))}};var je=class extends T{constructor(){super(...arguments),this.batches=new Jt(this._client)}create(e,r){e.model in Uc&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Uc[e.model]}
|
|
81
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),Yh.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=Ps[e.model]??void 0;s=this._client.calculateNonstreamingTimeout(e.max_tokens,o)}let n=Is(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=>Oo(s,e,{logger:this._client.logger??console}))}stream(e,r){return Gs.createMessage(this,e,r,{logger:this._client.logger??console})}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},Uc={"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"},Yh=["claude-mythos-preview","claude-opus-4-6"];je.Batches=Jt;var ot=class extends T{retrieve(e,r={},s){let{betas:n}=r??{};return this._client.get(_`/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",oe,{query:n,...r,headers:m([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},r?.headers])})}};var Qt=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 Do,jo,Ks,Fc,qc="\\n\\nHuman:",Hc="\\n\\nAssistant:",D=class{constructor({baseURL:e=Qt("ANTHROPIC_BASE_URL"),apiKey:r=Qt("ANTHROPIC_API_KEY")??null,authToken:s=Qt("ANTHROPIC_AUTH_TOKEN")??null,...n}={}){Do.add(this),Ks.set(this,void 0);let o={apiKey:r,authToken:s,...n,baseURL:e||"https://api.anthropic.com"};if(!o.dangerouslyAllowBrowser&&cc())throw new E(`It looks like you're running in a browser-like environment.
|
|
68
82
|
|
|
69
83
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
70
84
|
If you understand the risks and have appropriate mitigations in place,
|
|
71
85
|
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
72
86
|
|
|
73
87
|
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 Na(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",cc).call(this)&&s||this.baseURL,o=Sa(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(ar),g=Date.now();if(h instanceof globalThis.Error){let E=`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"} - ${E}`),D(this).debug(`[${l}] connection ${k?"timed out":"failed"} (${E})`,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 y=[...h.headers.entries()].filter(([E])=>E==="request-id").map(([E,k])=>", "+E+": "+JSON.stringify(k)).join(""),x=`[${l}${u}${y}] ${i.method} ${a} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${g-d}ms`;if(!h.ok){let E=await this.shouldRetry(h);if(r&&E){let K=`retrying, ${r} attempts remaining`;return await Ma(h.body),D(this).info(`${x} - ${K}`),D(this).debug(`[${l}] response error (${K})`,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=E?"error; no more retries left":"error; not retryable";D(this).info(`${x} - ${k}`);let R=await h.text().catch(K=>ar(K).message),H=as(R),U=H?void 0:R;throw D(this).debug(`[${l}] response error (${k})`,ye({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,message:U,durationMs:Date.now()-d})),this.makeStatusError(h.status,H,U,h.headers)}return D(this).info(x),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 hr(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 ka(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&&Ea("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))}:{},...Oa(),...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:cs(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,Ns,"f").call(this,{body:e,headers:s})}};ho=M,Ns=new WeakMap,fo=new WeakSet,cc=function(){return this.baseURL!=="https://api.anthropic.com"};M.Anthropic=ho;M.HUMAN_PROMPT=lc;M.AI_PROMPT=uc;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=ps;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 q(this)}};ue.Completions=Xe;ue.Messages=Ce;ue.Models=Ze;ue.Beta=q;function mc(t){return"generateStream"in t&&typeof t.generateStream=="function"}var Ls=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;if(o==="tool_calls"&&a!==void 0&&a.length>0){let c=i?.content??"";return{type:"tool_calls",calls:a.map(l=>({id:l.id,name:l.function.name,input:po(l.function.arguments)})),...c?{text:c}:{},...s.usage?{usage:this.#d(s.usage)}:{}}}return{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 Nf(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)})),...n?{text:n}:{},...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*Nf(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(`
|
|
88
|
+
`);this.baseURL=o.baseURL,this.timeout=o.timeout??jo.DEFAULT_TIMEOUT,this.logger=o.logger??console;let i="warn";this.logLevel=i,this.logLevel=mo(o.logLevel,"ClientOptions.logLevel",this)??mo(Qt("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??i,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??uc(),b(this,Ks,fc,"f");let a=Qt("ANTHROPIC_CUSTOM_HEADERS");if(a){let c={};for(let l of a.split(`
|
|
89
|
+
`)){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 hc(e)}getUserAgent(){return`${this.constructor.name}/JS ${Me}`}defaultIdempotencyKey(){return`stainless-node-retry-${co()}`}makeStatusError(e,r,s,n){return H.generate(e,r,s,n)}buildURL(e,r,s){let n=!f(this,Do,"m",Fc).call(this)&&s||this.baseURL,o=tc(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),a=Object.fromEntries(o.searchParams);return(!fo(i)||!fo(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 E("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 Xe(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(W(this).debug(`[${l}] sending request`,ve({retryOfRequestLogID:s,method:n.method,url:a,options:n,headers:i.headers})),n.signal?.aborted)throw new G;let p=new AbortController,h=await this.fetchWithTimeout(a,i,c,p).catch(yr),g=Date.now();if(h instanceof globalThis.Error){let k=`retrying, ${r} attempts remaining`;if(n.signal?.aborted)throw new G;let A=Se(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(r)return W(this).info(`[${l}] connection ${A?"timed out":"failed"} - ${k}`),W(this).debug(`[${l}] connection ${A?"timed out":"failed"} (${k})`,ve({retryOfRequestLogID:s,url:a,durationMs:g-d,message:h.message})),this.retryRequest(n,r,s??l);throw W(this).info(`[${l}] connection ${A?"timed out":"failed"} - error; no more retries left`),W(this).debug(`[${l}] connection ${A?"timed out":"failed"} (error; no more retries left)`,ve({retryOfRequestLogID:s,url:a,durationMs:g-d,message:h.message})),A?new xt:new Oe({cause:h})}let y=[...h.headers.entries()].filter(([k])=>k==="request-id").map(([k,A])=>", "+k+": "+JSON.stringify(A)).join(""),w=`[${l}${u}${y}] ${i.method} ${a} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${g-d}ms`;if(!h.ok){let k=await this.shouldRetry(h);if(r&&k){let j=`retrying, ${r} attempts remaining`;return await dc(h.body),W(this).info(`${w} - ${j}`),W(this).debug(`[${l}] response error (${j})`,ve({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:g-d})),this.retryRequest(n,r,s??l,h.headers)}let A=k?"error; no more retries left":"error; not retryable";W(this).info(`${w} - ${A}`);let x=await h.text().catch(j=>yr(j).message),v=ws(x),C=v?void 0:x;throw W(this).debug(`[${l}] response error (${A})`,ve({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,message:C,durationMs:Date.now()-d})),this.makeStatusError(h.status,v,C,h.headers)}return W(this).info(w),W(this).debug(`[${l}] response start`,ve({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 xr(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 nc(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 E("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&&sc("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))}:{},...lc(),...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:Es(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,Ks,"f").call(this,{body:e,headers:s})}};jo=D,Ks=new WeakMap,Do=new WeakSet,Fc=function(){return this.baseURL!=="https://api.anthropic.com"};D.Anthropic=jo;D.HUMAN_PROMPT=qc;D.AI_PROMPT=Hc;D.DEFAULT_TIMEOUT=6e5;D.AnthropicError=E;D.APIError=H;D.APIConnectionError=Oe;D.APIConnectionTimeoutError=xt;D.APIUserAbortError=G;D.NotFoundError=Rt;D.ConflictError=At;D.RateLimitError=Pt;D.BadRequestError=vt;D.AuthenticationError=kt;D.InternalServerError=Ot;D.PermissionDeniedError=Tt;D.UnprocessableEntityError=It;D.toFile=Rs;var pe=class extends D{constructor(){super(...arguments),this.completions=new st(this),this.messages=new je(this),this.models=new ot(this),this.beta=new K(this)}};pe.Completions=st;pe.Messages=je;pe.Models=ot;pe.Beta=K;function zc(t){return"generateStream"in t&&typeof t.generateStream=="function"}var zs=class{#e;#t;#r;#o;#s;#n;constructor(e){this.#e=e.baseURL.replace(/\/+$/,""),this.#t=e.apiKey,this.#r=e.model,this.#o=e.temperature,this.#s=e.maxTokens,this.#n=e.fetch??fetch}async generate(e){try{let r=await this.#n(`${this.#e}/chat/completions`,{method:"POST",headers:this.#l(),body:JSON.stringify(this.#a(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;if(o==="tool_calls"&&a!==void 0&&a.length>0){let c=i?.content??"";return{type:"tool_calls",calls:a.map(l=>({id:l.id,name:l.function.name,input:Bo(l.function.arguments)})),...c?{text:c}:{},...s.usage?{usage:this.#f(s.usage)}:{}}}return{type:"message",content:i?.content??"",...s.usage?{usage:this.#f(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.#l(),body:JSON.stringify({...this.#a(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 Qh(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.#f(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:Bo(c.arguments)})),...n?{text:n}:{},...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}}}#l(){return{"content-type":"application/json",...this.#t?{authorization:`Bearer ${this.#t}`}:{}}}#a(e){return{model:this.#r,messages:e.messages.map(r=>this.#u(r)),...e.tools!==void 0&&e.tools.length>0?{tools:e.tools}:{},...this.#o===void 0?{}:{temperature:this.#o},...this.#s===void 0?{}:{max_tokens:this.#s}}}#u(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"}#f(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*Qh(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
90
|
`);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
|
-
|
|
79
|
-
|
|
91
|
+
`)){let o=n.trim();o.startsWith("data: ")&&(yield o.slice(6))}}finally{e.releaseLock()}}function Bo(t){try{return JSON.parse(t)}catch{return t}}var Zh={minimal:1024,low:2048,medium:4096,high:8192,max:16384},Xs=class{#e;#t;#r;#o;#s;#n;constructor(e){if(this.#r=e.model,this.#o=e.maxTokens??4096,this.#s=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 pe({apiKey:e.apiKey});this.#e=r,this.#t={messages:{stream:s=>r.messages.create({...s,stream:!0})}}}}#l(){let e=this.#n;return e===void 0||e==="off"?void 0:e==="adaptive"?{type:"adaptive"}:{type:"enabled",budget_tokens:Zh[e]}}async generate(e){try{let{system:r,messages:s}=Wc(e.messages),n=r!==void 0?[{type:"text",text:r,cache_control:{type:"ephemeral"}}]:void 0,o=this.#l(),i=await this.#e.messages.create({model:this.#r,max_tokens:this.#o,...n!==void 0?{system:n}:{},messages:s,...e.tools!==void 0&&e.tools.length>0?{tools:Vc(e.tools)}:{},...this.#s!==void 0?{temperature:this.#s}:{},...o!==void 0?{thinking:o}:{}}),a=i.content.filter(ep);if(i.stop_reason==="tool_use"&&a.length>0){let l=i.content.find(Gc);return{type:"tool_calls",calls:a.map(u=>({id:u.id,name:u.name,input:u.input})),...l?.text?{text:l.text}:{},usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}return{type:"message",content:i.content.find(Gc)?.text??"",usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}catch(r){return Kc(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}=Wc(e.messages),n=r!==void 0?[{type:"text",text:r,cache_control:{type:"ephemeral"}}]:void 0,o=this.#l(),i={model:this.#r,max_tokens:this.#o,...n!==void 0?{system:n}:{},messages:s,...e.tools!==void 0&&e.tools.length>0?{tools:Vc(e.tools)}:{},...this.#s!==void 0?{temperature:this.#s}:{},...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 y=p.get(g.index);y!==void 0&&(y.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(([y],[w])=>y-w).map(([,y])=>({id:y.id,name:y.name,input:Bo(y.inputJson)})),...c?{text:c}:{},usage:h}:yield{type:"message_done",content:c,usage:h}}catch(r){yield Kc(r)}}};function Wc(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 Vc(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 ep(t){return t.type==="tool_use"&&typeof t.id=="string"&&typeof t.name=="string"}function Gc(t){return t.type==="text"&&typeof t.text=="string"}function Kc(t){if(typeof t=="object"&&t!==null&&"status"in t&&typeof t.status=="number"){let e=t;return{type:"error",category:tp(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 tp(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"}import{exec as ex}from"child_process";import{resolve as rx,sep as sx}from"path";import{Worker as ox}from"worker_threads";var Ys=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."}}};var ix=String.raw`
|
|
92
|
+
const { parentPort, workerData } = require('node:worker_threads');
|
|
93
|
+
async function main() {
|
|
94
|
+
const start = Date.now();
|
|
95
|
+
try {
|
|
96
|
+
const fn = new Function('return (async () => { ' + workerData.command + ' })()');
|
|
97
|
+
const result = await fn();
|
|
98
|
+
parentPort.postMessage({
|
|
99
|
+
ok: true,
|
|
100
|
+
stdout: result === undefined ? '' : String(result),
|
|
101
|
+
durationMs: Date.now() - start
|
|
102
|
+
});
|
|
103
|
+
} catch (error) {
|
|
104
|
+
parentPort.postMessage({
|
|
105
|
+
ok: false,
|
|
106
|
+
stderr: error && error.message ? String(error.message) : String(error),
|
|
107
|
+
durationMs: Date.now() - start
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
main();
|
|
112
|
+
`;import{exec as rp}from"child_process";import{readdir as sp,readFile as np,stat as dx,writeFile as op,mkdir as ip}from"fs/promises";import{resolve as Xc,relative as ap,basename as cp,extname as lp,dirname as up,join as hx}from"path";function Jc(){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=Zc(t);if(r===void 0)return Zt("Tool input must include a string path.");let s=qo(e.workspaceRoot,r);if(s===void 0)return Ho();if(el(s.absolutePath))return tl();try{return{ok:!0,content:await np(s.absolutePath,"utf8"),summary:`Read file ${s.displayPath}.`}}catch(n){return Wo(n)}}}}function Qc(){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=Zc(t);if(r===void 0)return Zt("Tool input must include a string path.");let s=qo(e.workspaceRoot,r);if(s===void 0)return Ho();try{return{ok:!0,entries:(await sp(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 Wo(n)}}}}function Zc(t){if(typeof t!="object"||t===null||!("path"in t))return;let e=t.path;return typeof e=="string"?e:void 0}function qo(t,e){let r=Xc(t),s=Xc(r,e),n=ap(r,s);if(!(n.startsWith("..")||n===".."||s!==r&&n===""))return{absolutePath:s,displayPath:n===""?".":n}}function Zt(t){return{ok:!1,error:{code:"invalid_input",message:t}}}function Ho(){return{ok:!1,error:{code:"path_outside_workspace",message:"Tool path must stay inside the workspace."}}}function Wo(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 el(t){let e=cp(t).toLowerCase();if(e===".env"||e.startsWith(".env.")||e===".netrc")return!0;let r=lp(e);return r===".key"||r===".pem"||r===".p12"||r===".pfx"?!0:e==="id_rsa"||e==="id_ed25519"||e==="id_ecdsa"||e==="id_dsa"}function tl(){return{ok:!1,error:{code:"path_not_permitted",message:"Tool path is not permitted."}}}function dp(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 fp=3e4,Uo=4e3,hp=[/\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 pp(t){return hp.some(e=>e.test(t))}function Yc(t){return t.length<=Uo?t:`${t.slice(0,Uo)}
|
|
113
|
+
[truncated ${t.length-Uo} characters]`}function mp(t,e,r){return new Promise(s=>{let n=Date.now();rp(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:Yc(i),stderr:Yc(a),durationMs:c})})})}function gp(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 yp(){return{ok:!1,error:{code:"command_blocked",message:"Command matches a blocked pattern."}}}function _p(){return{ok:!1,error:{code:"sandbox_rejected",message:"Command rejected: workspace sandbox prevents execution outside workspace."}}}var bp=[/\/\.\.\//,/\bcd\s+\/(\s|$)/,/\bcd\s+~\/?(\s|$)/];function wp(t){return bp.some(e=>e.test(t))}function rl(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=gp(e);if(s===void 0)return Zt("Tool input must include a string command.");if(pp(s.command))return yp();if(t?.sandboxed===!0&&wp(s.command))return _p();let n=s.timeoutMs??fp,o=await mp(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 sl(){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=dp(t);if(r===void 0)return Zt("Tool input must include a string path and string content.");let s=qo(e.workspaceRoot,r.path);if(s===void 0)return Ho();if(el(s.absolutePath))return tl();try{return await ip(up(s.absolutePath),{recursive:!0}),await op(s.absolutePath,r.content,"utf8"),{ok:!0,summary:`Wrote file ${s.displayPath}.`}}catch(n){return Wo(n)}}}}var Fo=8e3;function Ep(t){try{let e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"?e:void 0}catch{return}}function Sp(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 xp(t){return t.length<=Fo?t:`${t.slice(0,Fo)}
|
|
114
|
+
[truncated ${t.length-Fo} characters]`}function vp(t){if(typeof t!="object"||t===null)return;let e=t.url;return typeof e=="string"?e:void 0}function nl(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=vp(e);if(s===void 0)return Zt("Tool input must include a string url.");let n=Ep(s);if(n===void 0)return Zt("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=xp(Sp(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 ol(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 il(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);return s===void 0?{ok:!1,error:`Skill "${r}" not found. Check the skills list for available names.`}:{ok:!0,content:s}}}}var px=512*1024;var Js=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)}},kp=12,Tp=2,Rp="Low-risk actions run automatically. Medium and high-risk actions require approval. Blocked actions are never permitted.",Ap="Do not restate the plan. Act now: take the first concrete tool action you can.",cl=/\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,Ip=/\b(?:done|finished|implemented|updated|fixed|changed|ran|verified|found|here(?:'s| is) what|blocked by|the blocker is)\b/i,Pp=/^(?:plan|steps?|next steps?)\s*:/im,Op=/^(?:[-*•]\s+|\d+[.)]\s+)/u,Mp=/\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,Cp=700,Qs=class{#e;#t;#r;#o;#s;#n;#l;#a;#u;#c;#f;#p;#h;#d;#g;#y;#x;#b;#w;#E;#_=[];constructor(e){this.#e=e.contextAssembler??new ys,this.#t=e.modelProvider,this.#r=e.permissionPolicy??new Ys,this.#o=e.approvalResolver,this.#l=e.maxSteps??kp,this.#x=e.executionContract??"default",this.#a=e.executionContract==="strict-agentic"?e.maxPlanningStallRetries??3:e.maxPlanningStallRetries??Tp,this.#n=e.skillIndex??[];let r=e.systemInstruction??"";this.#u=e.executionContract==="strict-agentic"?`${r}
|
|
80
115
|
|
|
81
|
-
Execution contract: strict-agentic. Act immediately. Do not narrate plans. Call tools now.`:r,this.#c=e.runtime,this.#
|
|
82
|
-
`)),
|
|
83
|
-
|
|
84
|
-
|
|
116
|
+
Execution contract: strict-agentic. Act immediately. Do not narrate plans. Call tools now.`:r,this.#c=e.runtime,this.#f=e.preferStreaming??!1,this.#p=e.compaction,this.#h=e.promptMode,this.#d=e.hooks,this.#g=e.taskStore,this.#y=e.depth??0,this.#b=e.createRunId??al("run"),this.#w=e.createEventId??al("evt"),this.#E=e.now??(()=>new Date().toISOString());let s=ol(o=>{this.#_=o}),n=e.tools??[];this.#s=new Map([s,...n].map(o=>[o.name,o]))}async*runTurn(e){let r=this.#b(),s=e.sessionId?{runId:r,sessionId:e.sessionId}:{runId:r},n=[];{if(this.#d?.beforeTurn!==void 0)try{await this.#d.beforeTurn(e)}catch(x){typeof process<"u"&&process.env.NODE_ENV!=="production"&&console.warn("[AgentRuntime] beforeTurn hook threw:",x)}let o=x=>(n.push(x),x);yield o(this.#i({...s,type:"run_started",userMessage:e.message}));let i=[];if(this.#g!==void 0&&e.sessionId!==void 0)try{let x=await this.#g.drainPendingForParent(e.sessionId);for(let v of x)i.push({role:"system",content:Np(v)})}catch(x){typeof process<"u"&&process.env.NODE_ENV!=="production"&&console.warn("[AgentRuntime] drainPendingForParent failed:",x)}let a=i.length>0?[...i,...e.recentMessages??[]]:e.recentMessages,c=this.#k(),l=await this.#e.assemble({systemInstruction:this.#u,...this.#c?{runtime:this.#c}:{},...c.length>0?{tools:c}:{},permissionGuidance:Rp,...this.#n.length>0?{skillIndex:this.#n}:{},...a?{recentMessages:a}:{},...this.#h!==void 0?{promptMode:this.#h}:{},userMessage:e.message});yield o(this.#i({...s,type:"context_assembled",messageCount:l.modelInput.messages.length,systemInstructionIncluded:l.report.includedSections.includes("identity")}));let u=this.#S(),d=l.modelInput.messages,p=0,h=0,g=!1,y="";this.#_=[];let w=[],k=l.modelInput.messages.at(-1);for(k&&w.push({...k});p<this.#l;){if(e.signal?.aborted){yield o(this.#i({...s,type:"run_failed",error:{message:"Aborted by user.",recoverable:!1}})),await this.#m(n);return}if(this.#p!==void 0){let S={...io,...this.#p},$=S.memoryFlush?.enabled!==!1;if((ao(d)>S.maxTokens||d.length>S.maxMessages)&&$){let R=await this.#v(d,S.memoryFlush?.prompt??oo);yield o(this.#i({...s,type:"memory_flush_triggered",executed:R.executed,toolsInvoked:R.toolsInvoked,...R.reason!==void 0?{reason:R.reason}:{}}))}else $||(yield o(this.#i({...s,type:"memory_flush_triggered",executed:!1,toolsInvoked:[],reason:"disabled"})));let U=d.length;d=await ec(d,this.#t,this.#p);let V=d.length;if(V<U){let R=d.find(ge=>ge.role==="system"&&typeof ge.content=="string"&&ge.content.startsWith(`Conversation summary:
|
|
117
|
+
`)),X=R&&typeof R.content=="string"?R.content.slice(22):"";yield o(this.#i({...s,type:"compaction_triggered",messagesBefore:U,messagesAfter:V,summary:X}))}if(this.#d?.onCompaction!==void 0)try{await this.#d.onCompaction(U,V)}catch(R){typeof process<"u"&&process.env.NODE_ENV!=="production"&&console.warn("[AgentRuntime] onCompaction hook threw:",R)}}yield o(this.#i({...s,type:"model_request_started",provider:"configured"}));let x={messages:d,...u.length>0?{tools:u}:{},...l.modelInput.options!==void 0?{options:l.modelInput.options}:{}},v;if(this.#f&&zc(this.#t)){let S="",$,B="",U,V;for await(let R of this.#t.generateStream(x)){if(e.signal?.aborted)break;R.type==="token_delta"?yield o(this.#i({...s,type:"token_delta",delta:R.delta})):R.type==="message_done"?(S=R.content,U=R.usage):R.type==="tool_calls"?($=R.calls,B=R.text??"",U=R.usage):R.type==="error"&&(V={category:R.category,message:R.message,recoverable:R.recoverable})}V!==void 0?v={type:"error",category:V.category,message:V.message,recoverable:V.recoverable}:$!==void 0?v={type:"tool_calls",calls:$,...B?{text:B}:{},...U!==void 0?{usage:U}:{}}:v={type:"message",content:S,...U!==void 0?{usage:U}:{}}}else v=await this.#t.generate(x);if(yield o(this.#i({...s,type:"model_request_completed",provider:"configured"})),p++,v.type==="error"){yield o(this.#i({...s,type:"run_failed",error:{message:v.message,recoverable:v.recoverable}})),await this.#m(n);return}if(v.type==="message"){if([...this.#s.keys()].some(B=>B!=="update_todos")&&!g&&jp(v.content)){if(h++,yield o(this.#i({...s,type:"planning_stall_detected",stallCount:h,maxRetries:this.#a})),h>=this.#a){yield o(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}d=[...d,{role:"assistant",content:v.content},{role:"user",content:Ap}];continue}h=0,v.content!==""?(w.push({role:"assistant",content:v.content}),yield o(this.#i({...s,type:"assistant_message_created",message:{role:"assistant",content:v.content}}))):y!==""&&(yield o(this.#i({...s,type:"assistant_message_created",message:{role:"assistant",content:y}}))),yield o(this.#i({...s,type:"turn_complete",messages:[...w]})),yield o(this.#i({...s,type:"run_completed"})),await this.#m(n);return}h=0,v.calls.some(S=>S.name!=="update_todos")&&(g=!0),v.text&&(y=v.text);let C={role:"assistant",content:v.text??null,toolCalls:v.calls};d=[...d,C],w.push({...C});let M=[],j=!1,Y="";for(let S of v.calls){yield o(this.#i({...s,type:"tool_call_requested",call:S}));let $=this.#s.get(S.name);if($===void 0){let R=`Tool "${S.name}" is not registered.`;yield o(this.#i({...s,type:"tool_failed",callId:S.id,toolName:S.name,error:{message:R}}));let X={role:"tool",toolCallId:S.id,content:`Error: ${R}`};M.push(X),w.push({...X});continue}let B=this.#r.evaluate({mode:$p(this.#c?.mode),action:Lp(S,$.risk)});if(yield o(this.#i({...s,type:"tool_call_permission_evaluated",callId:S.id,toolName:S.name,decision:B})),B.decision==="deny"){j=!0,Y=`Tool call ${S.name} was denied.`;break}if(B.decision==="ask"){yield o(this.#i({...s,type:"approval_requested",callId:S.id,toolName:S.name,decision:B}));let R=this.#o===void 0?{approved:!1,reason:"No approval resolver was configured."}:await this.#o.resolve({call:S,decision:B});if(yield o(this.#i({...s,type:"approval_resolved",callId:S.id,toolName:S.name,resolution:R})),!R.approved){j=!0,Y=`Tool call ${S.name} was denied.`;break}}if(this.#d?.beforeToolCall!==void 0){let R;try{R=await this.#d.beforeToolCall(S)}catch(X){typeof process<"u"&&process.env.NODE_ENV!=="production"&&console.warn("[AgentRuntime] beforeToolCall hook threw:",X)}if(R==="abort"){let X="Tool call aborted by hook.";yield o(this.#i({...s,type:"tool_failed",callId:S.id,toolName:S.name,error:{message:X}}));let ge={role:"tool",toolCallId:S.id,content:`Error: ${X}`};M.push(ge),w.push({...ge});continue}}yield o(this.#i({...s,type:"tool_started",callId:S.id,toolName:S.name}));let U;try{let R={workspaceRoot:this.#c?.workspace??process.cwd(),parentRecentMessages:d.map(X=>({role:X.role,content:X.content})),...e.sessionId!==void 0?{parentSessionId:e.sessionId}:{},depth:this.#y};U=await $.execute(S.input,R)}catch(R){let X=R instanceof Error?R.message:"Unknown tool execution error.";yield o(this.#i({...s,type:"tool_failed",callId:S.id,toolName:S.name,error:{message:X}}));let ge={role:"tool",toolCallId:S.id,content:`Error: ${X}`};M.push(ge),w.push({...ge});continue}yield o(this.#i({...s,type:"tool_completed",callId:S.id,toolName:S.name,result:U}));let V={role:"tool",toolCallId:S.id,content:JSON.stringify(U)};if(M.push(V),w.push({...V}),this.#d?.afterToolCall!==void 0)try{await this.#d.afterToolCall(S,U)}catch(R){typeof process<"u"&&process.env.NODE_ENV!=="production"&&console.warn("[AgentRuntime] afterToolCall hook threw:",R)}}if(j){yield o(this.#i({...s,type:"run_failed",error:{message:Y,recoverable:!1}})),await this.#m(n);return}v.calls.some(S=>S.name==="update_todos")&&(yield o(this.#i({...s,type:"todos_updated",todos:[...this.#_]}))),d=[...d,...M]}yield o(this.#i({...s,type:"run_failed",error:{message:`Agent loop reached the step limit of ${this.#l}.`,recoverable:!1}})),await this.#m(n)}}async#v(e,r){let s=this.#S(),n=[...e,{role:"system",content:r}],o;try{o=await this.#t.generate({messages:n,...s.length>0?{tools:s}:{}})}catch{return{executed:!1,toolsInvoked:[],reason:"model_error"}}if(o.type==="error")return{executed:!1,toolsInvoked:[],reason:"model_error"};if(o.type!=="tool_calls")return{executed:!0,toolsInvoked:[]};let i=[],a={workspaceRoot:this.#c?.workspace??process.cwd(),parentRecentMessages:e.map(c=>({role:c.role,content:c.content})),depth:this.#y};for(let c of o.calls){let l=this.#s.get(c.name);if(l!==void 0&&!(l.risk==="high"||l.risk==="blocked"))try{await l.execute(c.input,a),i.push(c.name)}catch{}}return{executed:!0,toolsInvoked:i}}async#m(e){if(this.#d?.afterTurn!==void 0)try{await this.#d.afterTurn(e)}catch(r){typeof process<"u"&&process.env.NODE_ENV!=="production"&&console.warn("[AgentRuntime] afterTurn hook threw:",r)}}#k(){return[...this.#s.values()].map(e=>({name:e.name,description:e.description,risk:e.risk}))}#S(){return[...this.#s.values()].map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.inputSchema}}))}#i(e){return{...e,eventId:this.#w(),timestamp:this.#E()}}};function al(t){return()=>`${t}_${crypto.randomUUID()}`}function Np(t){let e=[`[subagent #${t.taskId} ${t.status}]`,`goal: ${t.goal}`,`status: ${t.status}`];return t.terminalSummary!==void 0&&t.terminalSummary.length>0&&e.push(`result: ${t.terminalSummary}`),e.push(`completedAt: ${t.completedAt}`),e.join(`
|
|
118
|
+
`)}function Lp(t,e){return{kind:"tool",name:t.name,summary:`Model requested tool ${t.name}.`,risk:e}}function $p(t){return t==="observe"||t==="auto"?t:"confirm"}function Dp(t){let e=t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(e.length===0)return!1;let r=e.filter(o=>Op.test(o)).length,s=e.some(o=>cl.test(o));return Pp.test(e[0]??"")&&s||r>=2&&s}function jp(t){let e=t.trim();if(!e||e.length>Cp||e.includes("```")||Ip.test(e))return!1;let r=Dp(e);return!(!cl.test(e)&&!r||!r&&!Mp.test(e))}var Ur=class{key;maxConcurrent;#e=0;#t=[];constructor(e){if(!Number.isInteger(e.maxConcurrent)||e.maxConcurrent<1)throw new Error(`Lane "${e.key}" maxConcurrent must be a positive integer; got ${e.maxConcurrent}.`);this.key=e.key,this.maxConcurrent=e.maxConcurrent}async enqueue(e){this.#e>=this.maxConcurrent&&await new Promise(r=>this.#t.push(r)),this.#e++;try{return await e()}finally{this.#e--;let r=this.#t.shift();r!==void 0&&r()}}occupancy(){return{active:this.#e,queued:this.#t.length}}},Fr={global:16,subagent:8,session:1},Zs=class{global;subagent;#e=new Map;#t;constructor(e={}){this.global=new Ur({key:"global",maxConcurrent:e.globalConcurrency??Fr.global}),this.subagent=new Ur({key:"subagent",maxConcurrent:e.subagentConcurrency??Fr.subagent}),this.#t=e.sessionConcurrency??Fr.session}sessionLane(e){let r=this.#e.get(e);return r===void 0&&(r=new Ur({key:`session:${e}`,maxConcurrent:this.#t}),this.#e.set(e,r)),r}releaseSessionLane(e){let r=this.#e.get(e);if(r===void 0)return!1;let{active:s,queued:n}=r.occupancy();return s===0&&n===0?(this.#e.delete(e),!0):!1}status(){let e=Array.from(this.#e.values()).map(r=>({key:r.key,...r.occupancy()}));return{global:this.global.occupancy(),subagent:this.subagent.occupancy(),sessions:e}}};async function ll(t,e,r){let s=t.sessionLane(e.sessionId),n=()=>s.enqueue(r),o=()=>e.isSubagent===!0?t.subagent.enqueue(n):n();return t.global.enqueue(o)}var Vo=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)}},Bp=5,Go=class extends Error{code="max_children_per_agent_exceeded";parentSessionKey;limit;constructor(e,r){super(`Parent session "${e}" already has ${r} active children (max).`),this.name="ChildLimitExceededError",this.parentSessionKey=e,this.limit=r}},Ko=class extends Error{code="run_timeout";runId;timeoutSeconds;constructor(e,r){super(`Run "${e}" exceeded its ${r}s timeout.`),this.name="RunTimeoutError",this.runId=e,this.timeoutSeconds=r}},zo=class{#e=[];#t=[];#r=!1;#o;push(e){if(this.#r)return;let r=this.#t.shift();if(r!==void 0){r.resolve({value:e,done:!1});return}this.#e.push(e)}close(){if(!this.#r)for(this.#r=!0;this.#t.length>0;){let e=this.#t.shift();e!==void 0&&e.resolve({value:void 0,done:!0})}}fail(e){if(!this.#r)for(this.#r=!0,this.#o=e;this.#t.length>0;){let r=this.#t.shift();r!==void 0&&r.reject(e)}}[Symbol.asyncIterator](){return{next:()=>this.#e.length>0?Promise.resolve({value:this.#e.shift(),done:!1}):this.#r?this.#o!==void 0?Promise.reject(this.#o):Promise.resolve({value:void 0,done:!0}):new Promise((e,r)=>{this.#t.push({resolve:e,reject:r})})}}},en=class extends Vo{#e;#t=new Map;#r;#o;constructor(e={}){super(),this.#e=new Zs(e.lanes??{}),this.#r=e.now??(()=>new Date().toISOString()),this.#o=e.maxChildrenPerAgent??Bp}submit(e){let r=new zo;if(e.isSubagent===!0&&e.parentSessionKey!==void 0&&this.#s(e.parentSessionKey)>=this.#o)return r.fail(new Go(e.parentSessionKey,this.#o)),r;let s=new AbortController,o={handle:{runId:e.runId,sessionKey:e.sessionKey,agentId:e.agentId,isSubagent:e.isSubagent===!0,startedAt:this.#r(),...e.parentSessionKey!==void 0?{parentSessionKey:e.parentSessionKey}:{}},controller:s};if(this.#t.set(e.runId,o),e.runTimeoutSeconds!==void 0&&e.runTimeoutSeconds>0){let u=e.runTimeoutSeconds*1e3,d=new Ko(e.runId,e.runTimeoutSeconds);o.timeoutHandle=setTimeout(()=>{s.abort(d)},u)}let i=this.#e,a=e.isSubagent===!0?{sessionId:e.sessionKey,isSubagent:!0}:{sessionId:e.sessionKey},c=this.#t,l=()=>{let u=c.get(e.runId);u?.timeoutHandle!==void 0&&clearTimeout(u.timeoutHandle),c.delete(e.runId)};return ll(i,a,async()=>{if(!s.signal.aborted)for await(let u of e.run(s.signal)){if(s.signal.aborted)break;r.push(u)}}).then(()=>{l(),r.close()}).catch(u=>{l(),r.fail(u)}),r}#s(e){let r=0;for(let s of this.#t.values())s.handle.parentSessionKey===e&&r++;return r}cancel(e){let r=this.#t.get(e);return r===void 0?!1:(r.controller.abort(),!0)}status(){return{lanes:this.#e.status(),activeRuns:Array.from(this.#t.values()).map(e=>e.handle)}}get defaultLaneConcurrency(){return Fr}};var bm=de(ei(),1);import{mkdir as pm,readdir as mm,readFile as zl,unlink as Hl,writeFile as ti}from"fs/promises";import{join as Wl}from"path";var un=class{#e;#t;#r;#o;#s;constructor(e){this.#e=e.directory,this.#t=e.createSessionId??Kl("sess"),this.#r=e.createMessageId??Kl("msg"),this.#o=e.now??(()=>new Date().toISOString());let r=e.fileLock??{};this.#s={enabled:r.enabled??!0,acquireTimeoutMs:r.acquireTimeoutMs??Xl,retryIntervalMs:r.retryIntervalMs??Yl,staleAfterMs:r.staleAfterMs??Jl,...r.pid!==void 0?{pid:r.pid}:{},...r.now!==void 0?{now:r.now}:{},...r.isProcessAlive!==void 0?{isProcessAlive:r.isProcessAlive}:{}}}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.#n(s.id,{type:"session",session:s}),{...s}}async getSession(e){let r=await this.#a(e);return r.session===void 0?void 0:{...r.session}}async listSessions(e={}){let r=await this.#c(),s=[];for(let i of r){let a=await this.getSession(i);a!==void 0&&s.push(a)}let n=s.sort(gm);return(e.limit===void 0?n:n.slice(0,e.limit)).map(i=>({...i}))}async appendMessage(e){if((await this.#a(e.sessionId)).session===void 0)throw new Error(`Unknown session "${e.sessionId}".`);let s=this.#o(),n={id:this.#r(),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.#n(e.sessionId,{type:"message",message:n}),{...n}}async listMessages(e,r={}){let s=await this.#a(e);return(r.limit===void 0?s.messages:s.messages.slice(-r.limit)).map(o=>({...o}))}async appendTraceEvent(e){if((await this.#a(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.#n(e.sessionId,{type:"trace",traceEvent:s}),Gl(s)}async listTraceEvents(e,r={}){let s=await this.#a(e);return(r.limit===void 0?s.traceEvents:s.traceEvents.slice(-r.limit)).map(o=>Gl(o))}async appendCompactBoundary(e){if((await this.#a(e.sessionId)).session===void 0)throw new Error(`Unknown session "${e.sessionId}".`);let s=this.#o();await this.#n(e.sessionId,{type:"compact_boundary",summary:e.summary,messagesBefore:e.messagesBefore,messagesAfter:e.messagesAfter,createdAt:s})}async#n(e,r){if(await pm(this.#e,{recursive:!0}),this.#s.enabled){let s=await _m(this.#l(e),this.#s);try{await ti(this.#u(e),`${JSON.stringify(r)}
|
|
119
|
+
`,{flag:"a"})}finally{await s.release()}}else await ti(this.#u(e),`${JSON.stringify(r)}
|
|
120
|
+
`,{flag:"a"})}#l(e){return Vl(e),Wl(this.#e,`${e}.lock`)}async#a(e){let r="";try{r=await zl(this.#u(e),"utf8")}catch(i){if(ct(i)&&i.code==="ENOENT")return{messages:[],traceEvents:[]};throw i}let s=[],n=[],o;for(let i of r.split(`
|
|
121
|
+
`)){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}}#u(e){return Vl(e),Wl(this.#e,`${e}.jsonl`)}async#c(){try{return(await mm(this.#e)).filter(r=>r.endsWith(".jsonl")).map(r=>r.slice(0,-6)).filter(r=>/^[A-Za-z0-9_-]+$/.test(r))}catch(e){if(ct(e)&&e.code==="ENOENT")return[];throw e}}};function Vl(t){if(!/^[A-Za-z0-9_-]+$/.test(t))throw new Error(`Unsafe session id "${t}".`)}function ct(t){return t instanceof Error&&"code"in t}function gm(t,e){return e.updatedAt.localeCompare(t.updatedAt)}function Gl(t){return{...t,event:structuredClone(t.event)}}function Kl(t){return()=>`${t}_${crypto.randomUUID()}`}var Xl=6e4,Yl=50,Jl=6e4;function ym(t){try{return process.kill(t,0),!0}catch(e){return!(ct(e)&&e.code==="ESRCH")}}async function _m(t,e={}){let r=e.acquireTimeoutMs??Xl,s=e.retryIntervalMs??Yl,n=e.staleAfterMs??Jl,o=e.pid??process.pid,i=e.now??(()=>Date.now()),a=e.isProcessAlive??ym,c=i(),l={pid:o,startedAt:i()},u=JSON.stringify(l),d=!1,p=async()=>{if(!d){d=!0;try{await Hl(t)}catch(h){if(ct(h)&&h.code==="ENOENT")return;throw h}}};for(;;){try{return await ti(t,u,{flag:"wx"}),{lockPath:t,release:p}}catch(y){if(!ct(y)||y.code!=="EEXIST")throw y}let h;try{let y=await zl(t,"utf8");h=JSON.parse(y)}catch(y){(!ct(y)||y.code!=="ENOENT"&&!(y instanceof SyntaxError))&&(h=void 0)}let g=!1;if((h===void 0||i()-h.startedAt>n||typeof h.pid=="number"&&!a(h.pid))&&(g=!0),g){try{await Hl(t)}catch(y){if(!ct(y)||y.code!=="ENOENT")throw y}continue}if(i()-c>r)throw new Error(`Timed out acquiring session file lock at ${t} after ${r}ms (held by pid ${h?.pid??"?"}).`);await new Promise(y=>setTimeout(y,s))}}import{copyFile as Wx,mkdir as Vx,readFile as Ql,readdir as wm,writeFile as Gx}from"fs/promises";import{homedir as Em}from"os";import{basename as Xx,join as dn}from"path";var Sm=[{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:""}],fn=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=dn(e.workspaceRoot,"skills");for(let c of await this.#e(a,"workspace",e))n(c)}let o=e.userSkillsDir??dn(Em(),".vole","skills"),i=await xm(o,e.readFile);for(let a of await this.#e(o,"user",e,i))n(a);for(let a of Sm)n(a);return s}async#e(e,r,s,n){let o=s.readDir??(l=>wm(l)),i=s.readFile??(l=>Ql(l,"utf8")),a;try{a=await o(e)}catch(l){if(km(l)&&l.code==="ENOENT")return[];throw l}let c=[];for(let l of a){if(l==="skills-index.json")continue;let u=dn(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=vm(d);if(p!==null){let h,g;if(r==="user"){let w=n?.skills.find(k=>k.name===l);h=w?.trusted??!1,g=w?.enabled??!0}let y={...p,source:r,filePath:u,...h!==void 0?{trusted:h}:{},...g!==void 0?{enabled:g}:{}};c.push(y)}}catch{}}return c}};async function xm(t,e){let r=e??(n=>Ql(n,"utf8")),s=dn(t,"skills-index.json");try{let n=await r(s);return JSON.parse(n)}catch{return}}function vm(t){let e=t.split(`
|
|
85
122
|
`);if(e[0]?.trim()!=="---")return null;let r=e.findIndex((g,y)=>y>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 y=/^\s+-\s+(.+)$/.exec(g);if(y!==null&&a!==null){let R=y[1]?.trim()??"";R.length>0&&(i[a]=[...i[a]??[],R]);continue}let x=g.indexOf(":");if(x===-1){a=null;continue}let E=g.slice(0,x).trim(),k=g.slice(x+1).trim();if(E.length===0){a=null;continue}k===""?a=E:(a=null,o[E]=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 jc(t){return{name:t.name,description:t.description,source:t.source}}function Oh(t){return t instanceof Error&&"code"in t}async function Nh(t=process.cwd()){let e=t;for(;;){try{return await Mh(Bc(e,".git")),e}catch{}let r=Ch(e);if(r===e)return;e=r}}async function et(){let t=_a({env:process.env});if(t.sessions.directory==="~/.vole/sessions"){let e=process.env.VOLE_WEB_ROOT??process.cwd(),r=await Nh(e);r!==void 0&&(t.sessions.directory=Bc(r,".vole","sessions"))}return t}var Eo=new qs,So=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}},xo,Or=new Map,vo=new Map;function Vt(t){if(xo===void 0){let e=wa(t,process.env);xo=new Hs({directory:e})}return xo}function Lh(t){return t.model.provider==="anthropic"?new $s({...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 Ls({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 Dc(t,e){let r=Vt(t),s=new So,n=new Us,o=new Date().toISOString().slice(0,10),i=await new Vs().load({workspaceRoot:t.workspace.root}),a=i.map(jc),c=new Map(i.map(y=>[y.name,y.filePath])),l=[bc(),wc(),kc(),Ec(t.runtime.sandboxed!==void 0?{sandboxed:t.runtime.sandboxed}:void 0),Rc()];(t.memory.longTermFiles==="read-only"||t.memory.longTermFiles==="write")&&(l.push(Ac(t.workspace.root)),l.push(Oc(t.workspace.root))),c.size>0&&l.push(Tc(c));let u=t.runtime.toolProfile!==void 0?ga(l,t.runtime.toolProfile):l,d=new Fs({contextAssembler:new os({workspacePromptFiles:["AGENTS.md","SOUL.md","TOOLS.md","IDENTITY.md","HEARTBEAT.md","BOOTSTRAP.md"]}),modelProvider:Lh(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};Or.set(p,h);let g=new Date().toISOString();return Eo.register({id:p,adapterName:"web",capabilities:ma,registeredAt:g,lastActivityAt:g}),h}var ie=new Nn;ie.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")});ie.options("/api/*",t=>t.text("",200));ie.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 Dc(e,s);return t.json({sessionId:n.id})}catch(n){return t.json({error:n instanceof Error?n.message:"Failed to create session"},400)}});ie.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:[]})}});ie.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)}});ie.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)}});ie.post("/api/sessions/:id/turns",async t=>{let e=t.req.param("id"),r=Or.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 Dc(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 vo.set(e,u),$n(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{vo.delete(e)}u.signal.aborted||(await a.appendMessage({sessionId:e,role:"user",content:o}),p!==""&&await a.appendMessage({sessionId:e,role:"assistant",content:p})),Eo.touch(e)})});ie.delete("/api/sessions/:id/turns",t=>{let e=t.req.param("id"),r=vo.get(e);return r===void 0?t.json({ok:!1,reason:"no running turn"},404):(r.abort(),t.json({ok:!0}))});ie.get("/api/gateway/sessions",t=>t.json({sessions:Eo.list()}));ie.post("/api/sessions/:id/approvals",async t=>{let e=t.req.param("id"),r=Or.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 $h=Ih("./client")?"./client":"./dist/client";ie.use("/*",Fo({root:$h}));var Uc=Number(process.env.PORT??3120);console.log(`Vole web server starting on http://localhost:${Uc}`);var jh=$o({fetch:ie.fetch,port:Uc}),Bh=new vn.default({noServer:!0});jh.on("upgrade",(t,e,r)=>{let s=t.url??"",n=/^\/ws\/([^/?#]+)/.exec(s);if(n===null){e.destroy();return}Bh.handleUpgrade(t,e,r,o=>{let i=n[1];if(Or.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=Or.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),y=(await h.listMessages(i,{limit:12})).map(x=>({role:x.role,content:x.content}));for await(let x of l.runtime.runTurn({sessionId:i,recentMessages:y,message:d}))if(await l.traceStore.append(x),await h.appendTraceEvent({sessionId:i,event:x}),o.send(JSON.stringify(x)),x.type==="run_completed"||x.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",()=>{})})});
|
|
123
|
+
`).trim(),o={},i={},a=null;for(let g of s){let y=/^\s+-\s+(.+)$/.exec(g);if(y!==null&&a!==null){let x=y[1]?.trim()??"";x.length>0&&(i[a]=[...i[a]??[],x]);continue}let w=g.indexOf(":");if(w===-1){a=null;continue}let k=g.slice(0,w).trim(),A=g.slice(w+1).trim();if(k.length===0){a=null;continue}A===""?a=k:(a=null,o[k]=A)}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 Zl(t){return{name:t.name,description:t.description,source:t.source}}function km(t){return t instanceof Error&&"code"in t}var Im=de(ei(),1);import{createHash as Qx}from"crypto";import{mkdir as e0,readdir as Tm,readFile as tu,writeFile as t0,access as Rm}from"fs/promises";import{join as hn,relative as Am,resolve as eu}from"path";function Pm(t,e){let r=Math.min(t.length,e.length),s=0;for(let n=0;n<r;n++)s+=(t[n]??0)*(e[n]??0);return s}function Om(t,e){let r=new Map;for(let s of t)s.forEach((n,o)=>{let i=o+1,a=1/(e+i),c=r.get(n.key);c?c.score+=a:r.set(n.key,{score:a,record:n.record})});return[...r.values()].sort((s,n)=>n.score-s.score).map(s=>s.record)}function ru(t,e){let r=e?.embeddingProvider,s=e?.topKVector??10,n=e?.fusionConstant??60;return{name:"memory_search",description:r===void 0?"Search over memory files (MEMORY.md, USER.md, memory/YYYY-MM-DD.md) for relevant content. Returns matching excerpts.":"Hybrid search over memory files (MEMORY.md, USER.md, memory/YYYY-MM-DD.md): combines keyword paragraph match with vector top-K from the configured embedding provider, fused via reciprocal rank fusion.",risk:"low",inputSchema:{type:"object",properties:{query:{type:"string"},maxResults:{type:"number"}},required:["query"]},async execute(o){let i=o,a=typeof i.query=="string"?i.query:"",c=typeof i.maxResults=="number"?i.maxResults:5,l=[],u=hn(t,"MEMORY.md"),d=hn(t,"USER.md"),p=hn(t,"memory");for(let x of[u,d])try{await Rm(x),l.push(x)}catch{}try{let x=await Tm(p,{recursive:!0,withFileTypes:!0});for(let v of x)if(v.isFile()&&v.name.endsWith(".md")){let C=typeof v.parentPath=="string"?v.parentPath:v.path;l.push(hn(C,v.name))}}catch{}if(l.length===0)return{ok:!0,results:[],total:0};let h=[];for(let x of l){let v;try{v=await tu(x,"utf8")}catch{continue}let C=v.split(/\n\n+/),M=Am(t,x);C.forEach((j,Y)=>{let S=j.trim();S.length!==0&&h.push({key:`${M}#${Y}`,record:{file:M,excerpt:S}})})}if(h.length===0)return{ok:!0,results:[],total:0};let g=a.toLowerCase().split(/\s+/).filter(x=>x.length>0),y=h.filter(x=>{let v=x.record.excerpt.toLowerCase();return g.some(C=>v.includes(C))});if(r===void 0){let x=y.slice(0,c).map(v=>v.record);return{ok:!0,results:x,total:x.length}}let w=[];try{let x=await r.embed([a,...h.map(C=>C.record.excerpt)]),v=x[0];if(v!==void 0&&x.length===h.length+1){let C=h.map((M,j)=>{let Y=x[j+1],S=Y===void 0?0:Pm(v,Y);return{entry:M,score:S}});C.sort((M,j)=>j.score-M.score),w=C.slice(0,s).map(M=>M.entry)}}catch{w=[]}let A=Om([w,y],n).slice(0,c);return{ok:!0,results:A,total:A.length}}}}function su(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=eu(t),o=eu(n,s);if(!o.startsWith(n+"/")&&o!==n)return{ok:!0,error:"Path traversal is not permitted."};try{return{ok:!0,content:await tu(o,"utf8")}}catch{return{ok:!0,error:`File not found: ${s}`}}}}}async function Lm(t=process.cwd()){let e=t;for(;;){try{return await Cm(nu(e,".git")),e}catch{}let r=Nm(e);if(r===e)return;e=r}}async function lt(){let t=Ja({env:process.env});if(t.sessions.directory==="~/.vole/sessions"){let e=process.env.VOLE_WEB_ROOT??process.cwd(),r=await Lm(e);r!==void 0&&(t.sessions.directory=nu(r,".vole","sessions"))}return t}var tr=new en,si=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}},ri,Hr=new Map,pn=new Map;function rr(t){if(ri===void 0){let e=Za(t,process.env);ri=new un({directory:e})}return ri}function $m(t){return t.model.provider==="anthropic"?new Xs({...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 zs({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 ou(t,e){let r=rr(t),s=new si,n=new Js,o=new Date().toISOString().slice(0,10),i=await new fn().load({workspaceRoot:t.workspace.root}),a=i.map(Zl),c=new Map(i.map(y=>[y.name,y.body])),l=[Jc(),Qc(),sl(),rl(t.runtime.sandboxed!==void 0?{sandboxed:t.runtime.sandboxed}:void 0),nl()];(t.memory.longTermFiles==="read-only"||t.memory.longTermFiles==="write")&&(l.push(ru(t.workspace.root)),l.push(su(t.workspace.root))),c.size>0&&l.push(il(c));let u=t.runtime.toolProfile!==void 0?Xa(l,t.runtime.toolProfile):l,d=new Qs({contextAssembler:new _s({workspacePromptFiles:["AGENTS.md","SOUL.md","TOOLS.md","IDENTITY.md","HEARTBEAT.md","BOOTSTRAP.md"]}),modelProvider:$m(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};Hr.set(p,h);let g=new Date().toISOString();return tr.register({id:p,adapterName:"web",capabilities:za,registeredAt:g,lastActivityAt:g}),h}var ce=new ro;ce.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")});ce.options("/api/*",t=>t.text("",200));ce.post("/api/sessions",async t=>{let e;try{e=await lt()}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 ou(e,s);return t.json({sessionId:n.id})}catch(n){return t.json({error:n instanceof Error?n.message:"Failed to create session"},400)}});ce.get("/api/sessions",async t=>{let e;try{e=await lt()}catch{return t.json({sessions:[]})}try{let n=(await rr(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:[]})}});ce.get("/api/sessions/:id",async t=>{let e;try{e=await lt()}catch(s){return t.json({error:s instanceof Error?s.message:"Config error"},400)}let r=t.req.param("id");try{let n=await rr(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)}});ce.get("/api/sessions/:id/messages",async t=>{let e;try{e=await lt()}catch(s){return t.json({error:s instanceof Error?s.message:"Config error"},400)}let r=t.req.param("id");try{let n=await rr(e).listMessages(r);return t.json({messages:n})}catch(s){return t.json({error:s instanceof Error?s.message:"Store error"},500)}});ce.post("/api/sessions/:id/turns",async t=>{let e=t.req.param("id"),r=Hr.get(e);if(r===void 0){let p;try{p=await lt()}catch(h){return t.json({error:h instanceof Error?h.message:"Config error"},400)}try{r=await ou(p,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 lt()}catch(p){return t.json({error:p instanceof Error?p.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=rr(i),l=(await a.listMessages(e,{limit:12})).map(p=>({role:p.role,content:p.content})),u=`run_${crypto.randomUUID()}`;pn.set(e,u);let d=s.runtime;return no(t,async p=>{let h="",g=!1;try{let y=tr.submit({runId:u,sessionKey:e,agentId:"default",run:async function*(w){for await(let k of d.runTurn({sessionId:e,recentMessages:l,message:o,signal:w}))yield k}});for await(let w of y)if(await s.traceStore.append(w),await a.appendTraceEvent({sessionId:e,event:w}),await p.writeSSE({event:w.type,data:JSON.stringify(w)}),w.type==="assistant_message_created"&&(h=w.message.content),w.type==="run_completed"||w.type==="run_failed")break}catch(y){if(y instanceof Error&&y.name==="AbortError")g=!0;else throw y}finally{pn.delete(e)}g||(await a.appendMessage({sessionId:e,role:"user",content:o}),h!==""&&await a.appendMessage({sessionId:e,role:"assistant",content:h})),tr.touch(e)})});ce.delete("/api/sessions/:id/turns",t=>{let e=t.req.param("id"),r=pn.get(e);return r===void 0?t.json({ok:!1,reason:"no running turn"},404):(tr.cancel(r),pn.delete(e),t.json({ok:!0}))});ce.get("/api/gateway/sessions",t=>t.json({sessions:tr.list()}));ce.post("/api/sessions/:id/approvals",async t=>{let e=t.req.param("id"),r=Hr.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 Dm=Mm("./client")?"./client":"./dist/client";ce.use("/*",wi({root:Dm}));var iu=Number(process.env.PORT??3120);console.log(`Vole web server starting on http://localhost:${iu}`);var jm=mi({fetch:ce.fetch,port:iu}),Bm=new Vn.default({noServer:!0});jm.on("upgrade",(t,e,r)=>{let s=t.url??"",n=/^\/ws\/([^/?#]+)/.exec(s);if(n===null){e.destroy();return}Bm.handleUpgrade(t,e,r,o=>{let i=n[1];if(Hr.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=Hr.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 lt()}catch{o.send(JSON.stringify({type:"error",message:"Config error."}));return}let h=rr(p),y=(await h.listMessages(i,{limit:12})).map(x=>({role:x.role,content:x.content})),w=`run_${crypto.randomUUID()}`,k=l.runtime,A=tr.submit({runId:w,sessionKey:i,agentId:"default",run:async function*(x){for await(let v of k.runTurn({sessionId:i,recentMessages:y,message:d,signal:x}))yield v}});for await(let x of A)if(await l.traceStore.append(x),await h.appendTraceEvent({sessionId:i,event:x}),o.send(JSON.stringify(x)),x.type==="run_completed"||x.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",()=>{})})});
|