neural-loom 0.4.0 → 0.4.1
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/.next/BUILD_ID +1 -1
- package/.next/build-manifest.json +3 -3
- package/.next/cache/.tsbuildinfo +1 -1
- package/.next/diagnostics/route-bundle-stats.json +1 -1
- package/.next/fallback-build-manifest.json +3 -3
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +1 -1
- package/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +2 -2
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
- package/.next/server/app/index.segments/_full.segment.rsc +2 -2
- package/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/.next/server/app/index.segments/_index.segment.rsc +1 -1
- package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/page/react-loadable-manifest.json +2 -2
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__0dliu9v._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__0dliu9v._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__0li1h1u._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__0li1h1u._.js.map +1 -1
- package/.next/server/middleware/middleware-manifest.json +1 -1
- package/.next/server/middleware-build-manifest.js +3 -3
- package/.next/server/middleware-manifest.json +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/static/chunks/{0m3otim_ed372.js → 0-mwzfyigo.qs.js} +1 -1
- package/.next/static/chunks/0r~-9nw2vt0gl.js +1 -0
- package/.next/static/chunks/{0.izrbl-wv3p5.js → 11w~pp-8cbmjd.js} +1 -1
- package/.next/trace +1 -1
- package/.next/trace-build +1 -1
- package/package.json +1 -1
- package/src/lib/agents/claudeModels.ts +2 -1
- package/src/lib/agents/pricing.ts +6 -2
- package/.next/static/chunks/10ic2.627gnl-.js +0 -1
- /package/.next/static/{KqsHz1i_LpGdGcKSvZiL1 → 7Rt23xVOwYg-hHmWh-bzT}/_buildManifest.js +0 -0
- /package/.next/static/{KqsHz1i_LpGdGcKSvZiL1 → 7Rt23xVOwYg-hHmWh-bzT}/_clientMiddlewareManifest.js +0 -0
- /package/.next/static/{KqsHz1i_LpGdGcKSvZiL1 → 7Rt23xVOwYg-hHmWh-bzT}/_ssgManifest.js +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
module.exports=[27699,(e,t,s)=>{t.exports=e.x("events",()=>require("events"))},24836,(e,t,s)=>{t.exports=e.x("https",()=>require("https"))},21517,(e,t,s)=>{t.exports=e.x("http",()=>require("http"))},4446,(e,t,s)=>{t.exports=e.x("net",()=>require("net"))},55004,(e,t,s)=>{t.exports=e.x("tls",()=>require("tls"))},88947,(e,t,s)=>{t.exports=e.x("stream",()=>require("stream"))},92509,(e,t,s)=>{t.exports=e.x("url",()=>require("url"))},6461,(e,t,s)=>{t.exports=e.x("zlib",()=>require("zlib"))},74836,(e,t,s)=>{"use strict";let r=["nodebuffer","arraybuffer","fragments"],i="u">typeof Blob;i&&r.push("blob"),t.exports={BINARY_TYPES:r,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:i,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}},97970,(e,t,s)=>{"use strict";let{EMPTY_BUFFER:r}=e.r(74836),i=Buffer[Symbol.species];function o(e,t,s,r,i){for(let o=0;o<i;o++)s[r+o]=e[o]^t[3&o]}function n(e,t){for(let s=0;s<e.length;s++)e[s]^=t[3&s]}function a(e){let t;return(a.readOnly=!0,Buffer.isBuffer(e))?e:(e instanceof ArrayBuffer?t=new i(e):ArrayBuffer.isView(e)?t=new i(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),a.readOnly=!1),t)}if(t.exports={concat:function(e,t){if(0===e.length)return r;if(1===e.length)return e[0];let s=Buffer.allocUnsafe(t),o=0;for(let t=0;t<e.length;t++){let r=e[t];s.set(r,o),o+=r.length}return o<t?new i(s.buffer,s.byteOffset,o):s},mask:o,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:a,unmask:n},!process.env.WS_NO_BUFFER_UTIL)try{let e=(()=>{let e=Error("Cannot find module 'bufferutil'");throw e.code="MODULE_NOT_FOUND",e})();t.exports.mask=function(t,s,r,i,n){n<48?o(t,s,r,i,n):e.mask(t,s,r,i,n)},t.exports.unmask=function(t,s){t.length<32?n(t,s):e.unmask(t,s)}}catch(e){}},62048,(e,t,s)=>{"use strict";let r=Symbol("kDone"),i=Symbol("kRun");class o{constructor(e){this[r]=()=>{this.pending--,this[i]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[i]()}[i](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[r])}}}t.exports=o},80295,(e,t,s)=>{"use strict";let r,i=e.r(6461),o=e.r(97970),n=e.r(62048),{kStatusCode:a}=e.r(74836),l=Buffer[Symbol.species],c=Buffer.from([0,0,255,255]),h=Symbol("permessage-deflate"),d=Symbol("total-length"),u=Symbol("callback"),p=Symbol("buffers"),f=Symbol("error");class m{constructor(e){this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._maxPayload=0|this._options.maxPayload,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,r||(r=new n(void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10))}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:null==this._options.clientMaxWindowBits&&(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[u];this._deflate.close(),this._deflate=null,e&&e(Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,s=e.find(e=>(!1!==t.serverNoContextTakeover||!e.server_no_context_takeover)&&(!e.server_max_window_bits||!1!==t.serverMaxWindowBits&&("number"!=typeof t.serverMaxWindowBits||!(t.serverMaxWindowBits>e.server_max_window_bits)))&&("number"!=typeof t.clientMaxWindowBits||!!e.client_max_window_bits));if(!s)throw Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(s.server_no_context_takeover=!0),t.clientNoContextTakeover&&(s.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(s.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?s.client_max_window_bits=t.clientMaxWindowBits:(!0===s.client_max_window_bits||!1===t.clientMaxWindowBits)&&delete s.client_max_window_bits,s}acceptAsClient(e){let t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let s=e[t];if(s.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(s=s[0],"client_max_window_bits"===t){if(!0!==s){let e=+s;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${s}`)}else if("server_max_window_bits"===t){let e=+s;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else if("client_no_context_takeover"===t||"server_no_context_takeover"===t){if(!0!==s)throw TypeError(`Invalid value for parameter "${t}": ${s}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=s})}),e}decompress(e,t,s){r.add(r=>{this._decompress(e,t,(e,t)=>{r(),s(e,t)})})}compress(e,t,s){r.add(r=>{this._compress(e,t,(e,t)=>{r(),s(e,t)})})}_decompress(e,t,s){let r=this._isServer?"client":"server";if(!this._inflate){let e=`${r}_max_window_bits`,t="number"!=typeof this.params[e]?i.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=i.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[h]=this,this._inflate[d]=0,this._inflate[p]=[],this._inflate.on("error",_),this._inflate.on("data",y)}this._inflate[u]=s,this._inflate.write(e),t&&this._inflate.write(c),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,s(e);return}let i=o.concat(this._inflate[p],this._inflate[d]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[d]=0,this._inflate[p]=[],t&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),s(null,i)})}_compress(e,t,s){let r=this._isServer?"server":"client";if(!this._deflate){let e=`${r}_max_window_bits`,t="number"!=typeof this.params[e]?i.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=i.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[d]=0,this._deflate[p]=[],this._deflate.on("data",g)}this._deflate[u]=s,this._deflate.write(e),this._deflate.flush(i.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=o.concat(this._deflate[p],this._deflate[d]);t&&(e=new l(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[d]=0,this._deflate[p]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),s(null,e)})}}function g(e){this[p].push(e),this[d]+=e.length}function y(e){(this[d]+=e.length,this[h]._maxPayload<1||this[d]<=this[h]._maxPayload)?this[p].push(e):(this[f]=RangeError("Max payload size exceeded"),this[f].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[f][a]=1009,this.removeListener("data",y),this.reset())}function _(e){(this[h]._inflate=null,this[f])?this[u](this[f]):(e[a]=1007,this[u](e))}t.exports=m},874,(e,t,s)=>{t.exports=e.x("buffer",()=>require("buffer"))},58739,(e,t,s)=>{"use strict";let{isUtf8:r}=e.r(874),{hasBlob:i}=e.r(74836);function o(e){let t=e.length,s=0;for(;s<t;)if((128&e[s])==0)s++;else if((224&e[s])==192){if(s+1===t||(192&e[s+1])!=128||(254&e[s])==192)return!1;s+=2}else if((240&e[s])==224){if(s+2>=t||(192&e[s+1])!=128||(192&e[s+2])!=128||224===e[s]&&(224&e[s+1])==128||237===e[s]&&(224&e[s+1])==160)return!1;s+=3}else{if((248&e[s])!=240||s+3>=t||(192&e[s+1])!=128||(192&e[s+2])!=128||(192&e[s+3])!=128||240===e[s]&&(240&e[s+1])==128||244===e[s]&&e[s+1]>143||e[s]>244)return!1;s+=4}return!0}if(t.exports={isBlob:function(e){return i&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&("Blob"===e[Symbol.toStringTag]||"File"===e[Symbol.toStringTag])},isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:o,tokenChars:[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]},r)t.exports.isValidUTF8=function(e){return e.length<24?o(e):r(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=(()=>{let e=Error("Cannot find module 'utf-8-validate'");throw e.code="MODULE_NOT_FOUND",e})();t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch(e){}},29485,(e,t,s)=>{"use strict";let{Writable:r}=e.r(88947),i=e.r(80295),{BINARY_TYPES:o,EMPTY_BUFFER:n,kStatusCode:a,kWebSocket:l}=e.r(74836),{concat:c,toArrayBuffer:h,unmask:d}=e.r(97970),{isValidStatusCode:u,isValidUTF8:p}=e.r(58739),f=Buffer[Symbol.species],m=0,g=1,y=2,_=3,S=4,b=5,k=6;class x extends r{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||o[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=0|e.maxBufferedChunks,this._maxFragments=0|e.maxFragments,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[l]=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=m}_write(e,t,s){return 8===this._opcode&&this._state==m?s():this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks?void s(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS")):void(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 t=this._buffers[0];return this._buffers[0]=new f(t.buffer,t.byteOffset+e,t.length-e),new f(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let s=this._buffers[0],r=t.length-e;e>=s.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(s.buffer,s.byteOffset,e),r),this._buffers[0]=new f(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0)return t}startLoop(e){this._loop=!0;do switch(this._state){case m:this.getInfo(e);break;case g:this.getPayloadLength16(e);break;case y:this.getPayloadLength64(e);break;case _:this.getMask();break;case S:this.getData(e);break;case b:case k:this._loop=!1;return}while(this._loop)this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((48&t[0])!=0)return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"));let s=(64&t[0])==64;if(s&&!this._extensions[i.extensionName])return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(this._fin=(128&t[0])==128,this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(s)return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(!this._fragmented)return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"));this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));this._compressed=s}else{if(!(this._opcode>7)||!(this._opcode<11))return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));if(!this._fin)return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"));if(s)return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength)return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=(128&t[1])==128,this._isServer){if(!this._masked)return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}else if(this._masked)return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"));126===this._payloadLength?this._state=g:127===this._payloadLength?this._state=y: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 t=this.consume(8),s=t.readUInt32BE(0);s>2097151?e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=0x100000000*s+t.readUInt32BE(4),this.haveLength(e))}haveLength(e){this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)?e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH")):this._masked?this._state=_:this._state=S}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=S}getData(e){let t=n;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!=0&&d(t,this._mask)}if(this._opcode>7)return void this.controlMessage(t,e);if(this._compressed){this._state=b,this.decompress(t,e);return}if(t.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments)return void e(this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));this._messageLength=this._totalPayloadLength,this._fragments.push(t)}this.dataMessage(e)}decompress(e,t){this._extensions[i.extensionName].decompress(e,this._fin,(e,s)=>{if(e)return t(e);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0)return void t(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));if(this._maxFragments>0&&this._fragments.length>=this._maxFragments)return void t(this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));this._fragments.push(s)}this.dataMessage(t),this._state===m&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=m;return}let t=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let r;r="nodebuffer"===this._binaryType?c(s,t):"arraybuffer"===this._binaryType?h(c(s,t)):"blob"===this._binaryType?new Blob(s):s,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=m):(this._state=k,setImmediate(()=>{this.emit("message",r,!0),this._state=m,this.startLoop(e)}))}else{let r=c(s,t);if(!this._skipUTF8Validation&&!p(r))return void e(this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8"));this._state===b||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=m):(this._state=k,setImmediate(()=>{this.emit("message",r,!1),this._state=m,this.startLoop(e)}))}}controlMessage(e,t){if(8===this._opcode){if(0===e.length)this._loop=!1,this.emit("conclude",1005,n),this.end();else{let s=e.readUInt16BE(0);if(!u(s))return void t(this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE"));let r=new f(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!p(r))return void t(this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8"));this._loop=!1,this.emit("conclude",s,r),this.end()}this._state=m;return}this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=m):(this._state=k,setImmediate(()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=m,this.startLoop(t)}))}createError(e,t,s,r,i){this._loop=!1,this._errored=!0;let o=new e(s?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[a]=r,o}}t.exports=x},16735,(e,t,s)=>{"use strict";let r,{Duplex:i}=e.r(88947),{randomFillSync:o}=e.r(54799),{types:{isUint8Array:n}}=e.r(24361),a=e.r(80295),{EMPTY_BUFFER:l,kWebSocket:c,NOOP:h}=e.r(74836),{isBlob:d,isValidStatusCode:u}=e.r(58739),{mask:p,toBuffer:f}=e.r(97970),m=Symbol("kByteLength"),g=Buffer.alloc(4),y=8192,_=8192,S=0,b=1,k=2;class x{constructor(e,t,s){this._extensions=t||{},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=S,this.onerror=h,this[c]=void 0}static frame(e,t){let s,i,n=!1,a=2,l=!1;t.mask&&(s=t.maskBuffer||g,t.generateMask?t.generateMask(s):(_===y&&(void 0===r&&(r=Buffer.alloc(y)),o(r,0,y),_=0),s[0]=r[_++],s[1]=r[_++],s[2]=r[_++],s[3]=r[_++]),l=(s[0]|s[1]|s[2]|s[3])==0,a=6),"string"==typeof e?i=(!t.mask||l)&&void 0!==t[m]?t[m]:(e=Buffer.from(e)).length:(i=e.length,n=t.mask&&t.readOnly&&!l);let c=i;i>=65536?(a+=8,c=127):i>125&&(a+=2,c=126);let h=Buffer.allocUnsafe(n?i+a:a);return(h[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(h[0]|=64),h[1]=c,126===c?h.writeUInt16BE(i,2):127===c&&(h[2]=h[3]=0,h.writeUIntBE(i,4,6)),t.mask)?(h[1]|=128,h[a-4]=s[0],h[a-3]=s[1],h[a-2]=s[2],h[a-1]=s[3],l)?[h,e]:n?(p(e,s,h,a,i),[h]):(p(e,s,e,0,i),[h,e]):[h,e]}close(e,t,s,r){let i;if(void 0===e)i=l;else if("number"==typeof e&&u(e))if(void 0!==t&&t.length){let s=Buffer.byteLength(t);if(s>123)throw RangeError("The message must not be greater than 123 bytes");if((i=Buffer.allocUnsafe(2+s)).writeUInt16BE(e,0),"string"==typeof t)i.write(t,2);else if(n(t))i.set(t,2);else throw TypeError("Second argument must be a string or a Uint8Array")}else(i=Buffer.allocUnsafe(2)).writeUInt16BE(e,0);else throw TypeError("First argument must be a valid error code number");let o={[m]:i.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==S?this.enqueue([this.dispatch,i,!1,o,r]):this.sendFrame(x.frame(i,o),r)}ping(e,t,s){let r,i;if("string"==typeof e?(r=Buffer.byteLength(e),i=!1):d(e)?(r=e.size,i=!1):(r=(e=f(e)).length,i=f.readOnly),r>125)throw RangeError("The data size must not be greater than 125 bytes");let o={[m]:r,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};d(e)?this._state!==S?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):this._state!==S?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(x.frame(e,o),s)}pong(e,t,s){let r,i;if("string"==typeof e?(r=Buffer.byteLength(e),i=!1):d(e)?(r=e.size,i=!1):(r=(e=f(e)).length,i=f.readOnly),r>125)throw RangeError("The data size must not be greater than 125 bytes");let o={[m]:r,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};d(e)?this._state!==S?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):this._state!==S?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(x.frame(e,o),s)}send(e,t,s){let r,i,o=this._extensions[a.extensionName],n=t.binary?2:1,l=t.compress;"string"==typeof e?(r=Buffer.byteLength(e),i=!1):d(e)?(r=e.size,i=!1):(r=(e=f(e)).length,i=f.readOnly),this._firstFragment?(this._firstFragment=!1,l&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(l=r>=o._threshold),this._compress=l):(l=!1,n=0),t.fin&&(this._firstFragment=!0);let c={[m]:r,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:n,readOnly:i,rsv1:l};d(e)?this._state!==S?this.enqueue([this.getBlobData,e,this._compress,c,s]):this.getBlobData(e,this._compress,c,s):this._state!==S?this.enqueue([this.dispatch,e,this._compress,c,s]):this.dispatch(e,this._compress,c,s)}getBlobData(e,t,s,r){this._bufferedBytes+=s[m],this._state=k,e.arrayBuffer().then(e=>{if(this._socket.destroyed){let e=Error("The socket was closed while the blob was being read");process.nextTick(v,this,e,r);return}this._bufferedBytes-=s[m];let i=f(e);t?this.dispatch(i,t,s,r):(this._state=S,this.sendFrame(x.frame(i,s),r),this.dequeue())}).catch(e=>{process.nextTick(w,this,e,r)})}dispatch(e,t,s,r){if(!t)return void this.sendFrame(x.frame(e,s),r);let i=this._extensions[a.extensionName];this._bufferedBytes+=s[m],this._state=b,i.compress(e,s.fin,(e,t)=>{this._socket.destroyed?v(this,Error("The socket was closed while data was being compressed"),r):(this._bufferedBytes-=s[m],this._state=S,s.readOnly=!1,this.sendFrame(x.frame(t,s),r),this.dequeue())})}dequeue(){for(;this._state===S&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][m],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][m],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}function v(e,t,s){"function"==typeof s&&s(t);for(let s=0;s<e._queue.length;s++){let r=e._queue[s],i=r[r.length-1];"function"==typeof i&&i(t)}}function w(e,t,s){v(e,t,s),e.onerror(t)}t.exports=x},70494,(e,t,s)=>{"use strict";let{kForOnEventAttribute:r,kListener:i}=e.r(74836),o=Symbol("kCode"),n=Symbol("kData"),a=Symbol("kError"),l=Symbol("kMessage"),c=Symbol("kReason"),h=Symbol("kTarget"),d=Symbol("kType"),u=Symbol("kWasClean");class p{constructor(e){this[h]=null,this[d]=e}get target(){return this[h]}get type(){return this[d]}}Object.defineProperty(p.prototype,"target",{enumerable:!0}),Object.defineProperty(p.prototype,"type",{enumerable:!0});class f extends p{constructor(e,t={}){super(e),this[o]=void 0===t.code?0:t.code,this[c]=void 0===t.reason?"":t.reason,this[u]=void 0!==t.wasClean&&t.wasClean}get code(){return this[o]}get reason(){return this[c]}get wasClean(){return this[u]}}Object.defineProperty(f.prototype,"code",{enumerable:!0}),Object.defineProperty(f.prototype,"reason",{enumerable:!0}),Object.defineProperty(f.prototype,"wasClean",{enumerable:!0});class m extends p{constructor(e,t={}){super(e),this[a]=void 0===t.error?null:t.error,this[l]=void 0===t.message?"":t.message}get error(){return this[a]}get message(){return this[l]}}Object.defineProperty(m.prototype,"error",{enumerable:!0}),Object.defineProperty(m.prototype,"message",{enumerable:!0});class g extends p{constructor(e,t={}){super(e),this[n]=void 0===t.data?null:t.data}get data(){return this[n]}}Object.defineProperty(g.prototype,"data",{enumerable:!0});let y={addEventListener(e,t,s={}){let o;for(let o of this.listeners(e))if(!s[r]&&o[i]===t&&!o[r])return;if("message"===e)o=function(e,s){let r=new g("message",{data:s?e:e.toString()});r[h]=this,_(t,this,r)};else if("close"===e)o=function(e,s){let r=new f("close",{code:e,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[h]=this,_(t,this,r)};else if("error"===e)o=function(e){let s=new m("error",{error:e,message:e.message});s[h]=this,_(t,this,s)};else{if("open"!==e)return;o=function(){let e=new p("open");e[h]=this,_(t,this,e)}}o[r]=!!s[r],o[i]=t,s.once?this.once(e,o):this.on(e,o)},removeEventListener(e,t){for(let s of this.listeners(e))if(s[i]===t&&!s[r]){this.removeListener(e,s);break}}};function _(e,t,s){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,s):e.call(t,s)}t.exports={CloseEvent:f,ErrorEvent:m,Event:p,EventTarget:y,MessageEvent:g}},96903,(e,t,s)=>{"use strict";let{tokenChars:r}=e.r(58739);function i(e,t,s){void 0===e[t]?e[t]=[s]:e[t].push(s)}t.exports={format:function(e){return Object.keys(e).map(t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map(e=>[t].concat(Object.keys(e).map(t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map(e=>!0===e?t:`${t}=${e}`).join("; ")})).join("; ")).join(", ")}).join(", ")},parse:function(e){let t,s,o=Object.create(null),n=Object.create(null),a=!1,l=!1,c=!1,h=-1,d=-1,u=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),void 0===t)if(-1===u&&1===r[d])-1===h&&(h=p);else if(0!==p&&(32===d||9===d))-1===u&&-1!==h&&(u=p);else if(59===d||44===d){if(-1===h)throw SyntaxError(`Unexpected character at index ${p}`);-1===u&&(u=p);let s=e.slice(h,u);44===d?(i(o,s,n),n=Object.create(null)):t=s,h=u=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(void 0===s)if(-1===u&&1===r[d])-1===h&&(h=p);else if(32===d||9===d)-1===u&&-1!==h&&(u=p);else if(59===d||44===d){if(-1===h)throw SyntaxError(`Unexpected character at index ${p}`);-1===u&&(u=p),i(n,e.slice(h,u),!0),44===d&&(i(o,t,n),n=Object.create(null),t=void 0),h=u=-1}else if(61===d&&-1!==h&&-1===u)s=e.slice(h,p),h=u=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(l){if(1!==r[d])throw SyntaxError(`Unexpected character at index ${p}`);-1===h?h=p:a||(a=!0),l=!1}else if(c)if(1===r[d])-1===h&&(h=p);else if(34===d&&-1!==h)c=!1,u=p;else if(92===d)l=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(34===d&&61===e.charCodeAt(p-1))c=!0;else if(-1===u&&1===r[d])-1===h&&(h=p);else if(-1!==h&&(32===d||9===d))-1===u&&(u=p);else if(59===d||44===d){if(-1===h)throw SyntaxError(`Unexpected character at index ${p}`);-1===u&&(u=p);let r=e.slice(h,u);a&&(r=r.replace(/\\/g,""),a=!1),i(n,s,r),44===d&&(i(o,t,n),n=Object.create(null),t=void 0),s=void 0,h=u=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(-1===h||c||32===d||9===d)throw SyntaxError("Unexpected end of input");-1===u&&(u=p);let f=e.slice(h,u);return void 0===t?i(o,f,n):(void 0===s?i(n,f,!0):a?i(n,s,f.replace(/\\/g,"")):i(n,s,f),i(o,t,n)),o}}},35065,(e,t,s)=>{"use strict";let r=e.r(27699),i=e.r(24836),o=e.r(21517),n=e.r(4446),a=e.r(55004),{randomBytes:l,createHash:c}=e.r(54799),{Duplex:h,Readable:d}=e.r(88947),{URL:u}=e.r(92509),p=e.r(80295),f=e.r(29485),m=e.r(16735),{isBlob:g}=e.r(58739),{BINARY_TYPES:y,CLOSE_TIMEOUT:_,EMPTY_BUFFER:S,GUID:b,kForOnEventAttribute:k,kListener:x,kStatusCode:v,kWebSocket:w,NOOP:E}=e.r(74836),{EventTarget:{addEventListener:L,removeEventListener:P}}=e.r(70494),{format:T,parse:O}=e.r(96903),{toBuffer:C}=e.r(97970),A=Symbol("kAborted"),N=[8,13],I=["CONNECTING","OPEN","CLOSING","CLOSED"],R=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class D extends r{constructor(e,t,s){super(),this._binaryType=y[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=S,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=D.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=[]:Array.isArray(t)||("object"==typeof t&&null!==t?(s=t,t=[]):t=[t]),U(this,e,t,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){y.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,t,s){let r=new f({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),i=new m(e,this._extensions,s.generateMask);this._receiver=r,this._sender=i,this._socket=e,r[w]=this,i[w]=this,e[w]=this,r.on("conclude",j),r.on("drain",z),r.on("error",G),r.on("message",q),r.on("ping",H),r.on("pong",K),i.onerror=J,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",X),e.on("data",Q),e.on("end",ee),e.on("error",et),this._readyState=D.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=D.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[p.extensionName]&&this._extensions[p.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=D.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==D.CLOSED){if(this.readyState===D.CONNECTING){let e="WebSocket was closed before the connection was established";W(this,this._req,e);return}if(this.readyState===D.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=D.CLOSING,this._sender.close(e,t,!this._isServer,e=>{!e&&(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Z(this)}}pause(){this.readyState!==D.CONNECTING&&this.readyState!==D.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,s){if(this.readyState===D.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");("function"==typeof e?(s=e,e=t=void 0):"function"==typeof t&&(s=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState!==D.OPEN)?B(this,e,s):(void 0===t&&(t=!this._isServer),this._sender.ping(e||S,t,s))}pong(e,t,s){if(this.readyState===D.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");("function"==typeof e?(s=e,e=t=void 0):"function"==typeof t&&(s=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState!==D.OPEN)?B(this,e,s):(void 0===t&&(t=!this._isServer),this._sender.pong(e||S,t,s))}resume(){this.readyState!==D.CONNECTING&&this.readyState!==D.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,s){if(this.readyState===D.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(s=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==D.OPEN)return void B(this,e,s);let r={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[p.extensionName]||(r.compress=!1),this._sender.send(e||S,r,s)}terminate(){if(this.readyState!==D.CLOSED){if(this.readyState===D.CONNECTING){let e="WebSocket was closed before the connection was established";W(this,this._req,e);return}this._socket&&(this._readyState=D.CLOSING,this._socket.destroy())}}}function U(e,t,s,r){let n,a,h,d,f={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:N[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:0x6400000,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=f.autoPong,e._closeTimeout=f.closeTimeout,!N.includes(f.protocolVersion))throw RangeError(`Unsupported protocol version: ${f.protocolVersion} (supported versions: ${N.join(", ")})`);if(t instanceof u)n=t;else try{n=new u(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}"http:"===n.protocol?n.protocol="ws:":"https:"===n.protocol&&(n.protocol="wss:"),e._url=n.href;let m="wss:"===n.protocol,g="ws+unix:"===n.protocol;if("ws:"===n.protocol||m||g?g&&!n.pathname?a="The URL's pathname is empty":n.hash&&(a="The URL contains a fragment identifier"):a='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"',a){let t=SyntaxError(a);if(0!==e._redirects)return void M(e,t);throw t}let y=m?443:80,S=l(16).toString("base64"),k=m?i.request:o.request,x=new Set;if(f.createConnection=f.createConnection||(m?F:$),f.defaultPort=f.defaultPort||y,f.port=n.port||y,f.host=n.hostname.startsWith("[")?n.hostname.slice(1,-1):n.hostname,f.headers={...f.headers,"Sec-WebSocket-Version":f.protocolVersion,"Sec-WebSocket-Key":S,Connection:"Upgrade",Upgrade:"websocket"},f.path=n.pathname+n.search,f.timeout=f.handshakeTimeout,f.perMessageDeflate&&(h=new p({...f.perMessageDeflate,isServer:!1,maxPayload:f.maxPayload}),f.headers["Sec-WebSocket-Extensions"]=T({[p.extensionName]:h.offer()})),s.length){for(let e of s){if("string"!=typeof e||!R.test(e)||x.has(e))throw SyntaxError("An invalid or duplicated subprotocol was specified");x.add(e)}f.headers["Sec-WebSocket-Protocol"]=s.join(",")}if(f.origin&&(f.protocolVersion<13?f.headers["Sec-WebSocket-Origin"]=f.origin:f.headers.Origin=f.origin),(n.username||n.password)&&(f.auth=`${n.username}:${n.password}`),g){let e=f.path.split(":");f.socketPath=e[0],f.path=e[1]}if(f.followRedirects){if(0===e._redirects){e._originalIpc=g,e._originalSecure=m,e._originalHostOrSocketPath=g?f.socketPath:n.host;let t=r&&r.headers;if(r={...r,headers:{}},t)for(let[e,s]of Object.entries(t))r.headers[e.toLowerCase()]=s}else if(0===e.listenerCount("redirect")){let t=g?!!e._originalIpc&&f.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&n.host===e._originalHostOrSocketPath;t&&(!e._originalSecure||m)||(delete f.headers.authorization,delete f.headers.cookie,t||delete f.headers.host,f.auth=void 0)}f.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(f.auth).toString("base64")),d=e._req=k(f),e._redirects&&e.emit("redirect",e.url,d)}else d=e._req=k(f);f.timeout&&d.on("timeout",()=>{W(e,d,"Opening handshake has timed out")}),d.on("error",t=>{null===d||d[A]||(d=e._req=null,M(e,t))}),d.on("response",i=>{let o=i.headers.location,n=i.statusCode;if(o&&f.followRedirects&&n>=300&&n<400){let i;if(++e._redirects>f.maxRedirects)return void W(e,d,"Maximum redirects exceeded");d.abort();try{i=new u(o,t)}catch(t){M(e,SyntaxError(`Invalid URL: ${o}`));return}U(e,i,s,r)}else e.emit("unexpected-response",d,i)||W(e,d,`Unexpected server response: ${i.statusCode}`)}),d.on("upgrade",(t,s,r)=>{let i;if(e.emit("upgrade",t),e.readyState!==D.CONNECTING)return;d=e._req=null;let o=t.headers.upgrade;if(void 0===o||"websocket"!==o.toLowerCase())return void W(e,s,"Invalid Upgrade header");let n=c("sha1").update(S+b).digest("base64");if(t.headers["sec-websocket-accept"]!==n)return void W(e,s,"Invalid Sec-WebSocket-Accept header");let a=t.headers["sec-websocket-protocol"];if(void 0!==a?x.size?x.has(a)||(i="Server sent an invalid subprotocol"):i="Server sent a subprotocol but none was requested":x.size&&(i="Server sent no subprotocol"),i)return void W(e,s,i);a&&(e._protocol=a);let l=t.headers["sec-websocket-extensions"];if(void 0!==l){let t;if(!h)return void W(e,s,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");try{t=O(l)}catch(t){W(e,s,"Invalid Sec-WebSocket-Extensions header");return}let r=Object.keys(t);if(1!==r.length||r[0]!==p.extensionName)return void W(e,s,"Server indicated an extension that was not requested");try{h.accept(t[p.extensionName])}catch(t){W(e,s,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[p.extensionName]=h}e.setSocket(s,r,{allowSynchronousEvents:f.allowSynchronousEvents,generateMask:f.generateMask,maxBufferedChunks:f.maxBufferedChunks,maxFragments:f.maxFragments,maxPayload:f.maxPayload,skipUTF8Validation:f.skipUTF8Validation})}),f.finishRequest?f.finishRequest(d,e):d.end()}function M(e,t){e._readyState=D.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function $(e){return e.path=e.socketPath,n.connect(e)}function F(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=n.isIP(e.host)?"":e.host),a.connect(e)}function W(e,t,s){e._readyState=D.CLOSING;let r=Error(s);Error.captureStackTrace(r,W),t.setHeader?(t[A]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(M,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function B(e,t,s){if(t){let s=g(t)?t.size:C(t).length;e._socket?e._sender._bufferedBytes+=s:e._bufferedAmount+=s}if(s){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${I[e.readyState]})`);process.nextTick(s,t)}}function j(e,t){let s=this[w];s._closeFrameReceived=!0,s._closeMessage=t,s._closeCode=e,void 0!==s._socket[w]&&(s._socket.removeListener("data",Q),process.nextTick(Y,s._socket),1005===e?s.close():s.close(e,t))}function z(){let e=this[w];e.isPaused||e._socket.resume()}function G(e){let t=this[w];void 0!==t._socket[w]&&(t._socket.removeListener("data",Q),process.nextTick(Y,t._socket),t.close(e[v])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function V(){this[w].emitClose()}function q(e,t){this[w].emit("message",e,t)}function H(e){let t=this[w];t._autoPong&&t.pong(e,!this._isServer,E),t.emit("ping",e)}function K(e){this[w].emit("pong",e)}function Y(e){e.resume()}function J(e){let t=this[w];t.readyState!==D.CLOSED&&(t.readyState===D.OPEN&&(t._readyState=D.CLOSING,Z(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function Z(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function X(){let e=this[w];if(this.removeListener("close",X),this.removeListener("data",Q),this.removeListener("end",ee),e._readyState=D.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&0!==this._readableState.length){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[w]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",V),e._receiver.on("finish",V))}function Q(e){this[w]._receiver.write(e)||this.pause()}function ee(){let e=this[w];e._readyState=D.CLOSING,e._receiver.end(),this.end()}function et(){let e=this[w];this.removeListener("error",et),this.on("error",E),e&&(e._readyState=D.CLOSING,this.destroy())}Object.defineProperty(D,"CONNECTING",{enumerable:!0,value:I.indexOf("CONNECTING")}),Object.defineProperty(D.prototype,"CONNECTING",{enumerable:!0,value:I.indexOf("CONNECTING")}),Object.defineProperty(D,"OPEN",{enumerable:!0,value:I.indexOf("OPEN")}),Object.defineProperty(D.prototype,"OPEN",{enumerable:!0,value:I.indexOf("OPEN")}),Object.defineProperty(D,"CLOSING",{enumerable:!0,value:I.indexOf("CLOSING")}),Object.defineProperty(D.prototype,"CLOSING",{enumerable:!0,value:I.indexOf("CLOSING")}),Object.defineProperty(D,"CLOSED",{enumerable:!0,value:I.indexOf("CLOSED")}),Object.defineProperty(D.prototype,"CLOSED",{enumerable:!0,value:I.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(D.prototype,e,{enumerable:!0})}),["open","error","close","message"].forEach(e=>{Object.defineProperty(D.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[k])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[k]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[k]:!0})}})}),D.prototype.addEventListener=L,D.prototype.removeEventListener=P,t.exports=D},21365,(e,t,s)=>{"use strict";e.r(35065);let{Duplex:r}=e.r(88947);function i(e){e.emit("close")}function o(){!this.destroyed&&this._writableState.finished&&this.destroy()}function n(e){this.removeListener("error",n),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}t.exports=function(e,t){let s=!0,a=new r({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(t,s){let r=!s&&a._readableState.objectMode?t.toString():t;a.push(r)||e.pause()}),e.once("error",function(e){a.destroyed||(s=!1,a.destroy(e))}),e.once("close",function(){a.destroyed||a.push(null)}),a._destroy=function(t,r){if(e.readyState===e.CLOSED){r(t),process.nextTick(i,a);return}let o=!1;e.once("error",function(e){o=!0,r(e)}),e.once("close",function(){o||r(t),process.nextTick(i,a)}),s&&e.terminate()},a._final=function(t){e.readyState===e.CONNECTING?e.once("open",function(){a._final(t)}):null!==e._socket&&(e._socket._writableState.finished?(t(),a._readableState.endEmitted&&a.destroy()):(e._socket.once("finish",function(){t()}),e.close()))},a._read=function(){e.isPaused&&e.resume()},a._write=function(t,s,r){e.readyState===e.CONNECTING?e.once("open",function(){a._write(t,s,r)}):e.send(t,r)},a.on("end",o),a.on("error",n),a}},42977,(e,t,s)=>{"use strict";let{tokenChars:r}=e.r(58739);t.exports={parse:function(e){let t=new Set,s=-1,i=-1,o=0;for(;o<e.length;o++){let n=e.charCodeAt(o);if(-1===i&&1===r[n])-1===s&&(s=o);else if(0!==o&&(32===n||9===n))-1===i&&-1!==s&&(i=o);else if(44===n){if(-1===s)throw SyntaxError(`Unexpected character at index ${o}`);-1===i&&(i=o);let r=e.slice(s,i);if(t.has(r))throw SyntaxError(`The "${r}" subprotocol is duplicated`);t.add(r),s=i=-1}else throw SyntaxError(`Unexpected character at index ${o}`)}if(-1===s||-1!==i)throw SyntaxError("Unexpected end of input");let n=e.slice(s,o);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);return t.add(n),t}}},17198,(e,t,s)=>{"use strict";let r=e.r(27699),i=e.r(21517),{Duplex:o}=e.r(88947),{createHash:n}=e.r(54799),a=e.r(96903),l=e.r(80295),c=e.r(42977),h=e.r(35065),{CLOSE_TIMEOUT:d,GUID:u,kWebSocket:p}=e.r(74836),f=/^[+/0-9A-Za-z]{22}==$/,m=0,g=1,y=2;class _ extends r{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1048576,maxFragments:131072,maxPayload:0x6400000,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:d,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:h,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=i.createServer((e,t)=>{let s=i.STATUS_CODES[426];t.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),t.end(s)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=S(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,s,r)=>{this.handleUpgrade(t,s,r,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=m}address(){if(this.options.noServer)throw Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===y){e&&this.once("close",()=>{e(Error("The server is not running"))}),process.nextTick(b,this);return}if(e&&this.once("close",e),this._state!==g)if(this._state=g,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(b,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{b(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,s,r){t.on("error",k);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,n=+e.headers["sec-websocket-version"];if("GET"!==e.method)return void v(this,e,t,405,"Invalid HTTP method");if(void 0===o||"websocket"!==o.toLowerCase())return void v(this,e,t,400,"Invalid Upgrade header");if(void 0===i||!f.test(i))return void v(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");if(13!==n&&8!==n)return void v(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});if(!this.shouldHandle(e))return void x(t,400);let h=e.headers["sec-websocket-protocol"],d=new Set;if(void 0!==h)try{d=c.parse(h)}catch(s){v(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&void 0!==u){let s=new l({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let e=a.parse(u);e[l.extensionName]&&(s.accept(e[l.extensionName]),p[l.extensionName]=s)}catch(s){v(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let o={origin:e.headers[`${8===n?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(o,(o,n,a,l)=>{if(!o)return x(t,n||401,a,l);this.completeUpgrade(p,i,d,e,t,s,r)});if(!this.options.verifyClient(o))return x(t,401)}this.completeUpgrade(p,i,d,e,t,s,r)}completeUpgrade(e,t,s,r,i,o,c){if(!i.readable||!i.writable)return i.destroy();if(i[p])throw Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>m)return x(i,503);let h=n("sha1").update(t+u).digest("base64"),d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${h}`],f=new this.options.WebSocket(null,void 0,this.options);if(s.size){let e=this.options.handleProtocols?this.options.handleProtocols(s,r):s.values().next().value;e&&(d.push(`Sec-WebSocket-Protocol: ${e}`),f._protocol=e)}if(e[l.extensionName]){let t=e[l.extensionName].params,s=a.format({[l.extensionName]:[t]});d.push(`Sec-WebSocket-Extensions: ${s}`),f._extensions=e}this.emit("headers",d,r),i.write(d.concat("\r\n").join("\r\n")),i.removeListener("error",k),f.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(f),f.on("close",()=>{this.clients.delete(f),this._shouldEmitClose&&!this.clients.size&&process.nextTick(b,this)})),c(f,r)}}function S(e,t){for(let s of Object.keys(t))e.on(s,t[s]);return function(){for(let s of Object.keys(t))e.removeListener(s,t[s])}}function b(e){e._state=y,e.emit("close")}function k(){this.destroy()}function x(e,t,s,r){s=s||i.STATUS_CODES[t],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(s),...r},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${i.STATUS_CODES[t]}\r
|
|
2
|
-
`+Object.keys(r).map(e=>`${e}: ${r[e]}`).join("\r\n")+"\r\n\r\n"+s)}function v(e,t,s,r,i,o){if(e.listenerCount("wsClientError")){let r=Error(i);Error.captureStackTrace(r,v),e.emit("wsClientError",r,s,t)}else x(s,r,i,o)}t.exports=_},29307,10928,__turbopack_context__=>{"use strict";var __TURBOPACK__imported__module__54799__=__turbopack_context__.i(54799),__TURBOPACK__imported__module__22734__=__turbopack_context__.i(22734),__TURBOPACK__imported__module__14747__=__turbopack_context__.i(14747),__TURBOPACK__imported__module__98003__=__turbopack_context__.i(98003),__TURBOPACK__imported__module__22734__1=__TURBOPACK__imported__module__22734__,__TURBOPACK__imported__module__14747__1=__TURBOPACK__imported__module__14747__,__TURBOPACK__imported__module__98003__1=__TURBOPACK__imported__module__98003__;class SessionPersister{static pendingSaves=new Map;static pendingData=new Map;static getSessionsDir(){let e=__TURBOPACK__imported__module__14747__1.default.join((0,__TURBOPACK__imported__module__98003__1.getConfigDir)(),"sessions");return __TURBOPACK__imported__module__22734__1.default.existsSync(e)||__TURBOPACK__imported__module__22734__1.default.mkdirSync(e,{recursive:!0}),e}static saveSession(e,t=!1){let s={id:e.id,name:e.name,type:e.type,status:"running"===e.status&&"mock"===e.type?"running":e.status,createdAt:e.createdAt,logs:e.logs,workspaceRoot:e.workspaceRoot,scopedDirs:e.scopedDirs,lastSyncedWorkspaceFolders:e.lastSyncedWorkspaceFolders,model:e.model};if(t){let t=this.pendingSaves.get(e.id);t&&(clearTimeout(t),this.pendingSaves.delete(e.id)),this.pendingData.delete(e.id),this.writeToDisk(e.id,s);return}if(this.pendingData.set(e.id,s),!this.pendingSaves.has(e.id)){let t=setTimeout(()=>{this.pendingSaves.delete(e.id);let t=this.pendingData.get(e.id);t&&(this.pendingData.delete(e.id),this.writeToDisk(e.id,t))},1e3);this.pendingSaves.set(e.id,t)}}static writeToDisk(e,t){try{let s=this.getSessionsDir(),r=__TURBOPACK__imported__module__14747__1.default.join(s,`${e}.json`),i=JSON.stringify(t,null,2),o=`${r}.tmp-${process.pid}-${Date.now()}`;__TURBOPACK__imported__module__22734__1.default.writeFile(o,i,"utf8",t=>{if(t)return void console.error(`[SessionPersister] Failed to save session ${e}:`,t);let s=t=>{__TURBOPACK__imported__module__22734__1.default.rename(o,r,n=>{if(!n)return;let a=n.code;("EPERM"===a||"EACCES"===a||"EBUSY"===a)&&t>0?setTimeout(()=>s(t-1),60):__TURBOPACK__imported__module__22734__1.default.writeFile(r,i,"utf8",t=>{t&&console.error(`[SessionPersister] Failed to save session ${e}:`,t),__TURBOPACK__imported__module__22734__1.default.unlink(o,()=>{})})})};s(5)})}catch(t){console.error(`[SessionPersister] Failed to save session ${e}:`,t)}}static loadAllSessions(){try{let e=this.getSessionsDir(),t=__TURBOPACK__imported__module__22734__1.default.readdirSync(e),s=[];for(let r of t)if(r.endsWith(".json")){let t=__TURBOPACK__imported__module__14747__1.default.join(e,r);try{let e=__TURBOPACK__imported__module__22734__1.default.readFileSync(t,"utf8"),r=JSON.parse(e);"running"===r.status&&"mock"!==r.type&&(r.status="stopped",r.logs.push("\r\n\x1b[1;31m[System] Server restarted. Terminal connection lost.\x1b[0m\r\n"),__TURBOPACK__imported__module__22734__1.default.writeFileSync(t,JSON.stringify(r,null,2),"utf8")),s.push(r)}catch(e){console.error(`[SessionPersister] Failed to load session file ${r}:`,e)}}return s}catch(e){return console.error("[SessionPersister] Failed to load sessions:",e),[]}}static cancelPendingSave(e){let t=this.pendingSaves.get(e);t&&(clearTimeout(t),this.pendingSaves.delete(e)),this.pendingData.delete(e)}static deleteSession(e){this.cancelPendingSave(e);try{let t=this.getSessionsDir(),s=__TURBOPACK__imported__module__14747__1.default.join(t,`${e}.json`);__TURBOPACK__imported__module__22734__1.default.existsSync(s)&&__TURBOPACK__imported__module__22734__1.default.unlinkSync(s)}catch(t){console.error(`[SessionPersister] Failed to delete session ${e}:`,t)}}}__turbopack_context__.s(["SessionPersister",0,SessionPersister],10928);let M=1e6,MODEL_RATES={"claude-opus-4":{input:15/M,output:75/M},"claude-sonnet-4":{input:3/M,output:15/M},"claude-haiku-4":{input:1/M,output:5/M},"claude-3-5-sonnet":{input:3/M,output:15/M},"claude-3-5-haiku":{input:.8/M,output:4/M},"claude-3-opus":{input:15/M,output:75/M},"gpt-4o":{input:2.5/M,output:10/M},"gpt-4o-mini":{input:.15/M,output:.6/M},"gpt-4-turbo":{input:10/M,output:30/M}},DEFAULT_MODEL="claude-sonnet-4";function getModelRate(e){if(e){let t=e.toLowerCase();if(MODEL_RATES[t])return MODEL_RATES[t];for(let e of Object.keys(MODEL_RATES))if(t.includes(e))return MODEL_RATES[e]}return MODEL_RATES[DEFAULT_MODEL]}function estimateCost(e,t,s){let r=getModelRate(s);return e*r.input+t*r.output}var __TURBOPACK__imported__module__22734__2=__TURBOPACK__imported__module__22734__,__TURBOPACK__imported__module__14747__2=__TURBOPACK__imported__module__14747__,__TURBOPACK__imported__module__46786__=__turbopack_context__.i(46786),__TURBOPACK__imported__module__98003__2=__TURBOPACK__imported__module__98003__;function isWindows(){let proc=eval("process");return"win32"===proc.platform}function findGitBash(){if(!isWindows())return"bash";let e=process.env.PROGRAMFILES||"C:\\Program Files",t=process.env["PROGRAMFILES(X86)"]||"C:\\Program Files (x86)",s=process.env.LOCALAPPDATA||"";return[process.env.WINGMAN_BASH_PATH,__TURBOPACK__imported__module__14747__2.default.join(e,"Git","bin","bash.exe"),__TURBOPACK__imported__module__14747__2.default.join(t,"Git","bin","bash.exe"),s?__TURBOPACK__imported__module__14747__2.default.join(s,"Programs","Git","bin","bash.exe"):""].filter(e=>"string"==typeof e&&""!==e).find(e=>__TURBOPACK__imported__module__22734__2.default.existsSync(e))||null}function findInteractiveShell(){let e=findGitBash();if(e)return e;if(!isWindows())return null;let t=process.env.windir||process.env.SystemRoot||"C:\\Windows",s=__TURBOPACK__imported__module__14747__2.default.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(__TURBOPACK__imported__module__22734__2.default.existsSync(s))return s;let r=process.env.COMSPEC;if(r&&__TURBOPACK__imported__module__22734__2.default.existsSync(r))return r;let i=__TURBOPACK__imported__module__14747__2.default.join(t,"System32","cmd.exe");return __TURBOPACK__imported__module__22734__2.default.existsSync(i)?i:r||"cmd.exe"}let cachedPty=null;function loadNodePty(){return cachedPty||(cachedPty=eval("require")("node-pty")),cachedPty}function loadClaudeExtraFlags(e){if(e)return"--resume";let t=__TURBOPACK__imported__module__14747__2.default.join((0,__TURBOPACK__imported__module__98003__2.getConfigDir)(),"claude.json");if(__TURBOPACK__imported__module__22734__2.default.existsSync(t))try{let e=JSON.parse(__TURBOPACK__imported__module__22734__2.default.readFileSync(t,"utf8"));if(e.extraFlags)return e.extraFlags}catch(e){console.error("Failed to parse Claude configuration:",e)}return""}function windowsPathOverride(){return["C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\MSBuild\\Microsoft\\VisualStudio\\NodeJs",__TURBOPACK__imported__module__14747__2.default.join(__TURBOPACK__imported__module__46786__.default.homedir(),"AppData","Local","npm"),process.env.Path||process.env.PATH||""].filter(Boolean).join(";")}let MAX_LOG_LINES=5e3;class AgentRunner{workspaceRoot;scopedDirs;lastSyncedWorkspaceFolders;tokenUsage={input:0,output:0,cost:0};agentState="idle";model;hasAnalyzedInitialState=!1;stateTimer=null;idleTimer=null;lastLoggedUsage={input:0,output:0,cost:0};resetInitialStateAnalysis(){this.hasAnalyzedInitialState=!1}logTokenUsageUpdate(){if(this.tokenUsage.input===this.lastLoggedUsage.input&&this.tokenUsage.output===this.lastLoggedUsage.output&&this.tokenUsage.cost===this.lastLoggedUsage.cost)return;let e=this.tokenUsage.input-this.lastLoggedUsage.input,t=this.tokenUsage.output-this.lastLoggedUsage.output,s=this.tokenUsage.cost-this.lastLoggedUsage.cost;if(e>0||t>0||s>0)try{let r=(0,__TURBOPACK__imported__module__98003__.getConfigDir)(),i=__TURBOPACK__imported__module__14747__.default.join(r,"token-history.json"),o=[];if(__TURBOPACK__imported__module__22734__.default.existsSync(i))try{o=JSON.parse(__TURBOPACK__imported__module__22734__.default.readFileSync(i,"utf8"))||[]}catch{o=[]}o.push({timestamp:new Date().toISOString(),sessionId:this.id,sessionName:this.name,type:this.type,inputTokens:e>0?e:0,outputTokens:t>0?t:0,cost:s>0?s:0,totalInput:this.tokenUsage.input,totalOutput:this.tokenUsage.output,totalCost:this.tokenUsage.cost}),__TURBOPACK__imported__module__22734__.default.writeFileSync(i,JSON.stringify(o,null,2),"utf8"),this.lastLoggedUsage={...this.tokenUsage}}catch(e){console.error("[AgentRunner] Failed to log token usage transaction:",e)}}parseTokenUsage(e){let t=e.replace(/\x1b\[[0-9;]*m/g,""),s=t.match(/(?:cost|estimated cost)[:\s]*\$([0-9.]+)/i);s&&(this.tokenUsage.cost=parseFloat(s[1]));let r=e=>(e=e.replace(/,/g,"").toLowerCase().trim()).endsWith("k")?1e3*parseFloat(e.slice(0,-1)):e.endsWith("m")?1e6*parseFloat(e.slice(0,-1)):parseInt(e,10)||0,i=/tokens?[:\s]*([0-9,.]+[km]?)\s*(?:sent|input|prompt)[^a-zA-Z0-9]+([0-9,.]+[km]?)\s*(?:received|output|completion)/i,o=t.match(i);if(o)this.tokenUsage.input=r(o[1]),this.tokenUsage.output=r(o[2]);else{let e=t.match(/([0-9,.]+[km]?)\s*(?:sent|input|prompt)\s*tokens?/i)||t.match(/tokens?\s*(?:sent|input|prompt)[:\s]*([0-9,.]+[km]?)/i);e&&(this.tokenUsage.input=r(e[1]));let s=t.match(/([0-9,.]+[km]?)\s*(?:received|output|completion)\s*tokens?/i)||t.match(/tokens?\s*(?:received|output|completion)[:\s]*([0-9,.]+[km]?)/i);s&&(this.tokenUsage.output=r(s[1]))}0===this.tokenUsage.cost&&(this.tokenUsage.input>0||this.tokenUsage.output>0)&&(this.tokenUsage.cost=estimateCost(this.tokenUsage.input,this.tokenUsage.output,this.model)),this.logTokenUsageUpdate()}getStatus(){return this.hasAnalyzedInitialState||"running"!==this.status||(this.analyzeState(),this.hasAnalyzedInitialState=!0),{id:this.id,name:this.name,type:this.type,status:this.status,createdAt:this.createdAt,logsCount:this.logs.length,workspaceRoot:this.workspaceRoot||("shell"===this.type?process.env.ORIGINAL_CWD||process.cwd():void 0),scopedDirs:this.scopedDirs,lastSyncedWorkspaceFolders:this.lastSyncedWorkspaceFolders,tokenUsage:this.tokenUsage,agentState:this.agentState,model:this.model}}resize(e,t){}getPid(){}listeners=[];onOutput(e){this.listeners.push(e)}offOutput(e){this.listeners=this.listeners.filter(t=>t!==e)}emitOutput(e){this.updateAgentState(e),this.listeners.forEach(t=>t(e))}parseTokensOnLog=!0;persistOnLog=!0;appendLog(e){this.logs.push(e),this.logs.length>MAX_LOG_LINES&&this.logs.shift(),this.parseTokensOnLog&&this.parseTokenUsage(e),this.emitOutput(e),this.persistOnLog&&SessionPersister.saveSession(this)}async writeToPty(e,t){if(!e)return;let s=isWindows(),r=t.includes("\x1b[200~");if(s&&t.length>100&&!r){let s=128;for(let r=0;r<t.length;r+=s){let i=t.slice(r,r+s);e.write(i),await new Promise(e=>setTimeout(e,10))}}else e.write(t)}updateAgentState(e){if("running"!==this.status){this.agentState="idle";return}let t=/\[Telemetry\]/i.test(e);e.trim().length>0&&!t&&(this.agentState="thinking"),this.stateTimer&&clearTimeout(this.stateTimer),this.stateTimer=setTimeout(()=>{this.analyzeState()},800)}analyzeState(){if("running"!==this.status){this.agentState="idle";return}let e=this.logs.filter(e=>!/\[Telemetry\]/i.test(e)).slice(-5).join("").replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"").trim(),t=e.endsWith(">")||e.endsWith("> ")||/([a-zA-Z0-9_-]+>\s*)$/.test(e)||e.endsWith("$")||e.endsWith("$ "),s=/(\[y\/n\]|\(y\/n\)|\?|confirm|allow|should I|would you|press enter|proceed)/i.test(e);t?("thinking"===this.agentState||"needs-input"===this.agentState)&&(this.agentState="complete",this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{"complete"===this.agentState&&(this.agentState="idle")},5e3)):s&&(this.agentState="needs-input")}}class MockRunner extends AgentRunner{id;name;type="mock";status="idle";createdAt;logs=[];intervalId=null;awaitingConfirmation=!1;mockSteps=["[NeuralLoom] Loading virtual PTY context...","[NeuralLoom] Spawning sandbox mock runtime environment...","[Mock Agent] Model online (v2.0-mock-flash). Dedicated memory allocated.","[Mock Agent] System rules parsed successfully from global context registry.","[Mock Agent] Awaiting developer commands. Type '/help' to list mock skills.","mock-agent> "];stepIndex=0;constructor(e,t){super(),this.id=e,this.name=t||`Mock Session ${e.substring(0,8)}`,this.createdAt=new Date().toISOString()}appendLog(e){this.logs.push(e),this.parseTokenUsage(e),this.emitOutput(e+"\r\n"),SessionPersister.saveSession(this)}async start(e){"running"!==this.status&&(this.status="running",this.appendLog("\x1b[1;35m==================================================\x1b[0m"),this.appendLog("\x1b[1;36m NEURALLOOM SIMULATED AGENT ENVIRONMENT \x1b[0m"),this.appendLog("\x1b[1;35m==================================================\x1b[0m"),this.stepIndex<this.mockSteps.length&&this.appendLog(this.mockSteps[this.stepIndex++]),this.intervalId=setInterval(()=>{if(this.tokenUsage.input+=Math.floor(50*Math.random())+10,this.tokenUsage.output+=Math.floor(20*Math.random())+5,this.tokenUsage.cost=3e-6*this.tokenUsage.input+15e-6*this.tokenUsage.output,this.stepIndex<this.mockSteps.length)this.appendLog(this.mockSteps[this.stepIndex++]);else{let e=new Date().toLocaleTimeString();this.appendLog(`[${e}] [Telemetry] CPU utilization 1.2% | Memory 142MB | Link stable.`)}},4e3))}async stop(){this.status="stopped",this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.appendLog("\x1b[1;31m[System] Process terminated. Connection closed.\x1b[0m")}async sendInput(e,t){"running"!==this.status?this.appendLog(`\x1b[1;31m[Error] Cannot write input: process is ${this.status}.\x1b[0m`):(this.appendLog(`\x1b[1;32m> ${e}\x1b[0m`),setTimeout(()=>{let t=e.trim().toLowerCase();if(this.awaitingConfirmation){if("y"===t||"yes"===t)this.appendLog("[Mock Agent] Proceeding with production deployment..."),setTimeout(()=>{this.appendLog("[Mock Agent] Deploying build artifacts to edge network..."),this.appendLog("[Mock Agent] Deployment complete. Site live!"),this.appendLog("mock-agent> ")},1e3);else{if("n"!==t&&"no"!==t)return void this.appendLog("[Mock Agent] Invalid input. Please confirm with y/n:");this.appendLog("[Mock Agent] Deployment aborted."),this.appendLog("mock-agent> ")}this.awaitingConfirmation=!1;return}"/help"===t?(this.appendLog("[Mock Agent] Available commands:"),this.appendLog(" /help - List available mock commands."),this.appendLog(" /status - Fetch current agent diagnostic metrics."),this.appendLog(" /context - View loaded staging files."),this.appendLog(" /deploy - Trigger production deployment wizard (requires confirmation)."),this.appendLog(" /clear - Flush terminal console buffer."),this.appendLog("mock-agent> ")):"/status"===t?(this.appendLog("[Mock Agent] Diagnostics:"),this.appendLog(" - Connection Type: WebSocket gateway (mock)"),this.appendLog(` - Active Runtime: ${this.id}`),this.appendLog(" - Sandbox State: Healthy (0 warnings)"),this.appendLog("mock-agent> ")):"/context"===t?(this.appendLog("[Mock Agent] Loaded Workspace Context Files:"),this.appendLog(" - [Mounted] src/app/globals.css (Modified)"),this.appendLog(" - [Mounted] src/app/page.tsx"),this.appendLog("mock-agent> ")):"/deploy"===t?(this.appendLog("[Mock Agent] Starting production deployment..."),this.appendLog("[Mock Agent] Warning: This will push current local build to server."),this.appendLog("[Mock Agent] Are you sure you want to proceed? (y/n)"),this.awaitingConfirmation=!0):"/clear"===t?(this.logs=[],this.appendLog("\x1b[1;33m[Console Cleared]\x1b[0m"),this.appendLog("mock-agent> ")):(this.appendLog(`[Mock Agent] Received command: "${e}". Processing...`),setTimeout(()=>{this.appendLog("[Mock Agent] Done. Task simulated successfully."),this.appendLog("mock-agent> ")},1500))},400))}}var __TURBOPACK__imported__module__22734__3=__TURBOPACK__imported__module__22734__,__TURBOPACK__imported__module__33405__=__turbopack_context__.i(33405);let CLAUDE_MODELS=[{alias:"",label:"Default (account)",versions:[]},{alias:"opus",label:"Opus (latest)",versions:["claude-opus-4-8"]},{alias:"sonnet",label:"Sonnet (latest)",versions:["claude-sonnet-4-6"]},{alias:"haiku",label:"Haiku (latest)",versions:["claude-haiku-4-5-20251001"]}],CUSTOM_MODEL="__custom__";function sanitizeModelArg(e){if(!e)return;let t=e.trim();if(t&&/^[A-Za-z0-9._:-]+$/.test(t))return t}function modelLabel(e){let t=sanitizeModelArg(e);if(!t)return"Default";let s=CLAUDE_MODELS.find(e=>e.alias===t||e.versions.includes(t));return s&&s.alias?s.label:t}class ClaudeRunner extends AgentRunner{id;name;type="claude";status="idle";createdAt;logs=[];ptyProcess=null;ptyModule=null;constructor(e,t){super(),this.id=e,this.name=t||`Claude Session ${e.substring(0,8)}`,this.createdAt=new Date().toISOString()}async start(e){if("running"===this.status)return;let t=isWindows(),s=t?process.env.COMSPEC||"cmd.exe":findGitBash();if(!s){this.status="stopped",this.appendLog("\x1b[1;31m[System Error] Shell not found. Cannot spawn terminal.\x1b[0m\r\n");return}let r=t?["/c"]:["-c"];try{this.ptyModule=loadNodePty(),this.status="running",this.appendLog("\x1b[1;35m==================================================\x1b[0m\r\n"),this.appendLog("\x1b[1;36m NEURALLOOM ACTIVE CLAUDE TERMINAL ROUTE \x1b[0m\r\n"),this.appendLog("\x1b[1;35m==================================================\x1b[0m\r\n");let t=this.workspaceRoot&&__TURBOPACK__imported__module__22734__3.default.existsSync(this.workspaceRoot)?this.workspaceRoot:process.env.ORIGINAL_CWD||process.cwd(),i=loadClaudeExtraFlags(e),o={...process.env,TERM:"xterm-256color",COLORTERM:"truecolor",CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN:"1"};if(isWindows()){let e=windowsPathOverride();for(let e of Object.keys(o))"path"===e.toLowerCase()&&delete o[e];o.Path=e,o.PATH=e}let n="claude";try{let e=isWindows()?"where.exe claude":"which claude";(0,__TURBOPACK__imported__module__33405__.execSync)(e,{env:o,stdio:"ignore"})}catch{n="npx -y @anthropic-ai/claude-code"}let a=sanitizeModelArg(this.model),l=a?`--model ${a}`:"",c=`${n} ${l} ${i}`.replace(/\s+/g," ").trim();this.appendLog(`[System] Spawning command: ${c}\r
|
|
2
|
+
`+Object.keys(r).map(e=>`${e}: ${r[e]}`).join("\r\n")+"\r\n\r\n"+s)}function v(e,t,s,r,i,o){if(e.listenerCount("wsClientError")){let r=Error(i);Error.captureStackTrace(r,v),e.emit("wsClientError",r,s,t)}else x(s,r,i,o)}t.exports=_},29307,10928,__turbopack_context__=>{"use strict";var __TURBOPACK__imported__module__54799__=__turbopack_context__.i(54799),__TURBOPACK__imported__module__22734__=__turbopack_context__.i(22734),__TURBOPACK__imported__module__14747__=__turbopack_context__.i(14747),__TURBOPACK__imported__module__98003__=__turbopack_context__.i(98003),__TURBOPACK__imported__module__22734__1=__TURBOPACK__imported__module__22734__,__TURBOPACK__imported__module__14747__1=__TURBOPACK__imported__module__14747__,__TURBOPACK__imported__module__98003__1=__TURBOPACK__imported__module__98003__;class SessionPersister{static pendingSaves=new Map;static pendingData=new Map;static getSessionsDir(){let e=__TURBOPACK__imported__module__14747__1.default.join((0,__TURBOPACK__imported__module__98003__1.getConfigDir)(),"sessions");return __TURBOPACK__imported__module__22734__1.default.existsSync(e)||__TURBOPACK__imported__module__22734__1.default.mkdirSync(e,{recursive:!0}),e}static saveSession(e,t=!1){let s={id:e.id,name:e.name,type:e.type,status:"running"===e.status&&"mock"===e.type?"running":e.status,createdAt:e.createdAt,logs:e.logs,workspaceRoot:e.workspaceRoot,scopedDirs:e.scopedDirs,lastSyncedWorkspaceFolders:e.lastSyncedWorkspaceFolders,model:e.model};if(t){let t=this.pendingSaves.get(e.id);t&&(clearTimeout(t),this.pendingSaves.delete(e.id)),this.pendingData.delete(e.id),this.writeToDisk(e.id,s);return}if(this.pendingData.set(e.id,s),!this.pendingSaves.has(e.id)){let t=setTimeout(()=>{this.pendingSaves.delete(e.id);let t=this.pendingData.get(e.id);t&&(this.pendingData.delete(e.id),this.writeToDisk(e.id,t))},1e3);this.pendingSaves.set(e.id,t)}}static writeToDisk(e,t){try{let s=this.getSessionsDir(),r=__TURBOPACK__imported__module__14747__1.default.join(s,`${e}.json`),i=JSON.stringify(t,null,2),o=`${r}.tmp-${process.pid}-${Date.now()}`;__TURBOPACK__imported__module__22734__1.default.writeFile(o,i,"utf8",t=>{if(t)return void console.error(`[SessionPersister] Failed to save session ${e}:`,t);let s=t=>{__TURBOPACK__imported__module__22734__1.default.rename(o,r,n=>{if(!n)return;let a=n.code;("EPERM"===a||"EACCES"===a||"EBUSY"===a)&&t>0?setTimeout(()=>s(t-1),60):__TURBOPACK__imported__module__22734__1.default.writeFile(r,i,"utf8",t=>{t&&console.error(`[SessionPersister] Failed to save session ${e}:`,t),__TURBOPACK__imported__module__22734__1.default.unlink(o,()=>{})})})};s(5)})}catch(t){console.error(`[SessionPersister] Failed to save session ${e}:`,t)}}static loadAllSessions(){try{let e=this.getSessionsDir(),t=__TURBOPACK__imported__module__22734__1.default.readdirSync(e),s=[];for(let r of t)if(r.endsWith(".json")){let t=__TURBOPACK__imported__module__14747__1.default.join(e,r);try{let e=__TURBOPACK__imported__module__22734__1.default.readFileSync(t,"utf8"),r=JSON.parse(e);"running"===r.status&&"mock"!==r.type&&(r.status="stopped",r.logs.push("\r\n\x1b[1;31m[System] Server restarted. Terminal connection lost.\x1b[0m\r\n"),__TURBOPACK__imported__module__22734__1.default.writeFileSync(t,JSON.stringify(r,null,2),"utf8")),s.push(r)}catch(e){console.error(`[SessionPersister] Failed to load session file ${r}:`,e)}}return s}catch(e){return console.error("[SessionPersister] Failed to load sessions:",e),[]}}static cancelPendingSave(e){let t=this.pendingSaves.get(e);t&&(clearTimeout(t),this.pendingSaves.delete(e)),this.pendingData.delete(e)}static deleteSession(e){this.cancelPendingSave(e);try{let t=this.getSessionsDir(),s=__TURBOPACK__imported__module__14747__1.default.join(t,`${e}.json`);__TURBOPACK__imported__module__22734__1.default.existsSync(s)&&__TURBOPACK__imported__module__22734__1.default.unlinkSync(s)}catch(t){console.error(`[SessionPersister] Failed to delete session ${e}:`,t)}}}__turbopack_context__.s(["SessionPersister",0,SessionPersister],10928);let M=1e6,MODEL_RATES={"claude-fable-5":{input:10/M,output:50/M},"claude-opus-4-8":{input:5/M,output:25/M},"claude-opus-4":{input:15/M,output:75/M},"claude-sonnet-5":{input:2/M,output:10/M},"claude-sonnet-4":{input:3/M,output:15/M},"claude-haiku-4":{input:1/M,output:5/M},"claude-3-5-sonnet":{input:3/M,output:15/M},"claude-3-5-haiku":{input:.8/M,output:4/M},"claude-3-opus":{input:15/M,output:75/M},"gpt-4o":{input:2.5/M,output:10/M},"gpt-4o-mini":{input:.15/M,output:.6/M},"gpt-4-turbo":{input:10/M,output:30/M}},DEFAULT_MODEL="claude-sonnet-5";function getModelRate(e){if(e){let t=e.toLowerCase();if(MODEL_RATES[t])return MODEL_RATES[t];for(let e of Object.keys(MODEL_RATES))if(t.includes(e))return MODEL_RATES[e]}return MODEL_RATES[DEFAULT_MODEL]}function estimateCost(e,t,s){let r=getModelRate(s);return e*r.input+t*r.output}var __TURBOPACK__imported__module__22734__2=__TURBOPACK__imported__module__22734__,__TURBOPACK__imported__module__14747__2=__TURBOPACK__imported__module__14747__,__TURBOPACK__imported__module__46786__=__turbopack_context__.i(46786),__TURBOPACK__imported__module__98003__2=__TURBOPACK__imported__module__98003__;function isWindows(){let proc=eval("process");return"win32"===proc.platform}function findGitBash(){if(!isWindows())return"bash";let e=process.env.PROGRAMFILES||"C:\\Program Files",t=process.env["PROGRAMFILES(X86)"]||"C:\\Program Files (x86)",s=process.env.LOCALAPPDATA||"";return[process.env.WINGMAN_BASH_PATH,__TURBOPACK__imported__module__14747__2.default.join(e,"Git","bin","bash.exe"),__TURBOPACK__imported__module__14747__2.default.join(t,"Git","bin","bash.exe"),s?__TURBOPACK__imported__module__14747__2.default.join(s,"Programs","Git","bin","bash.exe"):""].filter(e=>"string"==typeof e&&""!==e).find(e=>__TURBOPACK__imported__module__22734__2.default.existsSync(e))||null}function findInteractiveShell(){let e=findGitBash();if(e)return e;if(!isWindows())return null;let t=process.env.windir||process.env.SystemRoot||"C:\\Windows",s=__TURBOPACK__imported__module__14747__2.default.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(__TURBOPACK__imported__module__22734__2.default.existsSync(s))return s;let r=process.env.COMSPEC;if(r&&__TURBOPACK__imported__module__22734__2.default.existsSync(r))return r;let i=__TURBOPACK__imported__module__14747__2.default.join(t,"System32","cmd.exe");return __TURBOPACK__imported__module__22734__2.default.existsSync(i)?i:r||"cmd.exe"}let cachedPty=null;function loadNodePty(){return cachedPty||(cachedPty=eval("require")("node-pty")),cachedPty}function loadClaudeExtraFlags(e){if(e)return"--resume";let t=__TURBOPACK__imported__module__14747__2.default.join((0,__TURBOPACK__imported__module__98003__2.getConfigDir)(),"claude.json");if(__TURBOPACK__imported__module__22734__2.default.existsSync(t))try{let e=JSON.parse(__TURBOPACK__imported__module__22734__2.default.readFileSync(t,"utf8"));if(e.extraFlags)return e.extraFlags}catch(e){console.error("Failed to parse Claude configuration:",e)}return""}function windowsPathOverride(){return["C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\MSBuild\\Microsoft\\VisualStudio\\NodeJs",__TURBOPACK__imported__module__14747__2.default.join(__TURBOPACK__imported__module__46786__.default.homedir(),"AppData","Local","npm"),process.env.Path||process.env.PATH||""].filter(Boolean).join(";")}let MAX_LOG_LINES=5e3;class AgentRunner{workspaceRoot;scopedDirs;lastSyncedWorkspaceFolders;tokenUsage={input:0,output:0,cost:0};agentState="idle";model;hasAnalyzedInitialState=!1;stateTimer=null;idleTimer=null;lastLoggedUsage={input:0,output:0,cost:0};resetInitialStateAnalysis(){this.hasAnalyzedInitialState=!1}logTokenUsageUpdate(){if(this.tokenUsage.input===this.lastLoggedUsage.input&&this.tokenUsage.output===this.lastLoggedUsage.output&&this.tokenUsage.cost===this.lastLoggedUsage.cost)return;let e=this.tokenUsage.input-this.lastLoggedUsage.input,t=this.tokenUsage.output-this.lastLoggedUsage.output,s=this.tokenUsage.cost-this.lastLoggedUsage.cost;if(e>0||t>0||s>0)try{let r=(0,__TURBOPACK__imported__module__98003__.getConfigDir)(),i=__TURBOPACK__imported__module__14747__.default.join(r,"token-history.json"),o=[];if(__TURBOPACK__imported__module__22734__.default.existsSync(i))try{o=JSON.parse(__TURBOPACK__imported__module__22734__.default.readFileSync(i,"utf8"))||[]}catch{o=[]}o.push({timestamp:new Date().toISOString(),sessionId:this.id,sessionName:this.name,type:this.type,inputTokens:e>0?e:0,outputTokens:t>0?t:0,cost:s>0?s:0,totalInput:this.tokenUsage.input,totalOutput:this.tokenUsage.output,totalCost:this.tokenUsage.cost}),__TURBOPACK__imported__module__22734__.default.writeFileSync(i,JSON.stringify(o,null,2),"utf8"),this.lastLoggedUsage={...this.tokenUsage}}catch(e){console.error("[AgentRunner] Failed to log token usage transaction:",e)}}parseTokenUsage(e){let t=e.replace(/\x1b\[[0-9;]*m/g,""),s=t.match(/(?:cost|estimated cost)[:\s]*\$([0-9.]+)/i);s&&(this.tokenUsage.cost=parseFloat(s[1]));let r=e=>(e=e.replace(/,/g,"").toLowerCase().trim()).endsWith("k")?1e3*parseFloat(e.slice(0,-1)):e.endsWith("m")?1e6*parseFloat(e.slice(0,-1)):parseInt(e,10)||0,i=/tokens?[:\s]*([0-9,.]+[km]?)\s*(?:sent|input|prompt)[^a-zA-Z0-9]+([0-9,.]+[km]?)\s*(?:received|output|completion)/i,o=t.match(i);if(o)this.tokenUsage.input=r(o[1]),this.tokenUsage.output=r(o[2]);else{let e=t.match(/([0-9,.]+[km]?)\s*(?:sent|input|prompt)\s*tokens?/i)||t.match(/tokens?\s*(?:sent|input|prompt)[:\s]*([0-9,.]+[km]?)/i);e&&(this.tokenUsage.input=r(e[1]));let s=t.match(/([0-9,.]+[km]?)\s*(?:received|output|completion)\s*tokens?/i)||t.match(/tokens?\s*(?:received|output|completion)[:\s]*([0-9,.]+[km]?)/i);s&&(this.tokenUsage.output=r(s[1]))}0===this.tokenUsage.cost&&(this.tokenUsage.input>0||this.tokenUsage.output>0)&&(this.tokenUsage.cost=estimateCost(this.tokenUsage.input,this.tokenUsage.output,this.model)),this.logTokenUsageUpdate()}getStatus(){return this.hasAnalyzedInitialState||"running"!==this.status||(this.analyzeState(),this.hasAnalyzedInitialState=!0),{id:this.id,name:this.name,type:this.type,status:this.status,createdAt:this.createdAt,logsCount:this.logs.length,workspaceRoot:this.workspaceRoot||("shell"===this.type?process.env.ORIGINAL_CWD||process.cwd():void 0),scopedDirs:this.scopedDirs,lastSyncedWorkspaceFolders:this.lastSyncedWorkspaceFolders,tokenUsage:this.tokenUsage,agentState:this.agentState,model:this.model}}resize(e,t){}getPid(){}listeners=[];onOutput(e){this.listeners.push(e)}offOutput(e){this.listeners=this.listeners.filter(t=>t!==e)}emitOutput(e){this.updateAgentState(e),this.listeners.forEach(t=>t(e))}parseTokensOnLog=!0;persistOnLog=!0;appendLog(e){this.logs.push(e),this.logs.length>MAX_LOG_LINES&&this.logs.shift(),this.parseTokensOnLog&&this.parseTokenUsage(e),this.emitOutput(e),this.persistOnLog&&SessionPersister.saveSession(this)}async writeToPty(e,t){if(!e)return;let s=isWindows(),r=t.includes("\x1b[200~");if(s&&t.length>100&&!r){let s=128;for(let r=0;r<t.length;r+=s){let i=t.slice(r,r+s);e.write(i),await new Promise(e=>setTimeout(e,10))}}else e.write(t)}updateAgentState(e){if("running"!==this.status){this.agentState="idle";return}let t=/\[Telemetry\]/i.test(e);e.trim().length>0&&!t&&(this.agentState="thinking"),this.stateTimer&&clearTimeout(this.stateTimer),this.stateTimer=setTimeout(()=>{this.analyzeState()},800)}analyzeState(){if("running"!==this.status){this.agentState="idle";return}let e=this.logs.filter(e=>!/\[Telemetry\]/i.test(e)).slice(-5).join("").replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"").trim(),t=e.endsWith(">")||e.endsWith("> ")||/([a-zA-Z0-9_-]+>\s*)$/.test(e)||e.endsWith("$")||e.endsWith("$ "),s=/(\[y\/n\]|\(y\/n\)|\?|confirm|allow|should I|would you|press enter|proceed)/i.test(e);t?("thinking"===this.agentState||"needs-input"===this.agentState)&&(this.agentState="complete",this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{"complete"===this.agentState&&(this.agentState="idle")},5e3)):s&&(this.agentState="needs-input")}}class MockRunner extends AgentRunner{id;name;type="mock";status="idle";createdAt;logs=[];intervalId=null;awaitingConfirmation=!1;mockSteps=["[NeuralLoom] Loading virtual PTY context...","[NeuralLoom] Spawning sandbox mock runtime environment...","[Mock Agent] Model online (v2.0-mock-flash). Dedicated memory allocated.","[Mock Agent] System rules parsed successfully from global context registry.","[Mock Agent] Awaiting developer commands. Type '/help' to list mock skills.","mock-agent> "];stepIndex=0;constructor(e,t){super(),this.id=e,this.name=t||`Mock Session ${e.substring(0,8)}`,this.createdAt=new Date().toISOString()}appendLog(e){this.logs.push(e),this.parseTokenUsage(e),this.emitOutput(e+"\r\n"),SessionPersister.saveSession(this)}async start(e){"running"!==this.status&&(this.status="running",this.appendLog("\x1b[1;35m==================================================\x1b[0m"),this.appendLog("\x1b[1;36m NEURALLOOM SIMULATED AGENT ENVIRONMENT \x1b[0m"),this.appendLog("\x1b[1;35m==================================================\x1b[0m"),this.stepIndex<this.mockSteps.length&&this.appendLog(this.mockSteps[this.stepIndex++]),this.intervalId=setInterval(()=>{if(this.tokenUsage.input+=Math.floor(50*Math.random())+10,this.tokenUsage.output+=Math.floor(20*Math.random())+5,this.tokenUsage.cost=3e-6*this.tokenUsage.input+15e-6*this.tokenUsage.output,this.stepIndex<this.mockSteps.length)this.appendLog(this.mockSteps[this.stepIndex++]);else{let e=new Date().toLocaleTimeString();this.appendLog(`[${e}] [Telemetry] CPU utilization 1.2% | Memory 142MB | Link stable.`)}},4e3))}async stop(){this.status="stopped",this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.appendLog("\x1b[1;31m[System] Process terminated. Connection closed.\x1b[0m")}async sendInput(e,t){"running"!==this.status?this.appendLog(`\x1b[1;31m[Error] Cannot write input: process is ${this.status}.\x1b[0m`):(this.appendLog(`\x1b[1;32m> ${e}\x1b[0m`),setTimeout(()=>{let t=e.trim().toLowerCase();if(this.awaitingConfirmation){if("y"===t||"yes"===t)this.appendLog("[Mock Agent] Proceeding with production deployment..."),setTimeout(()=>{this.appendLog("[Mock Agent] Deploying build artifacts to edge network..."),this.appendLog("[Mock Agent] Deployment complete. Site live!"),this.appendLog("mock-agent> ")},1e3);else{if("n"!==t&&"no"!==t)return void this.appendLog("[Mock Agent] Invalid input. Please confirm with y/n:");this.appendLog("[Mock Agent] Deployment aborted."),this.appendLog("mock-agent> ")}this.awaitingConfirmation=!1;return}"/help"===t?(this.appendLog("[Mock Agent] Available commands:"),this.appendLog(" /help - List available mock commands."),this.appendLog(" /status - Fetch current agent diagnostic metrics."),this.appendLog(" /context - View loaded staging files."),this.appendLog(" /deploy - Trigger production deployment wizard (requires confirmation)."),this.appendLog(" /clear - Flush terminal console buffer."),this.appendLog("mock-agent> ")):"/status"===t?(this.appendLog("[Mock Agent] Diagnostics:"),this.appendLog(" - Connection Type: WebSocket gateway (mock)"),this.appendLog(` - Active Runtime: ${this.id}`),this.appendLog(" - Sandbox State: Healthy (0 warnings)"),this.appendLog("mock-agent> ")):"/context"===t?(this.appendLog("[Mock Agent] Loaded Workspace Context Files:"),this.appendLog(" - [Mounted] src/app/globals.css (Modified)"),this.appendLog(" - [Mounted] src/app/page.tsx"),this.appendLog("mock-agent> ")):"/deploy"===t?(this.appendLog("[Mock Agent] Starting production deployment..."),this.appendLog("[Mock Agent] Warning: This will push current local build to server."),this.appendLog("[Mock Agent] Are you sure you want to proceed? (y/n)"),this.awaitingConfirmation=!0):"/clear"===t?(this.logs=[],this.appendLog("\x1b[1;33m[Console Cleared]\x1b[0m"),this.appendLog("mock-agent> ")):(this.appendLog(`[Mock Agent] Received command: "${e}". Processing...`),setTimeout(()=>{this.appendLog("[Mock Agent] Done. Task simulated successfully."),this.appendLog("mock-agent> ")},1500))},400))}}var __TURBOPACK__imported__module__22734__3=__TURBOPACK__imported__module__22734__,__TURBOPACK__imported__module__33405__=__turbopack_context__.i(33405);let CLAUDE_MODELS=[{alias:"",label:"Default (account)",versions:[]},{alias:"opus",label:"Opus (latest)",versions:["claude-opus-4-8"]},{alias:"sonnet",label:"Sonnet (latest)",versions:["claude-sonnet-5"]},{alias:"haiku",label:"Haiku (latest)",versions:["claude-haiku-4-5-20251001"]},{alias:"fable",label:"Fable (latest)",versions:["claude-fable-5"]}],CUSTOM_MODEL="__custom__";function sanitizeModelArg(e){if(!e)return;let t=e.trim();if(t&&/^[A-Za-z0-9._:-]+$/.test(t))return t}function modelLabel(e){let t=sanitizeModelArg(e);if(!t)return"Default";let s=CLAUDE_MODELS.find(e=>e.alias===t||e.versions.includes(t));return s&&s.alias?s.label:t}class ClaudeRunner extends AgentRunner{id;name;type="claude";status="idle";createdAt;logs=[];ptyProcess=null;ptyModule=null;constructor(e,t){super(),this.id=e,this.name=t||`Claude Session ${e.substring(0,8)}`,this.createdAt=new Date().toISOString()}async start(e){if("running"===this.status)return;let t=isWindows(),s=t?process.env.COMSPEC||"cmd.exe":findGitBash();if(!s){this.status="stopped",this.appendLog("\x1b[1;31m[System Error] Shell not found. Cannot spawn terminal.\x1b[0m\r\n");return}let r=t?["/c"]:["-c"];try{this.ptyModule=loadNodePty(),this.status="running",this.appendLog("\x1b[1;35m==================================================\x1b[0m\r\n"),this.appendLog("\x1b[1;36m NEURALLOOM ACTIVE CLAUDE TERMINAL ROUTE \x1b[0m\r\n"),this.appendLog("\x1b[1;35m==================================================\x1b[0m\r\n");let t=this.workspaceRoot&&__TURBOPACK__imported__module__22734__3.default.existsSync(this.workspaceRoot)?this.workspaceRoot:process.env.ORIGINAL_CWD||process.cwd(),i=loadClaudeExtraFlags(e),o={...process.env,TERM:"xterm-256color",COLORTERM:"truecolor",CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN:"1"};if(isWindows()){let e=windowsPathOverride();for(let e of Object.keys(o))"path"===e.toLowerCase()&&delete o[e];o.Path=e,o.PATH=e}let n="claude";try{let e=isWindows()?"where.exe claude":"which claude";(0,__TURBOPACK__imported__module__33405__.execSync)(e,{env:o,stdio:"ignore"})}catch{n="npx -y @anthropic-ai/claude-code"}let a=sanitizeModelArg(this.model),l=a?`--model ${a}`:"",c=`${n} ${l} ${i}`.replace(/\s+/g," ").trim();this.appendLog(`[System] Spawning command: ${c}\r
|
|
3
3
|
`),this.ptyProcess=this.ptyModule.spawn(s,[...r,c],{name:"xterm-256color",cols:120,rows:30,cwd:t,env:o}),this.ptyProcess.onData(e=>{this.appendLog(e)}),this.ptyProcess.onExit(({exitCode:e,signal:t})=>{this.status="stopped",this.appendLog(`\r
|
|
4
4
|
\x1b[1;31m[System] Claude Code PTY process exited (code=${e}, signal=${t}).\x1b[0m\r
|
|
5
5
|
`),this.ptyProcess=null})}catch(t){let e=t instanceof Error?t.message:"Unknown error";this.status="stopped",this.appendLog(`\x1b[1;31m[System Error] Failed to initialize node-pty runner: ${e}\x1b[0m\r
|